qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
7,858,228 | This is just an academic question (I would never do this in real code):
**If I were to use shared\_ptr<> universally in my code, would the behavior be equivalent to a gc-collected language like Java?**
If not, how would the behavior be different from a gc-embedded language? Which C++ construct would yield equivalent behavior compared to a gc-embedded language?
Note: In real coding, I strongly prefer the use of RAII and strict ownership over the use of any smart pointers. I also know that other less-generic pointers, unique\_ptr<> would be more efficient. This question is just a query into smart-pointer equivalence. | 2011/10/22 | [
"https://Stackoverflow.com/questions/7858228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/975129/"
] | No, there'd be a couple of important differences:
* You would get a memory leak any time you have a cyclic reference. A garbage collector can handle cycles, ref-counting can't.
* You would avoid any stalls or pauses because no garbage collection ever occurs. On the other hand, you'd likely spend more total CPU time cleaning up resources, because the amortized cost of an occasional garbage collection is pretty low, and ref-counting can be relatively expensive if you do it on everything.
Obviously the first point is the killer. If you did this, many of your resources wouldn't get freed, and you'd leak memory and your app just wouldn't behave very well.
>
> Which C++ construct would yield equivalent behavior compared to a gc-embedded language?
>
>
>
None. C++ doesn't have a garbage collector because there's no way to implement a correct, reliable one. (Yes, I'm aware of Boehm's GC, and it's a good approximation, but it's conservative, and doesn't detect all references, only the ones it can be 100% sure of. There is no way, in a general C++ program, to implement a garbage collector that Just Works(tm)) | The main difference is that reference counting alone can't free circular data structures.
Many cases of such structures can nevertheless be handled by using `weak_ptr` appropriately, and some cases can be handled by delegating cleanup responsibility to a collection object.
However, the most frivolous spaghetti structures, if you want them (e.g. for math), can't have automated cleanup implemented by reference counting alone, because there will be circular sub-structures.
Cheers & hth., |
7,858,228 | This is just an academic question (I would never do this in real code):
**If I were to use shared\_ptr<> universally in my code, would the behavior be equivalent to a gc-collected language like Java?**
If not, how would the behavior be different from a gc-embedded language? Which C++ construct would yield equivalent behavior compared to a gc-embedded language?
Note: In real coding, I strongly prefer the use of RAII and strict ownership over the use of any smart pointers. I also know that other less-generic pointers, unique\_ptr<> would be more efficient. This question is just a query into smart-pointer equivalence. | 2011/10/22 | [
"https://Stackoverflow.com/questions/7858228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/975129/"
] | No, there'd be a couple of important differences:
* You would get a memory leak any time you have a cyclic reference. A garbage collector can handle cycles, ref-counting can't.
* You would avoid any stalls or pauses because no garbage collection ever occurs. On the other hand, you'd likely spend more total CPU time cleaning up resources, because the amortized cost of an occasional garbage collection is pretty low, and ref-counting can be relatively expensive if you do it on everything.
Obviously the first point is the killer. If you did this, many of your resources wouldn't get freed, and you'd leak memory and your app just wouldn't behave very well.
>
> Which C++ construct would yield equivalent behavior compared to a gc-embedded language?
>
>
>
None. C++ doesn't have a garbage collector because there's no way to implement a correct, reliable one. (Yes, I'm aware of Boehm's GC, and it's a good approximation, but it's conservative, and doesn't detect all references, only the ones it can be 100% sure of. There is no way, in a general C++ program, to implement a garbage collector that Just Works(tm)) | Its worth noting that a shared ptr is much larger that a Java reference. Generally this won't matter but some situations it might.
In Java 6, 64-bit JVMs still use 32-bit references access up to 32 GB of heap (it can do this because objects are on 8 byte boundaries) However a shared ptr uses two pointers (each 8 bytes in a 64-bit applications), the second pointer references an object which contains the counter. On libgcc it allocates 32-byte minimum to any malloc/new object. In total the shared pointer could be using 48 bytes which is relatively larger than 4 bytes. 44 bytes is not going to make a difference, but it could if you have lots of these. |
7,858,228 | This is just an academic question (I would never do this in real code):
**If I were to use shared\_ptr<> universally in my code, would the behavior be equivalent to a gc-collected language like Java?**
If not, how would the behavior be different from a gc-embedded language? Which C++ construct would yield equivalent behavior compared to a gc-embedded language?
Note: In real coding, I strongly prefer the use of RAII and strict ownership over the use of any smart pointers. I also know that other less-generic pointers, unique\_ptr<> would be more efficient. This question is just a query into smart-pointer equivalence. | 2011/10/22 | [
"https://Stackoverflow.com/questions/7858228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/975129/"
] | No, there'd be a couple of important differences:
* You would get a memory leak any time you have a cyclic reference. A garbage collector can handle cycles, ref-counting can't.
* You would avoid any stalls or pauses because no garbage collection ever occurs. On the other hand, you'd likely spend more total CPU time cleaning up resources, because the amortized cost of an occasional garbage collection is pretty low, and ref-counting can be relatively expensive if you do it on everything.
Obviously the first point is the killer. If you did this, many of your resources wouldn't get freed, and you'd leak memory and your app just wouldn't behave very well.
>
> Which C++ construct would yield equivalent behavior compared to a gc-embedded language?
>
>
>
None. C++ doesn't have a garbage collector because there's no way to implement a correct, reliable one. (Yes, I'm aware of Boehm's GC, and it's a good approximation, but it's conservative, and doesn't detect all references, only the ones it can be 100% sure of. There is no way, in a general C++ program, to implement a garbage collector that Just Works(tm)) | @jalf says this in his answer:
>
> You would avoid any stalls or pauses because no garbage collection ever occurs.
>
>
>
While smart pointers (or any reference counting scheme) have no pause while garbage collection occurs, you *can* get a pause if you null the last external pointer to a large data structure, and trigger a cascade of reference count adjustments and finalizations for each node in the data structure. While a smart smart-pointer implementation could ameliorate this, you'd be sacrificing immediate reclamation ... which some people claim is an advantage of smart pointers.
Also, there is an overhead of a few instructions each time you assign to a smart pointer-typed variable, and the overheads of allocating an object is greater. |
7,858,228 | This is just an academic question (I would never do this in real code):
**If I were to use shared\_ptr<> universally in my code, would the behavior be equivalent to a gc-collected language like Java?**
If not, how would the behavior be different from a gc-embedded language? Which C++ construct would yield equivalent behavior compared to a gc-embedded language?
Note: In real coding, I strongly prefer the use of RAII and strict ownership over the use of any smart pointers. I also know that other less-generic pointers, unique\_ptr<> would be more efficient. This question is just a query into smart-pointer equivalence. | 2011/10/22 | [
"https://Stackoverflow.com/questions/7858228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/975129/"
] | Garbage collection happens whenever the GC decides that it should. `shared_ptr`s are not collected. An object managed by a `shared_ptr` will only *ever* be destroyed in the destructor of a `shared_ptr`. And therefore, you know exactly when memory can and can *not* be freed.
You still have control over when memory goes away with `shared_ptr`. You don't have that with a garbage collector (outside of coarse-grained commands like turning it on/off or modifying it's behavior a bit). | Its worth noting that a shared ptr is much larger that a Java reference. Generally this won't matter but some situations it might.
In Java 6, 64-bit JVMs still use 32-bit references access up to 32 GB of heap (it can do this because objects are on 8 byte boundaries) However a shared ptr uses two pointers (each 8 bytes in a 64-bit applications), the second pointer references an object which contains the counter. On libgcc it allocates 32-byte minimum to any malloc/new object. In total the shared pointer could be using 48 bytes which is relatively larger than 4 bytes. 44 bytes is not going to make a difference, but it could if you have lots of these. |
7,858,228 | This is just an academic question (I would never do this in real code):
**If I were to use shared\_ptr<> universally in my code, would the behavior be equivalent to a gc-collected language like Java?**
If not, how would the behavior be different from a gc-embedded language? Which C++ construct would yield equivalent behavior compared to a gc-embedded language?
Note: In real coding, I strongly prefer the use of RAII and strict ownership over the use of any smart pointers. I also know that other less-generic pointers, unique\_ptr<> would be more efficient. This question is just a query into smart-pointer equivalence. | 2011/10/22 | [
"https://Stackoverflow.com/questions/7858228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/975129/"
] | The main difference is that reference counting alone can't free circular data structures.
Many cases of such structures can nevertheless be handled by using `weak_ptr` appropriately, and some cases can be handled by delegating cleanup responsibility to a collection object.
However, the most frivolous spaghetti structures, if you want them (e.g. for math), can't have automated cleanup implemented by reference counting alone, because there will be circular sub-structures.
Cheers & hth., | Its worth noting that a shared ptr is much larger that a Java reference. Generally this won't matter but some situations it might.
In Java 6, 64-bit JVMs still use 32-bit references access up to 32 GB of heap (it can do this because objects are on 8 byte boundaries) However a shared ptr uses two pointers (each 8 bytes in a 64-bit applications), the second pointer references an object which contains the counter. On libgcc it allocates 32-byte minimum to any malloc/new object. In total the shared pointer could be using 48 bytes which is relatively larger than 4 bytes. 44 bytes is not going to make a difference, but it could if you have lots of these. |
7,858,228 | This is just an academic question (I would never do this in real code):
**If I were to use shared\_ptr<> universally in my code, would the behavior be equivalent to a gc-collected language like Java?**
If not, how would the behavior be different from a gc-embedded language? Which C++ construct would yield equivalent behavior compared to a gc-embedded language?
Note: In real coding, I strongly prefer the use of RAII and strict ownership over the use of any smart pointers. I also know that other less-generic pointers, unique\_ptr<> would be more efficient. This question is just a query into smart-pointer equivalence. | 2011/10/22 | [
"https://Stackoverflow.com/questions/7858228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/975129/"
] | @jalf says this in his answer:
>
> You would avoid any stalls or pauses because no garbage collection ever occurs.
>
>
>
While smart pointers (or any reference counting scheme) have no pause while garbage collection occurs, you *can* get a pause if you null the last external pointer to a large data structure, and trigger a cascade of reference count adjustments and finalizations for each node in the data structure. While a smart smart-pointer implementation could ameliorate this, you'd be sacrificing immediate reclamation ... which some people claim is an advantage of smart pointers.
Also, there is an overhead of a few instructions each time you assign to a smart pointer-typed variable, and the overheads of allocating an object is greater. | Its worth noting that a shared ptr is much larger that a Java reference. Generally this won't matter but some situations it might.
In Java 6, 64-bit JVMs still use 32-bit references access up to 32 GB of heap (it can do this because objects are on 8 byte boundaries) However a shared ptr uses two pointers (each 8 bytes in a 64-bit applications), the second pointer references an object which contains the counter. On libgcc it allocates 32-byte minimum to any malloc/new object. In total the shared pointer could be using 48 bytes which is relatively larger than 4 bytes. 44 bytes is not going to make a difference, but it could if you have lots of these. |
12,379,253 | I am still a java newbie and trying to play around learning threads. My question is that it does not loop 5 times. It runs one time and exits. I am using a.class to lock on the class object, such that both the threads are locking on the same object monitor.
```
class a implements Runnable {
Thread thr;
int count;
String time;
a(String s) {
thr = new Thread(this, s);
thr.start();
}
public void run() {
count++;
if (Thread.currentThread().getName().compareTo("one") == 0) {
synchronized (a.class) {
try {
for (int i = 0; i < 5; i++) {
System.out.println("Now running thread " + Thread.currentThread().getName() + " with count " + count);
time = "Tick";
System.out.println(time);
notify();
while (time == "Tock") {
wait();
}
}
} catch (Exception e) {
}
}
} else if (Thread.currentThread().getName().compareTo("two") == 0) {
synchronized (a.class) {
try {
for (int j = 0; j < 5; j++) {
System.out.println("Now running thread " + Thread.currentThread().getName() + " with count " + count);
time = "Tock";
System.out.println(time);
notify();
while (time == "Tick") {
wait();
}
}
} catch (Exception e) {
}
}
}
}
}
public class b {
public static void main(String args[]) {
a obj1 = new a("one");
a obj2 = new a("two");
}
}
``` | 2012/09/11 | [
"https://Stackoverflow.com/questions/12379253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/547453/"
] | Here you go, with the original code:
```
class a implements Runnable {
Thread thr;
int count;
static String time = "Tock";
a(String s) {
thr = new Thread(this, s);
thr.start();
}
public void run() {
count++;
if (Thread.currentThread().getName().compareTo("one") == 0) {
synchronized (a.class) {
try {
for (int i = 0; i < 5; i++) {
while (time.equals("Tock")) {
a.class.wait();
}
System.out.println("Now running thread "
+ Thread.currentThread().getName()
+ " with count " + count);
time = "Tock";
System.out.println(time);
a.class.notify();
}
} catch (Exception e) {
e.printStackTrace();
}
}
} else if (Thread.currentThread().getName().compareTo("two") == 0) {
synchronized (a.class) {
try {
for (int j = 0; j < 5; j++) {
while (time.equals("Tick")) {
a.class.wait();
}
System.out.println("Now running thread "
+ Thread.currentThread().getName()
+ " with count " + count);
time = "Tick";
System.out.println(time);
a.class.notify();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public class Test {
public static void main(String args[]) {
a obj1 = new a("one");
a obj2 = new a("two");
}
}
```
The problem was that you were calling `wait` and `notify` on the implicit `this` object, when the lock was being held on the `a.class` object, hence you must call `wait/notify` on `a.class`. That was it.
I also did a small restructuring, since I assume you wanted them to print `Tick` and `Tock` in an alternating sequence, right? | When comparing strings (and objects in general), you should use `equals` as opposed to `==` (which is generally reserved for primitives): `while(time.equals("Tock"))`. `==` on strings will often times result in `false` when you want it to (and think it should) return `true`, and hence your loop will exit before expected. |
12,379,253 | I am still a java newbie and trying to play around learning threads. My question is that it does not loop 5 times. It runs one time and exits. I am using a.class to lock on the class object, such that both the threads are locking on the same object monitor.
```
class a implements Runnable {
Thread thr;
int count;
String time;
a(String s) {
thr = new Thread(this, s);
thr.start();
}
public void run() {
count++;
if (Thread.currentThread().getName().compareTo("one") == 0) {
synchronized (a.class) {
try {
for (int i = 0; i < 5; i++) {
System.out.println("Now running thread " + Thread.currentThread().getName() + " with count " + count);
time = "Tick";
System.out.println(time);
notify();
while (time == "Tock") {
wait();
}
}
} catch (Exception e) {
}
}
} else if (Thread.currentThread().getName().compareTo("two") == 0) {
synchronized (a.class) {
try {
for (int j = 0; j < 5; j++) {
System.out.println("Now running thread " + Thread.currentThread().getName() + " with count " + count);
time = "Tock";
System.out.println(time);
notify();
while (time == "Tick") {
wait();
}
}
} catch (Exception e) {
}
}
}
}
}
public class b {
public static void main(String args[]) {
a obj1 = new a("one");
a obj2 = new a("two");
}
}
``` | 2012/09/11 | [
"https://Stackoverflow.com/questions/12379253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/547453/"
] | Here you go, with the original code:
```
class a implements Runnable {
Thread thr;
int count;
static String time = "Tock";
a(String s) {
thr = new Thread(this, s);
thr.start();
}
public void run() {
count++;
if (Thread.currentThread().getName().compareTo("one") == 0) {
synchronized (a.class) {
try {
for (int i = 0; i < 5; i++) {
while (time.equals("Tock")) {
a.class.wait();
}
System.out.println("Now running thread "
+ Thread.currentThread().getName()
+ " with count " + count);
time = "Tock";
System.out.println(time);
a.class.notify();
}
} catch (Exception e) {
e.printStackTrace();
}
}
} else if (Thread.currentThread().getName().compareTo("two") == 0) {
synchronized (a.class) {
try {
for (int j = 0; j < 5; j++) {
while (time.equals("Tick")) {
a.class.wait();
}
System.out.println("Now running thread "
+ Thread.currentThread().getName()
+ " with count " + count);
time = "Tick";
System.out.println(time);
a.class.notify();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public class Test {
public static void main(String args[]) {
a obj1 = new a("one");
a obj2 = new a("two");
}
}
```
The problem was that you were calling `wait` and `notify` on the implicit `this` object, when the lock was being held on the `a.class` object, hence you must call `wait/notify` on `a.class`. That was it.
I also did a small restructuring, since I assume you wanted them to print `Tick` and `Tock` in an alternating sequence, right? | The answer to why you only loop once is that you call `notify()` on an object that is not locked and thus an `IllegalMonitorStateException` is thrown and caught by the empty catch statement.
This is one way to do it. Not saying that it is the best. I tried to keep it close to your code:
```
public class TickTock {
static final int N = 4;
Object lock = new Object();
int token;
class Worker extends Thread {
int id;
Worker(int id) {
this.id = id;
}
@Override
public void run() {
try {
synchronized (lock) {
for (int i = 0; i < 5; i++) {
while (id != token%N) lock.wait();
System.out.println(id + " " + i);
token++;
lock.notifyAll();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
void start() {
for (int i = 0; i < N; i++) {
new Worker(i).start();
}
}
public static void main(String[] args) {
new TickTock().start();
}
}
``` |
1,079,128 | Looking at options for embedding the 3D Secure page inside my own order form, I came across the following:
"Some commerce sites will devote the full browser page to the authentication rather than using a frame (not necessarily an iFrame, which is a less secure object anyway)."
from <http://en.wikipedia.org/wiki/3-D_Secure>
Can someone give me the lowdown as to ***why*** iframes are less secure, and cause problems, as opposed to normal frames? And what are the basic differences?
The way I see it, `iframe` is the way to go. | 2009/07/03 | [
"https://Stackoverflow.com/questions/1079128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7140/"
] | `iframe`s are used a lot to include complete pages. When those pages are hosted on another domain you get problems with cross side scripting and stuff. There are ways to fix this.
Frames were used to divide your page into multiple parts (for example, a navigation menu on the left). Using them is no longer recommended. | ***Inline frame is just one "box" and you can place it anywhere on your site.
Frames are a bunch of 'boxes' put together to make one site with many pages.*** |
1,079,128 | Looking at options for embedding the 3D Secure page inside my own order form, I came across the following:
"Some commerce sites will devote the full browser page to the authentication rather than using a frame (not necessarily an iFrame, which is a less secure object anyway)."
from <http://en.wikipedia.org/wiki/3-D_Secure>
Can someone give me the lowdown as to ***why*** iframes are less secure, and cause problems, as opposed to normal frames? And what are the basic differences?
The way I see it, `iframe` is the way to go. | 2009/07/03 | [
"https://Stackoverflow.com/questions/1079128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7140/"
] | The difference is an iframe is able to "float" within content in a page, that is you can create an html page and position an iframe within it. This allows you to have a page and place another document directly in it. A `frameset` allows you to split the screen into different pages (horizontally and vertically) and display different documents in each part.
Read [IFrames security summary](http://www.thespanner.co.uk/2007/10/24/iframes-security-summary/). | ***Inline frame is just one "box" and you can place it anywhere on your site.
Frames are a bunch of 'boxes' put together to make one site with many pages.*** |
1,079,128 | Looking at options for embedding the 3D Secure page inside my own order form, I came across the following:
"Some commerce sites will devote the full browser page to the authentication rather than using a frame (not necessarily an iFrame, which is a less secure object anyway)."
from <http://en.wikipedia.org/wiki/3-D_Secure>
Can someone give me the lowdown as to ***why*** iframes are less secure, and cause problems, as opposed to normal frames? And what are the basic differences?
The way I see it, `iframe` is the way to go. | 2009/07/03 | [
"https://Stackoverflow.com/questions/1079128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7140/"
] | The difference is an iframe is able to "float" within content in a page, that is you can create an html page and position an iframe within it. This allows you to have a page and place another document directly in it. A `frameset` allows you to split the screen into different pages (horizontally and vertically) and display different documents in each part.
Read [IFrames security summary](http://www.thespanner.co.uk/2007/10/24/iframes-security-summary/). | `iframe`s are used a lot to include complete pages. When those pages are hosted on another domain you get problems with cross side scripting and stuff. There are ways to fix this.
Frames were used to divide your page into multiple parts (for example, a navigation menu on the left). Using them is no longer recommended. |
1,079,128 | Looking at options for embedding the 3D Secure page inside my own order form, I came across the following:
"Some commerce sites will devote the full browser page to the authentication rather than using a frame (not necessarily an iFrame, which is a less secure object anyway)."
from <http://en.wikipedia.org/wiki/3-D_Secure>
Can someone give me the lowdown as to ***why*** iframes are less secure, and cause problems, as opposed to normal frames? And what are the basic differences?
The way I see it, `iframe` is the way to go. | 2009/07/03 | [
"https://Stackoverflow.com/questions/1079128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7140/"
] | The difference is an iframe is able to "float" within content in a page, that is you can create an html page and position an iframe within it. This allows you to have a page and place another document directly in it. A `frameset` allows you to split the screen into different pages (horizontally and vertically) and display different documents in each part.
Read [IFrames security summary](http://www.thespanner.co.uk/2007/10/24/iframes-security-summary/). | While the security is the same, it may be easier for fraudulent applications to dupe users using an iframe since they have more flexibility regarding where the frame is placed. |
1,079,128 | Looking at options for embedding the 3D Secure page inside my own order form, I came across the following:
"Some commerce sites will devote the full browser page to the authentication rather than using a frame (not necessarily an iFrame, which is a less secure object anyway)."
from <http://en.wikipedia.org/wiki/3-D_Secure>
Can someone give me the lowdown as to ***why*** iframes are less secure, and cause problems, as opposed to normal frames? And what are the basic differences?
The way I see it, `iframe` is the way to go. | 2009/07/03 | [
"https://Stackoverflow.com/questions/1079128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7140/"
] | `iframe`s are used a lot to include complete pages. When those pages are hosted on another domain you get problems with cross side scripting and stuff. There are ways to fix this.
Frames were used to divide your page into multiple parts (for example, a navigation menu on the left). Using them is no longer recommended. | While the security is the same, it may be easier for fraudulent applications to dupe users using an iframe since they have more flexibility regarding where the frame is placed. |
1,079,128 | Looking at options for embedding the 3D Secure page inside my own order form, I came across the following:
"Some commerce sites will devote the full browser page to the authentication rather than using a frame (not necessarily an iFrame, which is a less secure object anyway)."
from <http://en.wikipedia.org/wiki/3-D_Secure>
Can someone give me the lowdown as to ***why*** iframes are less secure, and cause problems, as opposed to normal frames? And what are the basic differences?
The way I see it, `iframe` is the way to go. | 2009/07/03 | [
"https://Stackoverflow.com/questions/1079128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7140/"
] | `iframe`s are used a lot to include complete pages. When those pages are hosted on another domain you get problems with cross side scripting and stuff. There are ways to fix this.
Frames were used to divide your page into multiple parts (for example, a navigation menu on the left). Using them is no longer recommended. | The only reasons I can think of are actually in the [wiki article you referenced](http://en.wikipedia.org/wiki/3-D_Secure) to mention a couple...
>
> "The "Verified by Visa" system has drawn some criticism, since it is
> hard for users to differentiate between the legitimate Verified by
> Visa pop-up window or inline frame, and a fraudulent phishing site."
>
>
> "as of 2008, most web browsers do not provide a simple way to check
> the security certificate for the contents of an iframe"
>
>
>
If you read the [**Criticism** section](http://en.wikipedia.org/wiki/3-D_Secure#Criticism) in the article it details all the potential security flaws.
Otherwise the only difference is the fact that an **IFrame** is an inline frame and a **Frame** is part of a **Frameset**. Which means more layout problems than anything else! |
1,079,128 | Looking at options for embedding the 3D Secure page inside my own order form, I came across the following:
"Some commerce sites will devote the full browser page to the authentication rather than using a frame (not necessarily an iFrame, which is a less secure object anyway)."
from <http://en.wikipedia.org/wiki/3-D_Secure>
Can someone give me the lowdown as to ***why*** iframes are less secure, and cause problems, as opposed to normal frames? And what are the basic differences?
The way I see it, `iframe` is the way to go. | 2009/07/03 | [
"https://Stackoverflow.com/questions/1079128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7140/"
] | IFrame is just an "internal frame". The reason why it can be considered less secure (than not using any kind of frame at all) is because you can include content that does not originate from your domain.
All this means is that you should trust whatever you include in an iFrame or a regular frame.
Frames and IFrames are equally secure (and insecure if you include content from an untrusted source). | While the security is the same, it may be easier for fraudulent applications to dupe users using an iframe since they have more flexibility regarding where the frame is placed. |
1,079,128 | Looking at options for embedding the 3D Secure page inside my own order form, I came across the following:
"Some commerce sites will devote the full browser page to the authentication rather than using a frame (not necessarily an iFrame, which is a less secure object anyway)."
from <http://en.wikipedia.org/wiki/3-D_Secure>
Can someone give me the lowdown as to ***why*** iframes are less secure, and cause problems, as opposed to normal frames? And what are the basic differences?
The way I see it, `iframe` is the way to go. | 2009/07/03 | [
"https://Stackoverflow.com/questions/1079128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7140/"
] | The only reasons I can think of are actually in the [wiki article you referenced](http://en.wikipedia.org/wiki/3-D_Secure) to mention a couple...
>
> "The "Verified by Visa" system has drawn some criticism, since it is
> hard for users to differentiate between the legitimate Verified by
> Visa pop-up window or inline frame, and a fraudulent phishing site."
>
>
> "as of 2008, most web browsers do not provide a simple way to check
> the security certificate for the contents of an iframe"
>
>
>
If you read the [**Criticism** section](http://en.wikipedia.org/wiki/3-D_Secure#Criticism) in the article it details all the potential security flaws.
Otherwise the only difference is the fact that an **IFrame** is an inline frame and a **Frame** is part of a **Frameset**. Which means more layout problems than anything else! | While the security is the same, it may be easier for fraudulent applications to dupe users using an iframe since they have more flexibility regarding where the frame is placed. |
1,079,128 | Looking at options for embedding the 3D Secure page inside my own order form, I came across the following:
"Some commerce sites will devote the full browser page to the authentication rather than using a frame (not necessarily an iFrame, which is a less secure object anyway)."
from <http://en.wikipedia.org/wiki/3-D_Secure>
Can someone give me the lowdown as to ***why*** iframes are less secure, and cause problems, as opposed to normal frames? And what are the basic differences?
The way I see it, `iframe` is the way to go. | 2009/07/03 | [
"https://Stackoverflow.com/questions/1079128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7140/"
] | Basically the difference between `<frame>` tag and `<iframe>` tag is :
When we use `<frame>` tag then the content of a web page constitutes of frames which is created by using `<frame>` and `<frameset>` tags only (*and `<body>` tag is not used*) as :
```
<html>
<head>
<title>HTML Frames</title>
</head>
<frameset rows="20%,70%,10%">
<frame name="top" src="/html/top.html" />
<frame name="main" src="/html/main.html" />
<frame name="bottom" src="/html/bottom.html" />
</frameset>
</html>
```
And when we use `<iframe>` then the content of web page don't contain frames and content of web page is created by using `<body>` tag (*and `<frame>` and `<frameset>` tags are not used*) as:
```
<html>
<head>
<title>HTML Iframes</title>
</head>
<body>
<p>See the video</p>
<iframe width="854" height="480" src="https://www.youtube.com/embed/2eabXBvw4oI"
frameborder="0" allowfullscreen>
</iframe>
</body>
</html>
```
So `<iframe>` just brings some other source's document to a web page. The `<iframe>` are used to specify **inline frames** or **floating frames**. The World Wide Web Consortium (W3C) included the `<iframe>` feature in HTML 4.01.
`<frameset>` tags were used to create frames with the tag `<frame>` whereas `<iframe>` fulfills functions of both `<frame>` and `<frameset>` tags. Unlike `<frame>` tags, `<iframe>` tags can also be placed inside the `<body>` tags.
Placement of `<iframe>` is easy, a coder can easily put the `<iframe>` tag among the other webpage tags, and also add several `<iframe>` tags if he/she wants. On the other hand, placing `<frame>` tags in `<frameset>` is bit complicated.
**Note :** `<frame>` tag and `<frameset>` tag are deprecated in HTML5
So now as use of `<frame>` and `<frameset>` tag is deprecated so web developers use `<body>` tag for creating content of a webpage and for embedding some other source's document in the web page `<iframe>` tags are used. But even `<frame>` tags were also used to embed other source's document in a webpage and even `<iframe>` tags are also used to create frames. | ***Inline frame is just one "box" and you can place it anywhere on your site.
Frames are a bunch of 'boxes' put together to make one site with many pages.*** |
1,079,128 | Looking at options for embedding the 3D Secure page inside my own order form, I came across the following:
"Some commerce sites will devote the full browser page to the authentication rather than using a frame (not necessarily an iFrame, which is a less secure object anyway)."
from <http://en.wikipedia.org/wiki/3-D_Secure>
Can someone give me the lowdown as to ***why*** iframes are less secure, and cause problems, as opposed to normal frames? And what are the basic differences?
The way I see it, `iframe` is the way to go. | 2009/07/03 | [
"https://Stackoverflow.com/questions/1079128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7140/"
] | ***Inline frame is just one "box" and you can place it anywhere on your site.
Frames are a bunch of 'boxes' put together to make one site with many pages.*** | While the security is the same, it may be easier for fraudulent applications to dupe users using an iframe since they have more flexibility regarding where the frame is placed. |
12,761,916 | >
> **Possible Duplicate:**
>
> [Difference between char \*str=“STRING” and char str[] = “STRING”?](https://stackoverflow.com/questions/3862842/difference-between-char-str-string-and-char-str-string)
>
>
>
I wrote the following code:
```
int main()
{
char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
```
This gives me a segmentation fault, I cant understand why.
`str` is `pointer to char` not `const char`. Even if that's the case shouldn't it give a compile error like the following program:
```
int main()
{
const char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
```
It gives an error: `assignment of read-only location *str`.
**EDIT**
If my code places the pointer to a read only location, shouldn't I get a compilation error? | 2012/10/06 | [
"https://Stackoverflow.com/questions/12761916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032610/"
] | You assign a pointer to a constant string (which comes as a part of your text and is thus not writable memory).
Fix with `char str[] = "hello";` this will create a r/w copy of the constant string on your stack.
What you do is a perfectly valid pointer assignment. What the compiler does not know is that in a standard system constant strings are placed in read-only memory. On embedded (or other weird) systems this may be different.
Depending on your system you could come with an `mprotect` and change the VM flags on your pointer destination to writable. So the compiler allows for this code, your OS does not though. | When you initialize a `char *` using a literal string, then you shouldn't try to modify it's contents: the variable is pointing to memory that doesn't belong to you.
You *can* use:
```
char str[] = "hello";
str[0] = 'H';
```
With this code you've declared an array which is initialized with a copy of the literal string's contents, and now you can modify the array. |
12,761,916 | >
> **Possible Duplicate:**
>
> [Difference between char \*str=“STRING” and char str[] = “STRING”?](https://stackoverflow.com/questions/3862842/difference-between-char-str-string-and-char-str-string)
>
>
>
I wrote the following code:
```
int main()
{
char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
```
This gives me a segmentation fault, I cant understand why.
`str` is `pointer to char` not `const char`. Even if that's the case shouldn't it give a compile error like the following program:
```
int main()
{
const char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
```
It gives an error: `assignment of read-only location *str`.
**EDIT**
If my code places the pointer to a read only location, shouldn't I get a compilation error? | 2012/10/06 | [
"https://Stackoverflow.com/questions/12761916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032610/"
] | You assign a pointer to a constant string (which comes as a part of your text and is thus not writable memory).
Fix with `char str[] = "hello";` this will create a r/w copy of the constant string on your stack.
What you do is a perfectly valid pointer assignment. What the compiler does not know is that in a standard system constant strings are placed in read-only memory. On embedded (or other weird) systems this may be different.
Depending on your system you could come with an `mprotect` and change the VM flags on your pointer destination to writable. So the compiler allows for this code, your OS does not though. | Your code has undefined behavior in runtime. You are attempting to write to a literal string, which is not allowed. Such writes may trigger an error or have undefined behavior. Your specific C compiler has `str` point to read-only memory, and attempting to write to that memory leads to a segmentation fault. Even though it's not `const`, the write is still not allowed. |
12,761,916 | >
> **Possible Duplicate:**
>
> [Difference between char \*str=“STRING” and char str[] = “STRING”?](https://stackoverflow.com/questions/3862842/difference-between-char-str-string-and-char-str-string)
>
>
>
I wrote the following code:
```
int main()
{
char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
```
This gives me a segmentation fault, I cant understand why.
`str` is `pointer to char` not `const char`. Even if that's the case shouldn't it give a compile error like the following program:
```
int main()
{
const char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
```
It gives an error: `assignment of read-only location *str`.
**EDIT**
If my code places the pointer to a read only location, shouldn't I get a compilation error? | 2012/10/06 | [
"https://Stackoverflow.com/questions/12761916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032610/"
] | You assign a pointer to a constant string (which comes as a part of your text and is thus not writable memory).
Fix with `char str[] = "hello";` this will create a r/w copy of the constant string on your stack.
What you do is a perfectly valid pointer assignment. What the compiler does not know is that in a standard system constant strings are placed in read-only memory. On embedded (or other weird) systems this may be different.
Depending on your system you could come with an `mprotect` and change the VM flags on your pointer destination to writable. So the compiler allows for this code, your OS does not though. | ```
char *str = "hello";
```
When you declare `str` as above, it is not guaranteed which part of memory it will be stored. str might be read-only depending on implementation. So trying to change it will cause segmentation fault.
In order to avoid segmentation faullt, declare `str` as an array of characters instead. |
12,761,916 | >
> **Possible Duplicate:**
>
> [Difference between char \*str=“STRING” and char str[] = “STRING”?](https://stackoverflow.com/questions/3862842/difference-between-char-str-string-and-char-str-string)
>
>
>
I wrote the following code:
```
int main()
{
char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
```
This gives me a segmentation fault, I cant understand why.
`str` is `pointer to char` not `const char`. Even if that's the case shouldn't it give a compile error like the following program:
```
int main()
{
const char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
```
It gives an error: `assignment of read-only location *str`.
**EDIT**
If my code places the pointer to a read only location, shouldn't I get a compilation error? | 2012/10/06 | [
"https://Stackoverflow.com/questions/12761916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032610/"
] | You assign a pointer to a constant string (which comes as a part of your text and is thus not writable memory).
Fix with `char str[] = "hello";` this will create a r/w copy of the constant string on your stack.
What you do is a perfectly valid pointer assignment. What the compiler does not know is that in a standard system constant strings are placed in read-only memory. On embedded (or other weird) systems this may be different.
Depending on your system you could come with an `mprotect` and change the VM flags on your pointer destination to writable. So the compiler allows for this code, your OS does not though. | ```
char *str = "hello";
```
here the string hello is a literal.
string literals are always stored in read only memory.
this is the reason you are getting a segmentation fault when you are trying to change the value at read only memory. |
12,761,916 | >
> **Possible Duplicate:**
>
> [Difference between char \*str=“STRING” and char str[] = “STRING”?](https://stackoverflow.com/questions/3862842/difference-between-char-str-string-and-char-str-string)
>
>
>
I wrote the following code:
```
int main()
{
char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
```
This gives me a segmentation fault, I cant understand why.
`str` is `pointer to char` not `const char`. Even if that's the case shouldn't it give a compile error like the following program:
```
int main()
{
const char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
```
It gives an error: `assignment of read-only location *str`.
**EDIT**
If my code places the pointer to a read only location, shouldn't I get a compilation error? | 2012/10/06 | [
"https://Stackoverflow.com/questions/12761916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032610/"
] | You assign a pointer to a constant string (which comes as a part of your text and is thus not writable memory).
Fix with `char str[] = "hello";` this will create a r/w copy of the constant string on your stack.
What you do is a perfectly valid pointer assignment. What the compiler does not know is that in a standard system constant strings are placed in read-only memory. On embedded (or other weird) systems this may be different.
Depending on your system you could come with an `mprotect` and change the VM flags on your pointer destination to writable. So the compiler allows for this code, your OS does not though. | Declaring str as char\* reserves memory for the pointer, but not for the string.
The compiler can put the memory for "hello" anywhere he likes.
You have no guarantee that str[i] is writable, so that's why in some compilers this results in a seg fault.
If you want to make sure that the string is in writable memory, then you have to allocate memory using alloc() or you can use
```
char str[] = "hello";
``` |
12,761,916 | >
> **Possible Duplicate:**
>
> [Difference between char \*str=“STRING” and char str[] = “STRING”?](https://stackoverflow.com/questions/3862842/difference-between-char-str-string-and-char-str-string)
>
>
>
I wrote the following code:
```
int main()
{
char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
```
This gives me a segmentation fault, I cant understand why.
`str` is `pointer to char` not `const char`. Even if that's the case shouldn't it give a compile error like the following program:
```
int main()
{
const char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
```
It gives an error: `assignment of read-only location *str`.
**EDIT**
If my code places the pointer to a read only location, shouldn't I get a compilation error? | 2012/10/06 | [
"https://Stackoverflow.com/questions/12761916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032610/"
] | When you initialize a `char *` using a literal string, then you shouldn't try to modify it's contents: the variable is pointing to memory that doesn't belong to you.
You *can* use:
```
char str[] = "hello";
str[0] = 'H';
```
With this code you've declared an array which is initialized with a copy of the literal string's contents, and now you can modify the array. | Your code has undefined behavior in runtime. You are attempting to write to a literal string, which is not allowed. Such writes may trigger an error or have undefined behavior. Your specific C compiler has `str` point to read-only memory, and attempting to write to that memory leads to a segmentation fault. Even though it's not `const`, the write is still not allowed. |
12,761,916 | >
> **Possible Duplicate:**
>
> [Difference between char \*str=“STRING” and char str[] = “STRING”?](https://stackoverflow.com/questions/3862842/difference-between-char-str-string-and-char-str-string)
>
>
>
I wrote the following code:
```
int main()
{
char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
```
This gives me a segmentation fault, I cant understand why.
`str` is `pointer to char` not `const char`. Even if that's the case shouldn't it give a compile error like the following program:
```
int main()
{
const char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
```
It gives an error: `assignment of read-only location *str`.
**EDIT**
If my code places the pointer to a read only location, shouldn't I get a compilation error? | 2012/10/06 | [
"https://Stackoverflow.com/questions/12761916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032610/"
] | When you initialize a `char *` using a literal string, then you shouldn't try to modify it's contents: the variable is pointing to memory that doesn't belong to you.
You *can* use:
```
char str[] = "hello";
str[0] = 'H';
```
With this code you've declared an array which is initialized with a copy of the literal string's contents, and now you can modify the array. | ```
char *str = "hello";
```
When you declare `str` as above, it is not guaranteed which part of memory it will be stored. str might be read-only depending on implementation. So trying to change it will cause segmentation fault.
In order to avoid segmentation faullt, declare `str` as an array of characters instead. |
12,761,916 | >
> **Possible Duplicate:**
>
> [Difference between char \*str=“STRING” and char str[] = “STRING”?](https://stackoverflow.com/questions/3862842/difference-between-char-str-string-and-char-str-string)
>
>
>
I wrote the following code:
```
int main()
{
char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
```
This gives me a segmentation fault, I cant understand why.
`str` is `pointer to char` not `const char`. Even if that's the case shouldn't it give a compile error like the following program:
```
int main()
{
const char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
```
It gives an error: `assignment of read-only location *str`.
**EDIT**
If my code places the pointer to a read only location, shouldn't I get a compilation error? | 2012/10/06 | [
"https://Stackoverflow.com/questions/12761916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032610/"
] | When you initialize a `char *` using a literal string, then you shouldn't try to modify it's contents: the variable is pointing to memory that doesn't belong to you.
You *can* use:
```
char str[] = "hello";
str[0] = 'H';
```
With this code you've declared an array which is initialized with a copy of the literal string's contents, and now you can modify the array. | ```
char *str = "hello";
```
here the string hello is a literal.
string literals are always stored in read only memory.
this is the reason you are getting a segmentation fault when you are trying to change the value at read only memory. |
12,761,916 | >
> **Possible Duplicate:**
>
> [Difference between char \*str=“STRING” and char str[] = “STRING”?](https://stackoverflow.com/questions/3862842/difference-between-char-str-string-and-char-str-string)
>
>
>
I wrote the following code:
```
int main()
{
char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
```
This gives me a segmentation fault, I cant understand why.
`str` is `pointer to char` not `const char`. Even if that's the case shouldn't it give a compile error like the following program:
```
int main()
{
const char *str = "hello";
str[0] = 'H';
printf("%s\n", str);
}
```
It gives an error: `assignment of read-only location *str`.
**EDIT**
If my code places the pointer to a read only location, shouldn't I get a compilation error? | 2012/10/06 | [
"https://Stackoverflow.com/questions/12761916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032610/"
] | When you initialize a `char *` using a literal string, then you shouldn't try to modify it's contents: the variable is pointing to memory that doesn't belong to you.
You *can* use:
```
char str[] = "hello";
str[0] = 'H';
```
With this code you've declared an array which is initialized with a copy of the literal string's contents, and now you can modify the array. | Declaring str as char\* reserves memory for the pointer, but not for the string.
The compiler can put the memory for "hello" anywhere he likes.
You have no guarantee that str[i] is writable, so that's why in some compilers this results in a seg fault.
If you want to make sure that the string is in writable memory, then you have to allocate memory using alloc() or you can use
```
char str[] = "hello";
``` |
133,319 | I've previously read some of Buterin's posts and he's been especially critical of cross-chain bridges. I know they aren't bridges where digital assets are stored non-natively, but are Chainlink keepers a vulnerability since they're performing `checkUpkeep` off-chain? What guarantee do developers have that the code they wrote is being securely and correctly executed off-chain? How resilient is this other chain? | 2022/08/09 | [
"https://ethereum.stackexchange.com/questions/133319",
"https://ethereum.stackexchange.com",
"https://ethereum.stackexchange.com/users/104442/"
] | Doe
*Disclaimer: I'm a Chainlink Labs employee.*
**What is "off-chain"?**
To your question regarding what is "off-chain". Off-chain is a synonym for using the blockchain client's simulation capability to tell you what would have happened if you submitted a transaction, without using gas. This uses on-chain data and deployed contracts. There is no other chain as per your question.
How does this work? If we look at Ethereum for example, and other EVM compatible chains, you can simulate a transaction to see what the outcome would be. To do this you need an RPC access node (eg node service providers such as <https://www.alchemy.com/>, <https://infura.io/>, or <https://moralis.io/>) and an Ethereum client such as [Geth](https://geth.ethereum.org/) (see [docs](https://ethereum.org/en/developers/docs/nodes-and-clients/#what-are-nodes-and-clients)). The Geth client allows you to simulate a function from an on-chain deployed contract, such as your Chainlink Keeper-compatible contract, using on-chain data and user supplied inputs and returns what state change that would have happened if you submitted it. This simulation doesn't use gas.
**Breaking this down using Chainlink Keepers**
**Network of Nodes aka Keepers**
In Chainlink Keepers, the Keepers Network is a network of nodes managed by the same DevOps teams that manage the nodes in the Chainlink Data Feeds Decentralized Oracle Network. The Keeper nodes and Keepers Registry are aware of each other through configuration. The Keeper nodes will take turns to monitor and service Upkeeps (jobs) [registered](https://docs.chain.link/docs/chainlink-keepers/register-upkeep/) on the Chainlink Keepers Registry .
**Off-chain simulation**
The Keepers nodes simulate the checkUpkeep functions (<https://docs.chain.link/docs/chainlink-keepers/compatible-contracts/#checkupkeep-function>) from all the registered Upkeeps (need to be Keepers compatible <https://docs.chain.link/docs/chainlink-keepers/compatible-contracts/> so nodes know which function to call) and uses the user's checkData (<https://docs.chain.link/docs/chainlink-keepers/compatible-contracts/#checkdata>) supplied on registration, and stored in the Registry, as input into the checkUpkeep function.
If the simulation returns success, the node will take the resulting performData (<https://docs.chain.link/docs/chainlink-keepers/compatible-contracts/#performdata>), if any, from the simulation, do another simulation to see if the performUpkeep function (<https://docs.chain.link/docs/chainlink-keepers/compatible-contracts/#performupkeep-function>) will succeed and falls within the user's specified gas limit (on Registry).
**On-chain execution (or transaction submission)**
If this completes successfully then the Keeper node will submit the performUpkeep transaction on-chain using the performData as input. The Keeper node will make a call via the Keepers Registry to execute the performUpkeep. Once a transaction has been confirmed the Keeper is paid for the gas cost of the transaction plus a premium for monitoring and maintaining the Upkeep (<https://docs.chain.link/docs/chainlink-keepers/keeper-economics/>). This payment happens in the Registry as part of the original transaction call and it is made in LINK. The Upkeep's LINK balance is reduced by the LINK equivalent of the gas cost + premium. Note, the Keeper nodes run Chainlink Labs software that has been optimized for transaction management and can cope with spiking gas environments and re-orgs to ensure your transactions get confirmed.
From the description above you can see the Chainlink Keepers service is fully decentralized. Chainlink Keepers is also highly reliable.
If this is not clear or if I need to elaborate on anything please let me know. | Keepers are a bit different. They just run a function you specify, so there's not really any way for them to be malicious other than just ignoring your request (at which point you (or anyone) can still run the function). Their oracles would be more of a similar risk since they can change what their putting on-chain (e.g. a bridge is simply an oracle that queries another chain, so if the oracle lies and says something happened when it didn't, parties can lose money). |
15,096,308 | There's a code
```
file_paths = {nature:[], nature_thumb:[]}
```
Elsif version that works fine:
```
Find.find('public/uploads') do |path|
if path =~ /.*nature.*\.(jpg|png|gif)$/ and path !~ /.*nature\/thumb.*\.(jpg|png|gif)$/
file_paths[:nature] << path
elsif
path =~ /.*nature\/thumb.*\.(jpg|png|gif)$/
file_paths[:nature_thumb] << path
#etc
end
end
```
Case version causes a problem
```
Find.find('public/uploads') do |path|
case
when path =~ /.*nature.*\.(jpg|png|gif)$/, path !~ /.*nature\/thumb.*\.(jpg|png|gif)$/
file_paths[:nature] << path
when path =~ /.*nature\/thumb.*\.(jpg|png|gif)$/
file_paths[:nature_thumb] << path
# etc
end
end
```
Putting '&&' instead comma causes a error. Comma works wrong. How to avoid this? | 2013/02/26 | [
"https://Stackoverflow.com/questions/15096308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1201917/"
] | You must use CompareTo() rather than the > operation.
See here: <http://msdn.microsoft.com/en-gb/library/system.icomparable.aspx>
In your case you'd put:
```
if (matrix[row, col].CompareTo(max_val) > 0)
``` | Implementing `IComparable` means that it defines the `CompareTo` method, not that the `>` operator is defined. You need to use:
```
if (matrix[row, col].CompareTo(max_val) > 0) {
``` |
15,096,308 | There's a code
```
file_paths = {nature:[], nature_thumb:[]}
```
Elsif version that works fine:
```
Find.find('public/uploads') do |path|
if path =~ /.*nature.*\.(jpg|png|gif)$/ and path !~ /.*nature\/thumb.*\.(jpg|png|gif)$/
file_paths[:nature] << path
elsif
path =~ /.*nature\/thumb.*\.(jpg|png|gif)$/
file_paths[:nature_thumb] << path
#etc
end
end
```
Case version causes a problem
```
Find.find('public/uploads') do |path|
case
when path =~ /.*nature.*\.(jpg|png|gif)$/, path !~ /.*nature\/thumb.*\.(jpg|png|gif)$/
file_paths[:nature] << path
when path =~ /.*nature\/thumb.*\.(jpg|png|gif)$/
file_paths[:nature_thumb] << path
# etc
end
end
```
Putting '&&' instead comma causes a error. Comma works wrong. How to avoid this? | 2013/02/26 | [
"https://Stackoverflow.com/questions/15096308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1201917/"
] | You must use CompareTo() rather than the > operation.
See here: <http://msdn.microsoft.com/en-gb/library/system.icomparable.aspx>
In your case you'd put:
```
if (matrix[row, col].CompareTo(max_val) > 0)
``` | ```
if (matrix[row, col] > max_val)
```
Should be
```
if (matrix[row, col].CompareTo(max_val) > 0)
```
Since [IComparable](http://msdn.microsoft.com/en-us/library/4d7sx9hd.aspx) provides only `CompareTo` not `>`. |
15,096,308 | There's a code
```
file_paths = {nature:[], nature_thumb:[]}
```
Elsif version that works fine:
```
Find.find('public/uploads') do |path|
if path =~ /.*nature.*\.(jpg|png|gif)$/ and path !~ /.*nature\/thumb.*\.(jpg|png|gif)$/
file_paths[:nature] << path
elsif
path =~ /.*nature\/thumb.*\.(jpg|png|gif)$/
file_paths[:nature_thumb] << path
#etc
end
end
```
Case version causes a problem
```
Find.find('public/uploads') do |path|
case
when path =~ /.*nature.*\.(jpg|png|gif)$/, path !~ /.*nature\/thumb.*\.(jpg|png|gif)$/
file_paths[:nature] << path
when path =~ /.*nature\/thumb.*\.(jpg|png|gif)$/
file_paths[:nature_thumb] << path
# etc
end
end
```
Putting '&&' instead comma causes a error. Comma works wrong. How to avoid this? | 2013/02/26 | [
"https://Stackoverflow.com/questions/15096308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1201917/"
] | Implementing `IComparable` means that it defines the `CompareTo` method, not that the `>` operator is defined. You need to use:
```
if (matrix[row, col].CompareTo(max_val) > 0) {
``` | ```
if (matrix[row, col] > max_val)
```
Should be
```
if (matrix[row, col].CompareTo(max_val) > 0)
```
Since [IComparable](http://msdn.microsoft.com/en-us/library/4d7sx9hd.aspx) provides only `CompareTo` not `>`. |
8,088,370 | ```
void menu() {
print();
Scanner input = new Scanner( System.in );
while(true) {
String s = input.next();
switch (s) {
case "m": print(); continue;
case "s": stat(); break;
case "[A-Z]{1}[a-z]{2}\\d{1,}": filminfo( s ); break;
case "Jur1": filminfo(s); break; //For debugging - this worked fine
case "q": ; return;
}
}
}
```
It seems like either my regex is off or that I am not using it right in the case-statement. What I want is a string that: Begins with exactly one uppercase letter and is followed by exactly two lowercase letters, which are followed by at least one digit.
I've checked out the regex API and tried the three variants (greedy, reluctant and possessive quantifiers) without knowing their proper use. Also checked the methods for String without finding a method that seemed pertinent to my needs. | 2011/11/11 | [
"https://Stackoverflow.com/questions/8088370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1020678/"
] | You can't use a regex as a switch case. (Think about it: how would Java know whether you wanted to match the string `"[A-Z]{1}[a-z]{2}\\d{1,}"` or the regex?)
What you could do, in this case, is try to match the regex in your default case.
```
switch (s) {
case "m": print(); continue;
case "s": stat(); break;
case "q": return;
default:
if (s.matches("[A-Z]{1}[a-z]{2}\\d{1,}")) {
filminfo( s );
}
break;
}
```
(BTW, this will only work with Java 7 and later. There's no switching on strings prior to that.) | I don't think you can use regex in switch cases.
>
> The String in the switch expression is compared with the expressions
> associated with each case label as if the String.equals method were
> being used.
>
>
>
See <http://download.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html> for more info. |
14,899,626 | Is there a way to use an OpenType font on Windows Phone 7 Silverlight application? I want to use Lobster which is only available AFAIK in OpenType format. It renders in Blend but not when I deploy to the emulator.
I have included the .otf file in my project and set the Properties to 'Content' and 'Copy If Newer'.
[This website](http://www.markermetro.com/2011/06/technical/windows-phone-7-custom-fonts/) found a solution for .ttf fonts, but the technique specified does not work for OpenType. Is OpenType not supported by Windows Phone? I find this hard to believe given that MS part invented the format! | 2013/02/15 | [
"https://Stackoverflow.com/questions/14899626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199/"
] | As far as I can see, there is nothing wrong with the query.
When I try it, it returns only the obj rows where there is a corresponding date and a corresponding option.
```
insert into dates values
(1, 1, '22/01/2013'),
(2, 1, '23/01/2013'),
(3, 2, '22/01/2013'),
(4, 2, '23/01/2013'),
(5, 3, '23/01/2013'),
(6, 3, '24/01/2013');
insert into `option` values
(1, 1, 4),
(2, 1, 5),
(3, 2, 3),
(4, 2, 4),
(5, 3, 3),
(6, 3, 4);
insert into obj values
(1),
(2),
(3)
```
With this data it should filter out obj 1 because there is no option 3 for it, and filter out obj 3 because there is no date 22 for it.
Result:
```
ID OBJ_ID DISPO_DATE RANDOM_OPTION
-------------------------------------
2 2 22/01/2013 3
```
Demo: <http://sqlfiddle.com/#!2/a398f/1> | Change your line
```
WHERE dates.dispo_date="22/01/2013"
```
for
```
WHERE DATE(dates.dispo_date)="22/01/2013"
```
Handling dates in text fields is a little tricky (also bad practice). Make sure both dates are in the same format. |
14,899,626 | Is there a way to use an OpenType font on Windows Phone 7 Silverlight application? I want to use Lobster which is only available AFAIK in OpenType format. It renders in Blend but not when I deploy to the emulator.
I have included the .otf file in my project and set the Properties to 'Content' and 'Copy If Newer'.
[This website](http://www.markermetro.com/2011/06/technical/windows-phone-7-custom-fonts/) found a solution for .ttf fonts, but the technique specified does not work for OpenType. Is OpenType not supported by Windows Phone? I find this hard to believe given that MS part invented the format! | 2013/02/15 | [
"https://Stackoverflow.com/questions/14899626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199/"
] | As far as I can see, there is nothing wrong with the query.
When I try it, it returns only the obj rows where there is a corresponding date and a corresponding option.
```
insert into dates values
(1, 1, '22/01/2013'),
(2, 1, '23/01/2013'),
(3, 2, '22/01/2013'),
(4, 2, '23/01/2013'),
(5, 3, '23/01/2013'),
(6, 3, '24/01/2013');
insert into `option` values
(1, 1, 4),
(2, 1, 5),
(3, 2, 3),
(4, 2, 4),
(5, 3, 3),
(6, 3, 4);
insert into obj values
(1),
(2),
(3)
```
With this data it should filter out obj 1 because there is no option 3 for it, and filter out obj 3 because there is no date 22 for it.
Result:
```
ID OBJ_ID DISPO_DATE RANDOM_OPTION
-------------------------------------
2 2 22/01/2013 3
```
Demo: <http://sqlfiddle.com/#!2/a398f/1> | First, I'm a little confused on which ID's map to which tables. I might respectfully suggest that the id field in DATES be renamed to date\_id, the id in OPTION be renamed to option\_id, and the id in obj to obj\_id. Makes those relationships MUCH clearer for folks looking in through the keyhole. I'm going in a bit of a circle making sure I understand your relationships properly. On that basis, I may be understanding your problem incorrectly.
I *think* you have obj.id->dates.obj\_id, and option.obj\_id->dates.obj\_id, so on that basis, I think your query has to be a bit more complicated:
This gives you object dates:
```
Select *
from obj obj
join dates d
on obj.id=d.obj_id
```
This gives you user dates:
```
select *
from option o
join dates d
on o.obj_id=d.obj_id
```
To get the result of objects and users having the same dates, you'd need to hook these two together:
```
select *
from (Select *
from obj obj
join dates d
on obj.id=d.obj_id) a
join (select *
from option o
join dates d
on o.obj_id=d.obj_id) b
on a.dispo_date=b.dispo_date
where b.random=3
```
I hope this is useful. Good luck. |
55,587,675 | i can't delete file & folder in android 8 and above. file.delete() return false in all possible way
```
File csvFile = new File(Environment.getExternalStorageDirectory().getPath() + "/Notes/help.csv");
File txtFile = new File(Environment.getExternalStorageDirectory().getPath() + "/Notes/MyFile.txt");
folder = new File(Environment.getExternalStorageDirectory().getPath() + "/Notes");
if (csvFile.exists()) csvFile.delete();
if (txtFile.exists()) txtFile.delete();
if (folder.exists()) folder.delete();
``` | 2019/04/09 | [
"https://Stackoverflow.com/questions/55587675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10122286/"
] | This may be a permission problem.
Starting from Android 8, READ\_EXTERNAL\_STORAGE and WRITE\_EXTERNAL\_STORAGE need to request separately. So even if you can read the file, it is possible you can't delete it.
If you are sure not a permission problem, then change your code to
```
try {
Files.delete(theFileName);
} catch (Exception e) {
log.e(TAG, e.getMessage());
}
```
Which will give you the reason why delete failed. | When you do `new File()` it doesn't create anything, it is just an object that points to a file (a bit like a path). If you were to write to that file object then it would exist, and then you could delete it.
In other words, I think you can't delete it because you never created it in the first place. |
53,682,058 | When I declare or just write a function which takes a 2-dimensional `char`-array in C, Visual Studio tells me I have to put a value in the columns parameter, for example:
```
void board(char mat[][MAX_COLUMNS]);
```
so my question is why do I even need to tell C one dimension of the 2 dimensional array, and why does it have to be the number of columns specifically. | 2018/12/08 | [
"https://Stackoverflow.com/questions/53682058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10700430/"
] | Because arrays are not first class objects in C. When you pass an array to a function, it *decays* to a pointer and the callee cannot guess the size. For a 1D array, it still allows to access elements through pointer arithmetics. But for a 2D array (an array of array) pointer arithmetics require that the size of the second level object (here a row) is known. That is the reason why the number of columns must be explicit.
In addition, Microsoft C does not support Variable Length Array, so the number of columns must be a constant. | Weather Vane pointed out well.
Plus, if you want to circumvent that restriction, use this prototype:
```
void board(char *mat, int rows, int columns);
```
And you can access it by this expression.
```
mat[i*columns+j]
```
when you want to access `i`th row `j`th column element.
Hope it helped! |
53,682,058 | When I declare or just write a function which takes a 2-dimensional `char`-array in C, Visual Studio tells me I have to put a value in the columns parameter, for example:
```
void board(char mat[][MAX_COLUMNS]);
```
so my question is why do I even need to tell C one dimension of the 2 dimensional array, and why does it have to be the number of columns specifically. | 2018/12/08 | [
"https://Stackoverflow.com/questions/53682058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10700430/"
] | Weather Vane pointed out well.
Plus, if you want to circumvent that restriction, use this prototype:
```
void board(char *mat, int rows, int columns);
```
And you can access it by this expression.
```
mat[i*columns+j]
```
when you want to access `i`th row `j`th column element.
Hope it helped! | ```
void board(char mat[][MAX_COLUMNS]);
```
is equivalent to
```
void board(char (*mat)[MAX_COLUMNS]);
```
with `char (*mat)[MAX_COLUMNS]` being the type your 2D-array is decayed to when passed to `board()`: To a pointer to its 1st element, as done to any array passed to a function. |
53,682,058 | When I declare or just write a function which takes a 2-dimensional `char`-array in C, Visual Studio tells me I have to put a value in the columns parameter, for example:
```
void board(char mat[][MAX_COLUMNS]);
```
so my question is why do I even need to tell C one dimension of the 2 dimensional array, and why does it have to be the number of columns specifically. | 2018/12/08 | [
"https://Stackoverflow.com/questions/53682058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10700430/"
] | Weather Vane pointed out well.
Plus, if you want to circumvent that restriction, use this prototype:
```
void board(char *mat, int rows, int columns);
```
And you can access it by this expression.
```
mat[i*columns+j]
```
when you want to access `i`th row `j`th column element.
Hope it helped! | Suppose you have an array
```
char arr[3][4];
```
and define the function as
```
void board(char mat[][4])
```
The array decays to a pointer, so if the function wants to access `mat[2][1]` then the offset from the pointer will be **row x width + column** elements, so `2 * 4 + 1 = 9`. Note that arrays are always contiguous, no matter how many dimensions.
But if you define the function as
```
void board(char mat[][])
```
then there is no information except the pointer, and the compiler has no idea how to index the array.
The reason the dimension given has to be the number of columns, is because that is the way the array is laid out in memory, row by row. |
53,682,058 | When I declare or just write a function which takes a 2-dimensional `char`-array in C, Visual Studio tells me I have to put a value in the columns parameter, for example:
```
void board(char mat[][MAX_COLUMNS]);
```
so my question is why do I even need to tell C one dimension of the 2 dimensional array, and why does it have to be the number of columns specifically. | 2018/12/08 | [
"https://Stackoverflow.com/questions/53682058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10700430/"
] | Because arrays are not first class objects in C. When you pass an array to a function, it *decays* to a pointer and the callee cannot guess the size. For a 1D array, it still allows to access elements through pointer arithmetics. But for a 2D array (an array of array) pointer arithmetics require that the size of the second level object (here a row) is known. That is the reason why the number of columns must be explicit.
In addition, Microsoft C does not support Variable Length Array, so the number of columns must be a constant. | ```
void board(char mat[][MAX_COLUMNS]);
```
is equivalent to
```
void board(char (*mat)[MAX_COLUMNS]);
```
with `char (*mat)[MAX_COLUMNS]` being the type your 2D-array is decayed to when passed to `board()`: To a pointer to its 1st element, as done to any array passed to a function. |
53,682,058 | When I declare or just write a function which takes a 2-dimensional `char`-array in C, Visual Studio tells me I have to put a value in the columns parameter, for example:
```
void board(char mat[][MAX_COLUMNS]);
```
so my question is why do I even need to tell C one dimension of the 2 dimensional array, and why does it have to be the number of columns specifically. | 2018/12/08 | [
"https://Stackoverflow.com/questions/53682058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10700430/"
] | Because arrays are not first class objects in C. When you pass an array to a function, it *decays* to a pointer and the callee cannot guess the size. For a 1D array, it still allows to access elements through pointer arithmetics. But for a 2D array (an array of array) pointer arithmetics require that the size of the second level object (here a row) is known. That is the reason why the number of columns must be explicit.
In addition, Microsoft C does not support Variable Length Array, so the number of columns must be a constant. | Suppose you have an array
```
char arr[3][4];
```
and define the function as
```
void board(char mat[][4])
```
The array decays to a pointer, so if the function wants to access `mat[2][1]` then the offset from the pointer will be **row x width + column** elements, so `2 * 4 + 1 = 9`. Note that arrays are always contiguous, no matter how many dimensions.
But if you define the function as
```
void board(char mat[][])
```
then there is no information except the pointer, and the compiler has no idea how to index the array.
The reason the dimension given has to be the number of columns, is because that is the way the array is laid out in memory, row by row. |
18,308,643 | How can I run a Streaming Map Reduce job remotely on Azure Cluster using C#? My mappers and reducers are written either in Java or C++. The .Net C# SDK's job execution method takes JobType in input so I am unable to specify type of C++ and Java based mapper/reducer.
There is another class `StreamingProcessExecutor` which seems like appropriate for my case but no where it takes my credentials in input so I think it won't be possible to use it for remote execution.
Anyone know how to execute a streaming map reduce job remotely and programtically? | 2013/08/19 | [
"https://Stackoverflow.com/questions/18308643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/421611/"
] | Try this one -
```
DECLARE @Xml XML, @UserTableType SYSNAME = '[dbo].[MyType]'
DECLARE @Sql NVARCHAR(MAX)
SELECT @Sql = 'SELECT ' +
STUFF((SELECT ' ,T.Data.value(''@' +
c.name + ''', ''' +
t.name +
CASE WHEN c.user_type_id IN (165,167,173,175,231,239)
THEN '(' + CONVERT(VARCHAR, c.max_length) + ')'
WHEN c.user_type_id IN (106, 108)
THEN '(' + CONVERT(VARCHAR, c.precision)
+ ', ' + CONVERT(VARCHAR, c.scale) + ')'
ELSE '' END +
''') AS ' + c.name + CHAR(10)
FROM sys.table_types tt
JOIN sys.columns c ON tt.type_table_object_id = c.[object_id]
JOIN sys.types t ON c.user_type_id = t.user_type_id
-- your mistake: [dbo].[MyType] != MyType
WHERE '[' + SCHEMA_NAME(tt.[schema_id]) + '].[' + tt.name + ']' = @UserTableType
AND t.name != 'xml'
FOR XML PATH('')), 1, 7, '') +
'FROM @Xml.nodes(''/' + @UserTableType + ''') T(Data)'
PRINT @Sql
```
Output -
```
SELECT T.Data.value('@Id', 'int') AS Id
,T.Data.value('@MonthNumber', 'int') AS MonthNumber
,T.Data.value('@YearNumber', 'int') AS YearNumber
,T.Data.value('@NumberOfOfficersMakingReferrals', 'int') AS NumberOfOfficersMakingReferrals
,T.Data.value('@TierLevel', 'nvarchar(20)') AS TierLevel
,T.Data.value('@TierStrengthTotal', 'int') AS TierStrengthTotal
FROM @Xml.nodes('/[dbo].[MyType]') T(Data)
``` | There're a several issues here:
* Your table is table variable, so to get schema you have to query `sys.table_types`.
* When you select `for xml for auto`, your node element name will be xml safe @Data - `<_x0040_Data ...`, so I suggest to user for `xml path`.
And your code becomes:
```
CREATE PROC dbo.uSpShredUserDefinedTableType @Xml XML, @UserTableType SYSNAME AS
DECLARE @Sql NVARCHAR(MAX)
SELECT @Sql = 'SELECT ' +
STUFF((SELECT ' ,T.Data.value(''@' +
c.name + ''', ''' +
t.name +
CASE WHEN c.user_type_id IN (165,167,173,175,231,239)
THEN '(' + CONVERT(VARCHAR, c.max_length) + ')'
WHEN c.user_type_id IN (106, 108)
THEN '(' + CONVERT(VARCHAR, c.precision)
+ ', ' + CONVERT(VARCHAR, c.scale) + ')'
ELSE '' END +
''') AS ' + c.name + CHAR(10)
FROM sys.table_types tt
JOIN sys.columns c ON tt.type_table_object_id = c.[object_id]
JOIN sys.types t ON c.user_type_id = t.user_type_id
WHERE tt.name = @UserTableType
AND t.name != 'xml'
FOR XML PATH('')), 1, 7, '') +
'FROM @Xml.nodes(''/' + @UserTableType + ''') T(Data)'
--select @sql
EXEC sp_executesql @Sql, N'@Xml XML', @Xml = @Xml
GO
```
And you calling it like
```
SET @Xml = (SELECT * FROM @Data FOR XML raw('MyType'))
EXEC uSpShredUserDefinedTableType @Xml, 'MyType'
```
[**`sql fiddle demo`**](http://sqlfiddle.com/#!3/a62cf/2) |
5,277,139 | I've been struggling with this issue for a few days now and I'm still not able to figure it out. I've created a sample project to hopefully help figure this issue out. The main issue is when I load a user from my context and perform an UpdateModel() on this object it seems to delete my entity references and I get null references in child objects.
Here is the error:
>
> The operation failed: The relationship
> could not be changed because one or
> more of the foreign-key properties is
> non-nullable. When a change is made to
> a relationship, the related
> foreign-key property is set to a null
> value. If the foreign-key does not
> support null values, a new
> relationship must be defined, the
> foreign-key property must be assigned
> another non-null value, or the
> unrelated object must be deleted
>
>
>
.
Here is the link to the code:
[Here](http://code.google.com/p/contactsctp5/source/browse/Contacts/Contacts/Controllers/ContactsController.cs) (line 42, causes the error to happen) | 2011/03/11 | [
"https://Stackoverflow.com/questions/5277139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I figured this question out thanks to Morteza Manavi on the entity framework website. My issue was caused by my ContactInformation model properties, 'contactid' & 'contacttypeid' not being nullable. Once I fixed this everything with UpdateModel() worked correctly. Thank you very much! | Have you used any data annotations on your key values like [Required] or [StringLength], that would explain the error message. |
29,151,572 | ```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class FileRead
{
public static void main (String[] args) throws IOException
{
try
{
FileInputStream fstream = new FileInputStream("data.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null)
{
System.out.println (strLine);
}
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
```
I put the data.txt in the same location as the java project. I have to get this done for a research project for my java class. | 2015/03/19 | [
"https://Stackoverflow.com/questions/29151572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4691008/"
] | I don't understand, the model shouldn't have to look at params[:reschedule] to know if it's "simply a change to the remind\_at time" -- the model is the thing being changed, it should be able to look at *what's actually being changed* and make sure it's only `remind_at`.
Looking at `params[:reschedule]` wouldn't be right even if you could easily do it -- as conceivably `params[:reschedule]` could be set at the same time other attributes were being modified, and you wouldn't want to allow that either. The only point to doing this in the model is *not* to trust the controller is doing the right thing (and has no security holes), but to ensure that only what's actually allowed is being done.
Which if I understand right, what's allowed is changing no attributes but `remind_at`, if `created_at` is past a certain time.
So what you really need to do is just look at what attributes have changed in a validation hook?
I believe the `changed` method should work to do that. It return a list of changed attributes since the last save. If the post is too old, you want to make sure they include include nothing but `remind_at`.
Does that work?
```
if self.created_at > (Time.now-1.day) &&
self.changed.find {|k| k.to_s != "remind_at"}
# BAD, they're trying to save some other attribute changed
end
```
<http://api.rubyonrails.org/classes/ActiveModel/Dirty.html#method-i-changed> | if its mass assignment..then include the attribute in [attr\_accessible](http://apidock.com/rails/ActiveRecord/Base/attr_accessible/class) or else set it explicitly in controller or model |
6,288 | *Hello everyone, my name is Jay
I work for you 24 hours a day,
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.*
*My kind can be you or you can be me
if you know a body by its chemistry.
We're not only human, but mostly a thing!
We have many shapes, on the air we are king.
Our children you could surf but not in the sea
(for some they are a monstruosity!).
They fly, they bounce, they bend,
but always to us they end!
We get and we give even not alive,
but to do our best we need a good drive,
for we can make work a lot you possess,
even destroy it if working in excess.*
*This riddle was difficult but I'm not a sphinx,
in fact I'm well sure, who I am you can glimpse*
EDIT:
I'm deleting the "easy" and "difficult" part because I think it got most of you thinking in the wrong direction.
HINTS:
* Jay is just a name, don't focus on it
* Most of "Jay"s are objects
* The chemistry I'm talking about is... well think VERY-little!
* "Jay"s have nothing to do with sphinxes! | 2014/12/19 | [
"https://puzzling.stackexchange.com/questions/6288",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/5122/"
] | Jay is
>
> your heart
>
>
>
```
Hello everyone, my name is Jay
I work for you 24 hours a day,
```
>
> the heart does not stop even when sleeping
>
>
>
```
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.
My kind can be you or you can be me
if you know a body by its chemistry.
We're not only human, but mostly a thing!
```
>
> because people sometimes take decisions with their hearts ??
>
>
>
```
We have many shapes, on the air we are king.
Our children you could surf but not in the sea
(for some they are a monstruosity!).
They fly, they bounce, they bend,
but always to us they end!
```
>
> the children are the leukocytes and red blood cells, they "surf" in the fluid, but always return back to the heart.
>
>
>
```
We get and we give even not alive,
but to do our best we need a good drive,
for we can make work a lot you possess,
even destroy it if working in excess.
```
>
> the heart is keeping us alive and supplies the brain with oxygen
>
>
> | I'll take a crack at it:
Jay is
>
> A Joule, the SI unit of energy.
>
>
>
```
Hello everyone, my name is Jay
I work for you 24 hours a day,
```
>
> `J` is the standard abbreviation for Joule, which is also considered to be a measure of work performed.
>
>
>
```
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.
My kind can be you or you can be me
if you know a body by its chemistry.
```
>
> Energy = Mass times the speed of light squared, so any amount of energy could be converted to mass or vice versa. Also, the human body is powered by chemical processes to extract energy from food.
>
>
>
```
We're not only human, but mostly a thing!
We have many shapes, on the air we are king.
```
>
> not really sure about this bit... Energy is commonly stored in batteries, which are a thing, and which come in a disgusting variety of shapes and sizes, but the air thing I dunno.
>
>
>
```
Our children you could surf but not in the sea
(for some they are a monstruosity!).
They fly, they bounce, they bend,
but always to us they end!
```
>
> Energy is commonly transmitted as a wave form. Energy waves can travel through the air, be bounced and bent, but they are still used as energy eventually.
>
>
>
```
We get and we give even not alive,
but to do our best we need a good drive,
for we can make work a lot you possess,
even destroy it if working in excess.
```
>
> Energy is received and transmitted all the time, and is required for all sorts of devices these days; but if you overcharge something or run it with the wrong voltage input you can easily burn it out.
>
>
> |
6,288 | *Hello everyone, my name is Jay
I work for you 24 hours a day,
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.*
*My kind can be you or you can be me
if you know a body by its chemistry.
We're not only human, but mostly a thing!
We have many shapes, on the air we are king.
Our children you could surf but not in the sea
(for some they are a monstruosity!).
They fly, they bounce, they bend,
but always to us they end!
We get and we give even not alive,
but to do our best we need a good drive,
for we can make work a lot you possess,
even destroy it if working in excess.*
*This riddle was difficult but I'm not a sphinx,
in fact I'm well sure, who I am you can glimpse*
EDIT:
I'm deleting the "easy" and "difficult" part because I think it got most of you thinking in the wrong direction.
HINTS:
* Jay is just a name, don't focus on it
* Most of "Jay"s are objects
* The chemistry I'm talking about is... well think VERY-little!
* "Jay"s have nothing to do with sphinxes! | 2014/12/19 | [
"https://puzzling.stackexchange.com/questions/6288",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/5122/"
] | Jay is
>
> your heart
>
>
>
```
Hello everyone, my name is Jay
I work for you 24 hours a day,
```
>
> the heart does not stop even when sleeping
>
>
>
```
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.
My kind can be you or you can be me
if you know a body by its chemistry.
We're not only human, but mostly a thing!
```
>
> because people sometimes take decisions with their hearts ??
>
>
>
```
We have many shapes, on the air we are king.
Our children you could surf but not in the sea
(for some they are a monstruosity!).
They fly, they bounce, they bend,
but always to us they end!
```
>
> the children are the leukocytes and red blood cells, they "surf" in the fluid, but always return back to the heart.
>
>
>
```
We get and we give even not alive,
but to do our best we need a good drive,
for we can make work a lot you possess,
even destroy it if working in excess.
```
>
> the heart is keeping us alive and supplies the brain with oxygen
>
>
> | I'll give it a try, this is what i've got so far:
Jay is
>
> an atom
>
>
>
```
Hello everyone, my name is Jay
I work for you 24 hours a day,
```
>
> atoms get together and break appart all the time to produce every kind of physical nature.
>
>
>
```
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.
```
>
> ...well jay is obviously not from *clerks*.
>
>
>
```
My kind can be you or you can be me
if you know a body by its chemistry.
```
>
> atoms make up all of the visible and touchable matter around us. pretty obvious connection to chemistry.
>
>
>
```
We're not only human, but mostly a thing!
We have many shapes, on the air we are king.
```
>
> human, things, atoms can take any kind of shape. Air is also composed of different molecules.
>
>
>
```
Our children you could surf but not in the sea
(for some they are a monstruosity!).
```
>
> i can't quite figure out this one yet but i'm sure its related to electrons and protons. i think electrons can surf on waves like sound or light waves.
>
>
>
```
They fly, they bounce, they bend,
but always to us they end!
```
>
> atoms exchange protons and electrons to undergo chemical processes.
>
>
>
```
We get and we give even not alive,
but to do our best we need a good drive,
```
>
> another reference to subatomic exchange. i think drive is refering to the force needed to exchange these particles.
>
>
>
```
for we can make work a lot you possess,
even destroy it if working in excess.
```
>
> the exchange of electrons produce electrical flow and can make work any electric device. if the electric flow is powerful enough, it could destroy.
>
>
> |
6,288 | *Hello everyone, my name is Jay
I work for you 24 hours a day,
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.*
*My kind can be you or you can be me
if you know a body by its chemistry.
We're not only human, but mostly a thing!
We have many shapes, on the air we are king.
Our children you could surf but not in the sea
(for some they are a monstruosity!).
They fly, they bounce, they bend,
but always to us they end!
We get and we give even not alive,
but to do our best we need a good drive,
for we can make work a lot you possess,
even destroy it if working in excess.*
*This riddle was difficult but I'm not a sphinx,
in fact I'm well sure, who I am you can glimpse*
EDIT:
I'm deleting the "easy" and "difficult" part because I think it got most of you thinking in the wrong direction.
HINTS:
* Jay is just a name, don't focus on it
* Most of "Jay"s are objects
* The chemistry I'm talking about is... well think VERY-little!
* "Jay"s have nothing to do with sphinxes! | 2014/12/19 | [
"https://puzzling.stackexchange.com/questions/6288",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/5122/"
] | Jay is
>
> your heart
>
>
>
```
Hello everyone, my name is Jay
I work for you 24 hours a day,
```
>
> the heart does not stop even when sleeping
>
>
>
```
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.
My kind can be you or you can be me
if you know a body by its chemistry.
We're not only human, but mostly a thing!
```
>
> because people sometimes take decisions with their hearts ??
>
>
>
```
We have many shapes, on the air we are king.
Our children you could surf but not in the sea
(for some they are a monstruosity!).
They fly, they bounce, they bend,
but always to us they end!
```
>
> the children are the leukocytes and red blood cells, they "surf" in the fluid, but always return back to the heart.
>
>
>
```
We get and we give even not alive,
but to do our best we need a good drive,
for we can make work a lot you possess,
even destroy it if working in excess.
```
>
> the heart is keeping us alive and supplies the brain with oxygen
>
>
> | I think the answer is
>
> computers.
>
>
>
*Hello everyone, my name is Jay*
>
> This might be a specific computer; I'm not really sure.
>
>
>
*I work for you 24 hours a day,*
>
> Lots of computers do this.
>
>
>
*but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.*
>
> References to something on the telly? Excuse my cultural ignorance :-)
>
>
>
*My kind can be you or you can be me
if you know a body by its chemistry.*
>
> People can be seen as very complicated machines/computers, the chemical reactions inside their body taking the place of electronic signals.
>
>
>
*We're not only human, but mostly a thing!*
>
> Computers are things and not humans.
>
>
>
*We have many shapes, on the air we are king.*
>
> ???
>
>
>
*Our children you could surf but not in the sea*
>
> Reference to surfing the web (this is what enabled me to get the answer).
>
>
>
*(for some they are a monstruosity!).*
>
> Some people don't like the internet?
>
>
>
*They fly, they bounce, they bend,
but always to us they end!*
>
> Webpages can do all sorts of things, but to access them you need a computer.
>
>
>
*We get and we give even not alive,*
>
> Computers can do all sorts of things even though they're inanimate.
>
>
>
*but to do our best we need a good drive,*
>
> They need hard drives to function properly.
>
>
>
*for we can make work a lot you possess,
even destroy it if working in excess.*
>
> ???
>
>
>
*This riddle was difficult but I'm not a sphinx,
in fact I'm well sure, who I am you can glimpse*
>
> Indeed, as I solve this riddle I am looking at the answer to the riddle! :-)
>
>
>
Nice one, Noldor! |
6,288 | *Hello everyone, my name is Jay
I work for you 24 hours a day,
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.*
*My kind can be you or you can be me
if you know a body by its chemistry.
We're not only human, but mostly a thing!
We have many shapes, on the air we are king.
Our children you could surf but not in the sea
(for some they are a monstruosity!).
They fly, they bounce, they bend,
but always to us they end!
We get and we give even not alive,
but to do our best we need a good drive,
for we can make work a lot you possess,
even destroy it if working in excess.*
*This riddle was difficult but I'm not a sphinx,
in fact I'm well sure, who I am you can glimpse*
EDIT:
I'm deleting the "easy" and "difficult" part because I think it got most of you thinking in the wrong direction.
HINTS:
* Jay is just a name, don't focus on it
* Most of "Jay"s are objects
* The chemistry I'm talking about is... well think VERY-little!
* "Jay"s have nothing to do with sphinxes! | 2014/12/19 | [
"https://puzzling.stackexchange.com/questions/6288",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/5122/"
] | Jay is
>
> your heart
>
>
>
```
Hello everyone, my name is Jay
I work for you 24 hours a day,
```
>
> the heart does not stop even when sleeping
>
>
>
```
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.
My kind can be you or you can be me
if you know a body by its chemistry.
We're not only human, but mostly a thing!
```
>
> because people sometimes take decisions with their hearts ??
>
>
>
```
We have many shapes, on the air we are king.
Our children you could surf but not in the sea
(for some they are a monstruosity!).
They fly, they bounce, they bend,
but always to us they end!
```
>
> the children are the leukocytes and red blood cells, they "surf" in the fluid, but always return back to the heart.
>
>
>
```
We get and we give even not alive,
but to do our best we need a good drive,
for we can make work a lot you possess,
even destroy it if working in excess.
```
>
> the heart is keeping us alive and supplies the brain with oxygen
>
>
> | \*Hello everyone, my name is Jay
>
> Jay is Carbon ?
>
>
>
I work for you 24 hours a day,
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.
>
> we are carbon-based
>
>
>
My kind can be you or you can be me
if you know a body by its chemistry.
We're not only human, but mostly a thing!
>
> carbon form many compounds, and is present in air
>
>
>
We have many shapes, on the air we are king.
Our children you could surf but not in the sea
(for some they are a monstruosity!).
They fly, they bounce, they bend,
but always to us they end!
>
> also fuel
>
>
>
We get and we give even not alive,
but to do our best we need a good drive,
for we can make work a lot you possess,
even destroy it if working in excess.\* |
6,288 | *Hello everyone, my name is Jay
I work for you 24 hours a day,
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.*
*My kind can be you or you can be me
if you know a body by its chemistry.
We're not only human, but mostly a thing!
We have many shapes, on the air we are king.
Our children you could surf but not in the sea
(for some they are a monstruosity!).
They fly, they bounce, they bend,
but always to us they end!
We get and we give even not alive,
but to do our best we need a good drive,
for we can make work a lot you possess,
even destroy it if working in excess.*
*This riddle was difficult but I'm not a sphinx,
in fact I'm well sure, who I am you can glimpse*
EDIT:
I'm deleting the "easy" and "difficult" part because I think it got most of you thinking in the wrong direction.
HINTS:
* Jay is just a name, don't focus on it
* Most of "Jay"s are objects
* The chemistry I'm talking about is... well think VERY-little!
* "Jay"s have nothing to do with sphinxes! | 2014/12/19 | [
"https://puzzling.stackexchange.com/questions/6288",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/5122/"
] | *Hello everyone, my name is Jay
I work for you 24 hours a day,
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.*
>
> As I already said this did only give the hint that those "Jays" are working 24 hours a day
>
>
>
*My kind can be you or you can be me
if you know a body by its chemistry.*
>
> Chemistry is not Biology: the chemistry I'm talking about is the interaction between charged particles (for example molecules work with protonic/electronic pumps
>
>
>
*We're not only human, but mostly a thing!*
>
> Self explanatory, once you read the solution
>
>
>
*We have many shapes, on the air we are king.*
>
> Many shapes... Again, self explanatory. On the air = On-The-Air -> Radio
>
>
>
*Our children you could surf but not in the sea*
>
> Waves are surfable... and there are some kind of them which are not necessarily made of water
>
>
>
*(for some they are a monstruosity!).*
>
> It's no mystery that some people despise electromagnetic pollution
>
>
>
*They fly, they bounce, they bend,
but always to us they end!*
>
> E.m. waves can fly, can bounce (on metals) can "bend" (refraction) and get captured only by... Antennas! In fact antennas trasmit (waves are their child) and receive such waves
>
>
>
*We get and we give even not alive,*
>
> Antennas are passive pieces of metal
>
>
>
*but to do our best we need a good drive,*
>
> They need to have a power source in order to be able to send a signal
>
>
>
*for we can make work a lot you possess,*
>
> Well, again self-explanatory
>
>
>
*even destroy it if working in excess.*
>
> if overloaded - for example with a lightning - the power spike can destroy electronics in you TV or any other thing connected to it
>
>
>
*This riddle was difficult but I'm not a sphinx,
in fact I'm well sure, who I am you can glimpse*
Well this last verse was only a challange to you ;)
So, the solution is:
>
> ANTENNA! P.s. = There are some kind of antennas that are called "J" antennas ;)
>
>
> | I'll take a crack at it:
Jay is
>
> A Joule, the SI unit of energy.
>
>
>
```
Hello everyone, my name is Jay
I work for you 24 hours a day,
```
>
> `J` is the standard abbreviation for Joule, which is also considered to be a measure of work performed.
>
>
>
```
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.
My kind can be you or you can be me
if you know a body by its chemistry.
```
>
> Energy = Mass times the speed of light squared, so any amount of energy could be converted to mass or vice versa. Also, the human body is powered by chemical processes to extract energy from food.
>
>
>
```
We're not only human, but mostly a thing!
We have many shapes, on the air we are king.
```
>
> not really sure about this bit... Energy is commonly stored in batteries, which are a thing, and which come in a disgusting variety of shapes and sizes, but the air thing I dunno.
>
>
>
```
Our children you could surf but not in the sea
(for some they are a monstruosity!).
They fly, they bounce, they bend,
but always to us they end!
```
>
> Energy is commonly transmitted as a wave form. Energy waves can travel through the air, be bounced and bent, but they are still used as energy eventually.
>
>
>
```
We get and we give even not alive,
but to do our best we need a good drive,
for we can make work a lot you possess,
even destroy it if working in excess.
```
>
> Energy is received and transmitted all the time, and is required for all sorts of devices these days; but if you overcharge something or run it with the wrong voltage input you can easily burn it out.
>
>
> |
6,288 | *Hello everyone, my name is Jay
I work for you 24 hours a day,
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.*
*My kind can be you or you can be me
if you know a body by its chemistry.
We're not only human, but mostly a thing!
We have many shapes, on the air we are king.
Our children you could surf but not in the sea
(for some they are a monstruosity!).
They fly, they bounce, they bend,
but always to us they end!
We get and we give even not alive,
but to do our best we need a good drive,
for we can make work a lot you possess,
even destroy it if working in excess.*
*This riddle was difficult but I'm not a sphinx,
in fact I'm well sure, who I am you can glimpse*
EDIT:
I'm deleting the "easy" and "difficult" part because I think it got most of you thinking in the wrong direction.
HINTS:
* Jay is just a name, don't focus on it
* Most of "Jay"s are objects
* The chemistry I'm talking about is... well think VERY-little!
* "Jay"s have nothing to do with sphinxes! | 2014/12/19 | [
"https://puzzling.stackexchange.com/questions/6288",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/5122/"
] | *Hello everyone, my name is Jay
I work for you 24 hours a day,
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.*
>
> As I already said this did only give the hint that those "Jays" are working 24 hours a day
>
>
>
*My kind can be you or you can be me
if you know a body by its chemistry.*
>
> Chemistry is not Biology: the chemistry I'm talking about is the interaction between charged particles (for example molecules work with protonic/electronic pumps
>
>
>
*We're not only human, but mostly a thing!*
>
> Self explanatory, once you read the solution
>
>
>
*We have many shapes, on the air we are king.*
>
> Many shapes... Again, self explanatory. On the air = On-The-Air -> Radio
>
>
>
*Our children you could surf but not in the sea*
>
> Waves are surfable... and there are some kind of them which are not necessarily made of water
>
>
>
*(for some they are a monstruosity!).*
>
> It's no mystery that some people despise electromagnetic pollution
>
>
>
*They fly, they bounce, they bend,
but always to us they end!*
>
> E.m. waves can fly, can bounce (on metals) can "bend" (refraction) and get captured only by... Antennas! In fact antennas trasmit (waves are their child) and receive such waves
>
>
>
*We get and we give even not alive,*
>
> Antennas are passive pieces of metal
>
>
>
*but to do our best we need a good drive,*
>
> They need to have a power source in order to be able to send a signal
>
>
>
*for we can make work a lot you possess,*
>
> Well, again self-explanatory
>
>
>
*even destroy it if working in excess.*
>
> if overloaded - for example with a lightning - the power spike can destroy electronics in you TV or any other thing connected to it
>
>
>
*This riddle was difficult but I'm not a sphinx,
in fact I'm well sure, who I am you can glimpse*
Well this last verse was only a challange to you ;)
So, the solution is:
>
> ANTENNA! P.s. = There are some kind of antennas that are called "J" antennas ;)
>
>
> | I'll give it a try, this is what i've got so far:
Jay is
>
> an atom
>
>
>
```
Hello everyone, my name is Jay
I work for you 24 hours a day,
```
>
> atoms get together and break appart all the time to produce every kind of physical nature.
>
>
>
```
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.
```
>
> ...well jay is obviously not from *clerks*.
>
>
>
```
My kind can be you or you can be me
if you know a body by its chemistry.
```
>
> atoms make up all of the visible and touchable matter around us. pretty obvious connection to chemistry.
>
>
>
```
We're not only human, but mostly a thing!
We have many shapes, on the air we are king.
```
>
> human, things, atoms can take any kind of shape. Air is also composed of different molecules.
>
>
>
```
Our children you could surf but not in the sea
(for some they are a monstruosity!).
```
>
> i can't quite figure out this one yet but i'm sure its related to electrons and protons. i think electrons can surf on waves like sound or light waves.
>
>
>
```
They fly, they bounce, they bend,
but always to us they end!
```
>
> atoms exchange protons and electrons to undergo chemical processes.
>
>
>
```
We get and we give even not alive,
but to do our best we need a good drive,
```
>
> another reference to subatomic exchange. i think drive is refering to the force needed to exchange these particles.
>
>
>
```
for we can make work a lot you possess,
even destroy it if working in excess.
```
>
> the exchange of electrons produce electrical flow and can make work any electric device. if the electric flow is powerful enough, it could destroy.
>
>
> |
6,288 | *Hello everyone, my name is Jay
I work for you 24 hours a day,
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.*
*My kind can be you or you can be me
if you know a body by its chemistry.
We're not only human, but mostly a thing!
We have many shapes, on the air we are king.
Our children you could surf but not in the sea
(for some they are a monstruosity!).
They fly, they bounce, they bend,
but always to us they end!
We get and we give even not alive,
but to do our best we need a good drive,
for we can make work a lot you possess,
even destroy it if working in excess.*
*This riddle was difficult but I'm not a sphinx,
in fact I'm well sure, who I am you can glimpse*
EDIT:
I'm deleting the "easy" and "difficult" part because I think it got most of you thinking in the wrong direction.
HINTS:
* Jay is just a name, don't focus on it
* Most of "Jay"s are objects
* The chemistry I'm talking about is... well think VERY-little!
* "Jay"s have nothing to do with sphinxes! | 2014/12/19 | [
"https://puzzling.stackexchange.com/questions/6288",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/5122/"
] | *Hello everyone, my name is Jay
I work for you 24 hours a day,
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.*
>
> As I already said this did only give the hint that those "Jays" are working 24 hours a day
>
>
>
*My kind can be you or you can be me
if you know a body by its chemistry.*
>
> Chemistry is not Biology: the chemistry I'm talking about is the interaction between charged particles (for example molecules work with protonic/electronic pumps
>
>
>
*We're not only human, but mostly a thing!*
>
> Self explanatory, once you read the solution
>
>
>
*We have many shapes, on the air we are king.*
>
> Many shapes... Again, self explanatory. On the air = On-The-Air -> Radio
>
>
>
*Our children you could surf but not in the sea*
>
> Waves are surfable... and there are some kind of them which are not necessarily made of water
>
>
>
*(for some they are a monstruosity!).*
>
> It's no mystery that some people despise electromagnetic pollution
>
>
>
*They fly, they bounce, they bend,
but always to us they end!*
>
> E.m. waves can fly, can bounce (on metals) can "bend" (refraction) and get captured only by... Antennas! In fact antennas trasmit (waves are their child) and receive such waves
>
>
>
*We get and we give even not alive,*
>
> Antennas are passive pieces of metal
>
>
>
*but to do our best we need a good drive,*
>
> They need to have a power source in order to be able to send a signal
>
>
>
*for we can make work a lot you possess,*
>
> Well, again self-explanatory
>
>
>
*even destroy it if working in excess.*
>
> if overloaded - for example with a lightning - the power spike can destroy electronics in you TV or any other thing connected to it
>
>
>
*This riddle was difficult but I'm not a sphinx,
in fact I'm well sure, who I am you can glimpse*
Well this last verse was only a challange to you ;)
So, the solution is:
>
> ANTENNA! P.s. = There are some kind of antennas that are called "J" antennas ;)
>
>
> | I think the answer is
>
> computers.
>
>
>
*Hello everyone, my name is Jay*
>
> This might be a specific computer; I'm not really sure.
>
>
>
*I work for you 24 hours a day,*
>
> Lots of computers do this.
>
>
>
*but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.*
>
> References to something on the telly? Excuse my cultural ignorance :-)
>
>
>
*My kind can be you or you can be me
if you know a body by its chemistry.*
>
> People can be seen as very complicated machines/computers, the chemical reactions inside their body taking the place of electronic signals.
>
>
>
*We're not only human, but mostly a thing!*
>
> Computers are things and not humans.
>
>
>
*We have many shapes, on the air we are king.*
>
> ???
>
>
>
*Our children you could surf but not in the sea*
>
> Reference to surfing the web (this is what enabled me to get the answer).
>
>
>
*(for some they are a monstruosity!).*
>
> Some people don't like the internet?
>
>
>
*They fly, they bounce, they bend,
but always to us they end!*
>
> Webpages can do all sorts of things, but to access them you need a computer.
>
>
>
*We get and we give even not alive,*
>
> Computers can do all sorts of things even though they're inanimate.
>
>
>
*but to do our best we need a good drive,*
>
> They need hard drives to function properly.
>
>
>
*for we can make work a lot you possess,
even destroy it if working in excess.*
>
> ???
>
>
>
*This riddle was difficult but I'm not a sphinx,
in fact I'm well sure, who I am you can glimpse*
>
> Indeed, as I solve this riddle I am looking at the answer to the riddle! :-)
>
>
>
Nice one, Noldor! |
6,288 | *Hello everyone, my name is Jay
I work for you 24 hours a day,
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.*
*My kind can be you or you can be me
if you know a body by its chemistry.
We're not only human, but mostly a thing!
We have many shapes, on the air we are king.
Our children you could surf but not in the sea
(for some they are a monstruosity!).
They fly, they bounce, they bend,
but always to us they end!
We get and we give even not alive,
but to do our best we need a good drive,
for we can make work a lot you possess,
even destroy it if working in excess.*
*This riddle was difficult but I'm not a sphinx,
in fact I'm well sure, who I am you can glimpse*
EDIT:
I'm deleting the "easy" and "difficult" part because I think it got most of you thinking in the wrong direction.
HINTS:
* Jay is just a name, don't focus on it
* Most of "Jay"s are objects
* The chemistry I'm talking about is... well think VERY-little!
* "Jay"s have nothing to do with sphinxes! | 2014/12/19 | [
"https://puzzling.stackexchange.com/questions/6288",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/5122/"
] | *Hello everyone, my name is Jay
I work for you 24 hours a day,
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.*
>
> As I already said this did only give the hint that those "Jays" are working 24 hours a day
>
>
>
*My kind can be you or you can be me
if you know a body by its chemistry.*
>
> Chemistry is not Biology: the chemistry I'm talking about is the interaction between charged particles (for example molecules work with protonic/electronic pumps
>
>
>
*We're not only human, but mostly a thing!*
>
> Self explanatory, once you read the solution
>
>
>
*We have many shapes, on the air we are king.*
>
> Many shapes... Again, self explanatory. On the air = On-The-Air -> Radio
>
>
>
*Our children you could surf but not in the sea*
>
> Waves are surfable... and there are some kind of them which are not necessarily made of water
>
>
>
*(for some they are a monstruosity!).*
>
> It's no mystery that some people despise electromagnetic pollution
>
>
>
*They fly, they bounce, they bend,
but always to us they end!*
>
> E.m. waves can fly, can bounce (on metals) can "bend" (refraction) and get captured only by... Antennas! In fact antennas trasmit (waves are their child) and receive such waves
>
>
>
*We get and we give even not alive,*
>
> Antennas are passive pieces of metal
>
>
>
*but to do our best we need a good drive,*
>
> They need to have a power source in order to be able to send a signal
>
>
>
*for we can make work a lot you possess,*
>
> Well, again self-explanatory
>
>
>
*even destroy it if working in excess.*
>
> if overloaded - for example with a lightning - the power spike can destroy electronics in you TV or any other thing connected to it
>
>
>
*This riddle was difficult but I'm not a sphinx,
in fact I'm well sure, who I am you can glimpse*
Well this last verse was only a challange to you ;)
So, the solution is:
>
> ANTENNA! P.s. = There are some kind of antennas that are called "J" antennas ;)
>
>
> | \*Hello everyone, my name is Jay
>
> Jay is Carbon ?
>
>
>
I work for you 24 hours a day,
but don't get me wrong I know not Silent Bob
and got nothing to do with weed on the job.
>
> we are carbon-based
>
>
>
My kind can be you or you can be me
if you know a body by its chemistry.
We're not only human, but mostly a thing!
>
> carbon form many compounds, and is present in air
>
>
>
We have many shapes, on the air we are king.
Our children you could surf but not in the sea
(for some they are a monstruosity!).
They fly, they bounce, they bend,
but always to us they end!
>
> also fuel
>
>
>
We get and we give even not alive,
but to do our best we need a good drive,
for we can make work a lot you possess,
even destroy it if working in excess.\* |
55,945,937 | I have a set of objects in a MongoDB. The object includes an array of types. Now I am connecting to the DB with Mongoose and would like to now the number of objects for each Type.
For example my objects look like
```
{
"name": "abc",
"tags": ["a","b","c"]
}
```
Now I would like to get the total number of Objects which for example have the Tag "a"
I am connecting to the MongoDB with a NodeJS Backend using Mongoose
Thanks for your Ideas on how to query this efficiently.
**Addition**:
In the case where I don't know what kind of different tags are existing in the different objects and I would like to get an overview of all tags, how do I need to query on this one? For better understanding I give an example.
Two objects in the database:
```
{
"name": "abc",
"tags": ["a","b","c"]
},
{
"name": "abc",
"tags": ["a","b"]
}
```
the function/query should give a response of something like this:
```
{
"a": 2,
"b": 2,
"c": 1
}
``` | 2019/05/02 | [
"https://Stackoverflow.com/questions/55945937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8966014/"
] | ```
collection.aggregate([
{$unwind: "$tags" },
{$group: {
_id: "$tags",
count: {$sum : 1}
}},
]);
```
this will give output like this:
```
/* 1 */
{
"_id" : "c",
"count" : 2
}
/* 2 */
{
"_id" : "b",
"count" : 3
}
/* 3 */
{
"_id" : "a",
"count" : 2
}
``` | Use `count` which is a collection method. It returns the count only instead of all documents. If You need the documents , replace `count` with `find`
```
collection.count({tags:"a"})
``` |
69,166,004 | I tried to deploy something like [this example](https://www.serverless.com/blog/how-to-create-a-rest-api-in-java-using-dynamodb-and-serverless/) from [serverless](https://www.serverless.com/). Building my `serverless.yml`, I run into this error, of which I don't find a handle to deal with:
```yaml
service: products-api
package:
artifact: target\products-api-dev.jar
#artifact: target\${self:service}-${self:provider.stage}.jar #cool alternative :)
provider:
name: aws
runtime: java8
#Copy-pasted
resources:
Resources:
productsTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: products_table
AttributeDefinitions:
- AttributeName: id
AttributeType: S
- AttributeName: name
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
- AttributeName: name
KeyType: RANGE
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
functions:
listProducts:
handler: com.serverless.ListProductsHandler
events:
- http:
path: /products
method: get
getProduct:
handler: com.serverless.GetProductHandler
events:
- http:
path: /products/{id}
method: get
createProduct:
handler: com.serverless.CreateProductHandler
events:
- http:
path: /products
method: post
deleteProduct:
handler: com.serverless.DeleteProductHandler
events:
- http:
path: /products/{id}
```
The error I get is this - not having a reference to a mistake in my own code makes difficult to spot where I went wrong.
I looked into many Q/A including [this](https://stackoverflow.com/questions/55292269/why-i-got-typeerror-cannot-read-property-tolowercase-of-undefined) and [this](https://stackoverflow.com/questions/42542137/typescript-cannot-read-property-tolowercase-of-undefined), but it seems to be more of a javascript and typescript problem there, not serverless as here.
```
Type Error ----------------------------------------------
TypeError: Cannot read property 'toLowerCase' of undefined
at AwsCompileApigEvents.getHttpMethod (C:\snapshot\serverless\lib\plugins\aws\package\compile\events\apiGateway\lib\validate.js:195:24)
at C:\snapshot\serverless\lib\plugins\aws\package\compile\events\apiGateway\lib\validate.js:50:30
at Array.forEach (<anonymous>)
at C:\snapshot\serverless\lib\plugins\aws\package\compile\events\apiGateway\lib\validate.js:45:37
at Array.forEach (<anonymous>)
at AwsCompileApigEvents.validate (C:\snapshot\serverless\lib\plugins\aws\package\compile\events\apiGateway\lib\validate.js:44:55)
at Object.package:compileEvents [as hook] (C:\snapshot\serverless\lib\plugins\aws\package\compile\events\apiGateway\index.js:318:31)
at PluginManager.invoke (C:\snapshot\serverless\lib\classes\PluginManager.js:579:20)
at async PluginManager.spawn (C:\snapshot\serverless\lib\classes\PluginManager.js:601:5)
at async Object.before:deploy:deploy [as hook] (C:\snapshot\serverless\lib\plugins\deploy.js:60:11)
at async PluginManager.invoke (C:\snapshot\serverless\lib\classes\PluginManager.js:579:9)
at async PluginManager.run (C:\snapshot\serverless\lib\classes\PluginManager.js:639:7)
at async Serverless.run (C:\snapshot\serverless\lib\Serverless.js:452:5)
at async C:\snapshot\serverless\scripts\serverless.js:751:9
For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.
``` | 2021/09/13 | [
"https://Stackoverflow.com/questions/69166004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13914780/"
] | It's a really simple solution. You created `int` function that never returns a value. If you have a function that you don't want any value to be returned, just make it `void`. To make your code work simply change function type from `int` to `void`
```
void Task(int balance, int balance2, int option)
```
The second issue is that you did declare balance1 and balance2, but you forgot to declare their values which lead to another error ( how is the compiler supposed to know their starting value?):
```
int Account1; Account2; // incorrect
int Account1=0, Account2=0; //fixed
```
Of course, you can also set these values later, but in this case, you should do it while declaring.
Another thing, why do you have `int main1()` function?
compiler will not treat it as you desire - it has to be called `int main()`
in order to do what you want. | You are missing "return balance" at the end of the Task() function. You define your function to return integer, that means you have to have return statement inside the function. Also, you have to have main() function, not main1() as in your case. Every C/C++ needs function that is called main() and it represent the entry point of the program. Try this code:
```
#include <iostream>
using namespace std;
// ATM menu
void Menu() {
cout << " MENU " << endl;
cout << "1.Deposit" << endl;
cout << "2.Balance" << endl;
cout << "3.Withdraw" << endl;
cout << "4.Transfer" << endl;
cout << "5.Exit" << endl;
cout << "-------------------------------" << endl;
}
// Tasks of ATM
int Task(int balance, int balance2, int option) {
int amount;
cin >> option;
switch (option) {
case 1:
cout << "please enter the amount" << endl;
cin >> amount;
balance += amount;
cout << "your balance is now:" << balance << "$" << endl;
break;
case 2:
cout << balance << endl;
break;
case 3:
cout << "please enter the amount" << endl;
cin >> amount;
if (amount <= balance) {
balance -= amount;
cout << "your balance is now:" << balance << "$" << endl;
break;
} else
cout << "insufficent amount";
break;
case 4:
cout << "please enter the amount" << endl;
cin >> amount;
if (amount <= balance) {
balance -= amount;
balance2 += amount;
cout << "your balance is now:" << balance << "$" << endl;
break;
} else
cout << "insufficent amount";
break;
}
return balance;
}
// Main func
int main() {
cout << "Please choose Your account " << endl;
int Account1, Account2;
cout << "Account 1 , Account 2" << endl;
char x;
cin >> x;
int option;
// Account 1 lines:Balance = 500 , balance 2= 700
do {
if (x == Account1) {
Menu();
cout << "option:" << endl;
cin >> option;
Task(500, 700, option);
}
// Account 2 lines : Balance = 700 , balance 2= 500
else {
int option;
cout << "option:" << endl;
cin >> option;
Task(700, 500, option);
}
} while (option != 5);
}
``` |
28,907,292 | I run the following query:
```
select * from my_temp_table
```
And get this output:
>
> PNRP1-109/RT
>
> PNRP1-200-16
>
> PNRP1-209/PG
>
> 013555366-IT
>
>
>
How can I alter my query to strip the last two characters from each value? | 2015/03/06 | [
"https://Stackoverflow.com/questions/28907292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4632588/"
] | Use the `SUBSTR()` function.
```
SELECT SUBSTR(my_column, 1, LENGTH(my_column) - 2) FROM my_table;
``` | Another way using a regular expression:
```
select regexp_replace('PNRP1-109/RT', '^(.*).{2}$', '\1') from dual;
```
This replaces your string with group 1 from the regular expression, where group 1 (inside of the parens) includes the set of characters after the beginning of the line, not including the 2 characters just before the end of the line.
While not as simple for your example, arguably more powerful. |
29,312,315 | I have a table with time periods like (no overlap in time periods):
```
start_date end_date
-----------------------------
12-aug-14 12-nov-14
12-jan-15 12-apr-15
12-jun-15 12-aug-15
... 5 more
```
I'm trying to find the in between time periods - something like:
```
12-nov-14 12-jan-15
12-apr-15 12-jun-15
...
```
However, my queries are giving all time period differences like:
```
12-nov-14 12-jan-15
12-nov-14 12-jun-15
```
My query was:
```
select
l1.end_date, l2.start_date
from
lease l1, lease l2
where
l1.place_no = 'P1' and l2.place_no = 'P1'
and l2.start_date > l1.end_date
order by
l1.end_date asc;
```
Any ideas?
Thanks! | 2015/03/28 | [
"https://Stackoverflow.com/questions/29312315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1264806/"
] | `sort` your table, use `rownum` and then `join` them:
```
WITH CTE AS (
SELECT
START_DATE,
END_DATE,
ROWNUM AS RN
FROM ( SELECT START_DATE, END_DATE FROM TABLE_NAME ORDER BY 1,2)
)
SELECT T1.END_DATE, T2.START_DATE
FROM CTE T1 JOIN CTE T2 ON T2.RN=T1.RN+1
``` | This is kind of tricky. You are currently creating a cartesian, which is close, after you create your cartesian, use a group-by to limit it back down to just the start-rows, and the minimum end-rows:
```
select
l1.end_date,
min(l2.start_date)
from
lease l1
inner join lease l2 ON
l1.place_no = l2.place_no and
l2.start_date >= l1 end_date
where
l1.place_no = 'P1'
group by
l1.start_date
having
l2.start_date != l1.end_date
```
Sorry about chaning your join syntax on you, it helps me organize my SQL better in my head. |
29,312,315 | I have a table with time periods like (no overlap in time periods):
```
start_date end_date
-----------------------------
12-aug-14 12-nov-14
12-jan-15 12-apr-15
12-jun-15 12-aug-15
... 5 more
```
I'm trying to find the in between time periods - something like:
```
12-nov-14 12-jan-15
12-apr-15 12-jun-15
...
```
However, my queries are giving all time period differences like:
```
12-nov-14 12-jan-15
12-nov-14 12-jun-15
```
My query was:
```
select
l1.end_date, l2.start_date
from
lease l1, lease l2
where
l1.place_no = 'P1' and l2.place_no = 'P1'
and l2.start_date > l1.end_date
order by
l1.end_date asc;
```
Any ideas?
Thanks! | 2015/03/28 | [
"https://Stackoverflow.com/questions/29312315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1264806/"
] | Use `lead()`. That is what the function is designed for:
```
select l.*,
lead(start_date) over (partition by place_no order by start_date) as next_start_date,
(lead(start_date) over (partition by place_no order by start_date) as next_start_date - end_date) as gap
from lease l
where l1.place_no = 'P1';
```
There is no need for a `join` or even for subqueries -- unless you want to eliminate the additional row that has a NULL value because there is no next value. | This is kind of tricky. You are currently creating a cartesian, which is close, after you create your cartesian, use a group-by to limit it back down to just the start-rows, and the minimum end-rows:
```
select
l1.end_date,
min(l2.start_date)
from
lease l1
inner join lease l2 ON
l1.place_no = l2.place_no and
l2.start_date >= l1 end_date
where
l1.place_no = 'P1'
group by
l1.start_date
having
l2.start_date != l1.end_date
```
Sorry about chaning your join syntax on you, it helps me organize my SQL better in my head. |
35,468,956 | Completely lost here. I have a mysql database with an appointment table. The important for this is that is has a start\_date and end\_date
Suppose I need to find the next available 30 minute slot. Need to stat Mon-Fri and 7am to 7 pm
Basically I need a way to automatically do this process. What would my sql query look like?
select \* from calendar where end\_date < now and ???? lost | 2016/02/17 | [
"https://Stackoverflow.com/questions/35468956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/528130/"
] | `analysttest.rss.channel.item[0]` gives the fist item, which you can `#assign` to a shorther name for convenience. Note that at least 1 item must exist, or else you get an error. (Or, you can do something like `<#assign item = analysttest.rss.channel.item[0]!someDefault>`, where `someDefault` is like `''`, `[]`, `{}`, etc, depending on what you need. There's even a shorter `<#assign item = analysttest.rss.channel.item[0]!>` form, which uses a multi-typed "generic nothing" value as the default... see in the Manual.)
Listing is also possible, though odd for only one item: `<#list analysttest.rss.channel.item[0..*1] as item>`, where `*1` means at most length of 1 (requires FreeMarker 2.3.21 or later). This works (and outputs nothing) even if you have 0 items. | ```
<#assign item = analysttest.rss.channel.item[0]>
<div>
<h3 class="bstitle">${item.title}</h3>
<span class="bsauthor">${item.author}</span>
<span>${item.pubDate}</span>
<p>${item.description}</p>
</div>
``` |
21,333,935 | I have a legacy project which has a singleton class like this:
```
class Singleton
{
public:
static Singleton& Instance()
{
static Singleton inst;
return inst;
}
void foo();
};
```
The project uses a DLL which needs to use the same class (part of the source is shared between the hosting application and the DLL, so the DLL has access to `Singleton`). However, `Instance` (naturally) returns a different instance for DLL, and a different one for the hosting application. This obviously causes problems.
Is there a way to use the same instance between the DLL and the hosting process? (let's assume that binary compatibility is not an issue.) | 2014/01/24 | [
"https://Stackoverflow.com/questions/21333935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/140367/"
] | One way would be to put an ifdef in your Instance() method so that it behaved differently in your app and dll. For example, have the app one call an exported function on the dll which internally calls the dlls Instance() method. Have the dll version work as originally.
Beware though, unless you make methods like foo() virtual, when the app calls foo() it will call the app's implementation of foo(), and when the dll calls foo() it will call the dll's foo(). This is messy at best and problematic at worst.
The neatest way around this is to make a pure virtual interface which contains the public interface, then have the app get a pointer to this interface class from the dll and use that. This way the app has no code from Singleton and you will save yourself future debug pain.
In a shared header:
```
struct ISingleton
{
virtual void foo()=0;
};
DLL_EXPORT ISingleton &GetSingleton();
```
In Dll:
```
struct Singleton : public ISingleton
{
virtual void foo() { /* code */ }
};
ISingleton &GetSingleton()
{
static Singleton inst;
return inst;
}
```
In common code (dll or exe):
```
GetSingleton().foo();
``` | The common solution is to have another dll that holds the singleton but not implemented with a static member. See this [answer](https://stackoverflow.com/a/6936218/109960) for example. |
21,333,935 | I have a legacy project which has a singleton class like this:
```
class Singleton
{
public:
static Singleton& Instance()
{
static Singleton inst;
return inst;
}
void foo();
};
```
The project uses a DLL which needs to use the same class (part of the source is shared between the hosting application and the DLL, so the DLL has access to `Singleton`). However, `Instance` (naturally) returns a different instance for DLL, and a different one for the hosting application. This obviously causes problems.
Is there a way to use the same instance between the DLL and the hosting process? (let's assume that binary compatibility is not an issue.) | 2014/01/24 | [
"https://Stackoverflow.com/questions/21333935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/140367/"
] | I've solved the same problem (eg. class used within library, in other library and also in main application) by moving the static Singleton inst; into cpp file.
```
Foo.h
class Foo{
public:
static Foo *getInstance();
...
Foo.cpp
Foo *Foo::getInstance(){
static Foo instance;
return &foo;
}
```
The static variable is then in one position inside library (so/dll) and everything runs fine. I'm even able to have different header files for export. | The common solution is to have another dll that holds the singleton but not implemented with a static member. See this [answer](https://stackoverflow.com/a/6936218/109960) for example. |
21,333,935 | I have a legacy project which has a singleton class like this:
```
class Singleton
{
public:
static Singleton& Instance()
{
static Singleton inst;
return inst;
}
void foo();
};
```
The project uses a DLL which needs to use the same class (part of the source is shared between the hosting application and the DLL, so the DLL has access to `Singleton`). However, `Instance` (naturally) returns a different instance for DLL, and a different one for the hosting application. This obviously causes problems.
Is there a way to use the same instance between the DLL and the hosting process? (let's assume that binary compatibility is not an issue.) | 2014/01/24 | [
"https://Stackoverflow.com/questions/21333935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/140367/"
] | One way would be to put an ifdef in your Instance() method so that it behaved differently in your app and dll. For example, have the app one call an exported function on the dll which internally calls the dlls Instance() method. Have the dll version work as originally.
Beware though, unless you make methods like foo() virtual, when the app calls foo() it will call the app's implementation of foo(), and when the dll calls foo() it will call the dll's foo(). This is messy at best and problematic at worst.
The neatest way around this is to make a pure virtual interface which contains the public interface, then have the app get a pointer to this interface class from the dll and use that. This way the app has no code from Singleton and you will save yourself future debug pain.
In a shared header:
```
struct ISingleton
{
virtual void foo()=0;
};
DLL_EXPORT ISingleton &GetSingleton();
```
In Dll:
```
struct Singleton : public ISingleton
{
virtual void foo() { /* code */ }
};
ISingleton &GetSingleton()
{
static Singleton inst;
return inst;
}
```
In common code (dll or exe):
```
GetSingleton().foo();
``` | I've solved the same problem (eg. class used within library, in other library and also in main application) by moving the static Singleton inst; into cpp file.
```
Foo.h
class Foo{
public:
static Foo *getInstance();
...
Foo.cpp
Foo *Foo::getInstance(){
static Foo instance;
return &foo;
}
```
The static variable is then in one position inside library (so/dll) and everything runs fine. I'm even able to have different header files for export. |
41,805,638 | This works perfectly fine. Now, I would like to incorporate this into a function and just call the function within my expression. It doesn't work.
**Working code:**
```
render: function() {
return (
<div>
{this.props.list.map(function(listValue){
return <p>{listValue}</p>;
})}
</div>
)
}
});
ReactDOM.render(<List list={[1,2,3,4,5]} />, document.getElementById('app'));
```
**code with the function (doesn't work):**
```
var List = React.createClass({
addText: function()
{
this.props.list.map(function(listValue){
return <p>{listValue}</p>;
});
},
render: function() {
return (
<div>
{this.addText()}
</div>
)
}
});
ReactDOM.render(<List list={[1,2,3,4,5]} />, document.getElementById('app'));
``` | 2017/01/23 | [
"https://Stackoverflow.com/questions/41805638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2951933/"
] | You've extracted the call to `map` into another function and *maybe* assumed the `return` call inside it was sufficient to return the result of the whole call (it just returns the mapped value for that iteration of map).
You just need to return the result of your map in your `addText` function:
```
var List = React.createClass({
addText: function()
{
return ( // <------ADD THIS
this.props.list.map(function(listValue){
return <p>{listValue}</p>;
})
); //<<-----DON'T FORGET TO CLOSE OFF THE NEW BRACKET
},
render: function() {
return (
<div>
{this.addText()}
</div>
)
}
});
``` | Tnx **@Thomas altmann**, I forgot to make another return prior to my first return
```
var List = React.createClass({
addText: function()
{
return (this.props.list.map(function(listValue){
return <p>{listValue}</p>;
})
);
},
render: function() {
return (
<div>
{this.addText()}
</div>
)
}
});
ReactDOM.render(<List list={[1,2,3,4,5]} />, document.getElementById('app'));
``` |
682,964 | I am new to networking, my problem is: I have two internet connections in my company, so when one internet goes down, it should access from another – but it's not working: the Internet is connected to different routers and then connected to a switch. If I want to share Internet connections, what setting do I want to change on the computers or router?
I tried the following settings on the computers (Windows 7):
1. Set the default gateway & preferred DNS as first internet
2. Set alternative DNS as second internet
3. Added the second internet connection IP in the "default gateway" option in the "advanced" tab of network adapter settings. | 2013/12/02 | [
"https://superuser.com/questions/682964",
"https://superuser.com",
"https://superuser.com/users/278512/"
] | First: You are doing it backwards.
First priority is to CLEAN the machine.
And the only certain way to do that is to boot from a rescue-medium and scan/clean the machine from there.
But sometimes you don't have a choice.
Example: When you have a machine that uses some form of disk-encryption so you can't get at the harddisk when booted from other media.
In that case boot it in "Safe mode with command prompt".
Then run regedit (there is a GUI, just not an Explorer shell running at that time).
In regedit go to HKLM\Software\Microsoft\Windows\CurrentVersion\Run.
Add you autorun program as extra entry in that key.
Alternatively you can use the REG.EXE command to do the same from the commandline.
(It is a good idea to remove ALL other entries from the Run key while you are at it. One of them might be part of the malware. You can use the export function of Regedit to temporarily save them in a file.)
An alternative to this is to change the logon shell from explorer.exe to a filemanager (like TotalCommander or DirOpus).
Sometimes adding autorun entries doesn't work, but using an alternative shell does.
That is in the key HKLM\Software\Microsoft\Windows NT\CurrentVersion\WinLogon. You will have to change the value of the "Shell" entry for that (you can use a full path to the executable).
**Please note** that adding an extra program, that relies on keyboard input while the malware is active, may NOT work. The malware can easily hijack any keyboard input thereby preventing your program to activate. | Open file:
```
openfiles /Query /FO:csv | more
```
View NetBIOS network open files:
```
net files
```
Process commandline, caption, Pid:
```
Wmic process get CommandLine, name, ProcessId | more
```
Process path, caption, Pid:
```
Wmic process get ExecutablePath, name, ProcessId | more
```
Network active process:
```
netstat -aon | findstr [1-9]\. | more
```
Network active process with name:
```
netstat -baon | more
```
Job list:
```
wmic job list STATUS
```
Autorun list:
```
wmic startup list full | more
```
View import dll module (Embarcadero or Borland version):
```
tdump -w hal*.dll | find "Imports from "
```
Remove all permissions and permits the user to disable all:
```
cacls <filename> /T /C /P %username%:N
```
Terminates the specified process and any child processes which were started by it:
```
taskkill /PID <pid1> /PID <pid2> /PID <pid3> /T
``` |
49,074,101 | This is the current dataframe:
```
> ID Date current
> 2001980 10/30/2017 1
> 2001980 10/29/2017 0
> 2001980 10/28/2017 0
> 2001980 10/27/2017 40
> 2001980 10/26/2017 39
> 2001980 10/25/2017 0
> 2001980 10/24/2017 0
> 2001980 10/23/2017 60
> 2001980 10/22/2017 0
> 2001980 10/21/2017 0
> 2002222 10/21/2017 0
> 2002222 10/20/2017 0
> 2002222 10/19/2017 16
> 2002222 10/18/2017 0
> 2002222 10/17/2017 0
> 2002222 10/16/2017 20
> 2002222 10/15/2017 19
> 2002222 10/14/2017 18
```
Below is the final data frame. Column `expected` is what I am trying to get.
1. One ID might have multiple date/record/rows. (ID+Date) is unique.
2. this row's expected value = last row's expected - 1
3. the minimum value is 0.
4. Based on the formula in 2, if this row's expected value < this row's current value, then use this row's current value. for example, for ID 2001980 on 10/23/2017. Based on rule 2, the value should be 36, but based on rule 4, 36<60, so we use 60.
thank you so much.
```
> ID Date current expected
> 2001980 10/30/2017 1 1
> 2001980 10/29/2017 0 0
> 2001980 10/28/2017 0 0
> 2001980 10/27/2017 40 40
> 2001980 10/26/2017 39 39
> 2001980 10/25/2017 0 38
> 2001980 10/24/2017 0 37
> 2001980 10/23/2017 60 60
> 2001980 10/22/2017 0 59
> 2001980 10/21/2017 0 58
> 2002222 10/21/2017 0 0
> 2002222 10/20/2017 0 0
> 2002222 10/19/2017 16 16
> 2002222 10/18/2017 0 15
> 2002222 10/17/2017 0 14
> 2002222 10/16/2017 20 20
> 2002222 10/15/2017 19 19
> 2002222 10/14/2017 18 18
```
I am using Excel with the formula below:
= if(this row's ID = last row's ID,
max(last row's expected value - 1, this row's current value),
this row's current value) | 2018/03/02 | [
"https://Stackoverflow.com/questions/49074101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6256904/"
] | So you can do this used `apply` and `nested functions`
```
import pandas as pd
ID = [2001980,2001980,2001980,2001980,2001980,2001980,2001980,2001980,2001980,2001980,2002222,2002222,2002222,2002222,2002222,2002222,2002222,2002222,]
Date = ["10/30/2017","10/29/2017","10/28/2017","10/27/2017","10/26/2017","10/25/2017","10/24/2017","10/23/2017","10/22/2017","10/21/2017","10/21/2017","10/20/2017","10/19/2017","10/18/2017","10/17/2017","10/16/2017","10/15/2017","10/14/2017",]
current = [1 ,0 ,0 ,40,39,0 ,0 ,60,0 ,0 ,0 ,0 ,16,0 ,0 ,20,19,18,]
df = pd.DataFrame({"ID": ID, "Date": Date, "current": current})
```
Then create the function to update the frame
**Python 3.X**
```
def update_frame(df):
last_expected = None
def apply_logic(row):
nonlocal last_expected
last_row_id = row.name - 1
if row.name == 0:
last_expected = row["current"]
return last_expected
last_row = df.iloc[[last_row_id]].iloc[0].to_dict()
last_expected = max(last_expected-1,row['current']) if last_row['ID'] == row['ID'] else row['current']
return last_expected
return apply_logic
```
**Python 2.X**
```
def update_frame(df):
sd = {"last_expected": None}
def apply_logic(row):
last_row_id = row.name - 1
if row.name == 0:
sd['last_expected'] = row["current"]
return sd['last_expected']
last_row = df.iloc[[last_row_id]].iloc[0].to_dict()
sd['last_expected'] = max(sd['last_expected'] - 1,row['current']) if last_row['ID'] == row['ID'] else row['current']
return sd['last_expected']
return apply_logic
```
And run the function like below
```
df['expected'] = df.apply(update_frame(df), axis=1)
```
The output is as expected
[](https://i.stack.imgur.com/yKlwN.png) | You can use a conditional statement combined with [`.shift()`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html) to get previous row, and [`np.where`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html) which AFAIK does *not* rely on loops as mentioned in a comment as something to avoid:
```
df['test'] = np.where(df['current'].shift() <
df['current'], df['current'] - 1, df['current'])
```
Result (I added a `'test'` column) with the result; you can change to `'expected'` if you so desire):
```
>>> df
ID Date current expected test
0 2001980 10/30/2017 1 1 1
1 2001980 10/29/2017 0 0 0
2 2001980 10/28/2017 0 0 0
3 2001980 10/27/2017 40 40 39
4 2001980 10/26/2017 39 39 39
5 2001980 10/25/2017 38 38 38
6 2001980 10/24/2017 37 37 37
7 2001980 10/18/2017 0 36 0
8 2001980 10/17/2017 0 35 0
9 2001980 10/16/2017 60 60 59
10 2001980 10/15/2017 0 59 0
11 2001980 10/14/2017 0 58 0
12 2001980 10/13/2017 0 57 0
13 2001980 10/12/2017 0 56 0
14 2002222 10/21/2017 0 0 0
15 2002222 10/20/2017 0 0 0
16 2002222 10/19/2017 16 16 15
17 2002222 10/18/2017 0 15 0
18 2002222 10/17/2017 0 14 0
19 2002222 10/16/2017 13 13 12
20 2002222 10/15/2017 12 12 12
21 2002222 10/14/2017 11 11 11
22 2002222 10/13/2017 10 10 10
23 2002222 10/12/2017 9 9 9
``` |
49,074,101 | This is the current dataframe:
```
> ID Date current
> 2001980 10/30/2017 1
> 2001980 10/29/2017 0
> 2001980 10/28/2017 0
> 2001980 10/27/2017 40
> 2001980 10/26/2017 39
> 2001980 10/25/2017 0
> 2001980 10/24/2017 0
> 2001980 10/23/2017 60
> 2001980 10/22/2017 0
> 2001980 10/21/2017 0
> 2002222 10/21/2017 0
> 2002222 10/20/2017 0
> 2002222 10/19/2017 16
> 2002222 10/18/2017 0
> 2002222 10/17/2017 0
> 2002222 10/16/2017 20
> 2002222 10/15/2017 19
> 2002222 10/14/2017 18
```
Below is the final data frame. Column `expected` is what I am trying to get.
1. One ID might have multiple date/record/rows. (ID+Date) is unique.
2. this row's expected value = last row's expected - 1
3. the minimum value is 0.
4. Based on the formula in 2, if this row's expected value < this row's current value, then use this row's current value. for example, for ID 2001980 on 10/23/2017. Based on rule 2, the value should be 36, but based on rule 4, 36<60, so we use 60.
thank you so much.
```
> ID Date current expected
> 2001980 10/30/2017 1 1
> 2001980 10/29/2017 0 0
> 2001980 10/28/2017 0 0
> 2001980 10/27/2017 40 40
> 2001980 10/26/2017 39 39
> 2001980 10/25/2017 0 38
> 2001980 10/24/2017 0 37
> 2001980 10/23/2017 60 60
> 2001980 10/22/2017 0 59
> 2001980 10/21/2017 0 58
> 2002222 10/21/2017 0 0
> 2002222 10/20/2017 0 0
> 2002222 10/19/2017 16 16
> 2002222 10/18/2017 0 15
> 2002222 10/17/2017 0 14
> 2002222 10/16/2017 20 20
> 2002222 10/15/2017 19 19
> 2002222 10/14/2017 18 18
```
I am using Excel with the formula below:
= if(this row's ID = last row's ID,
max(last row's expected value - 1, this row's current value),
this row's current value) | 2018/03/02 | [
"https://Stackoverflow.com/questions/49074101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6256904/"
] | Revised simpler:
```
df['expected'] = df.groupby(['ID',df.current.ne(0).cumsum()])['current']\
.transform(lambda x: x.eq(0).cumsum().mul(-1).add(x.iloc[0])).clip(0,np.inf)
```
Let's have a little fun:
```
df['expected'] = (df.groupby('ID')['current'].transform(lambda x: x.where(x.ne(0)).ffill()) +
df.groupby(['ID',df.current.ne(0).cumsum()])['current'].transform(lambda x: x.eq(0).cumsum()).mul(-1))\
.clip(0,np.inf).fillna(0).astype(int)
print(df)
```
Output:
```
ID Date current expected
0 2001980 10/30/2017 1 1
1 2001980 10/29/2017 0 0
2 2001980 10/28/2017 0 0
3 2001980 10/27/2017 40 40
4 2001980 10/26/2017 39 39
5 2001980 10/25/2017 0 38
6 2001980 10/24/2017 0 37
7 2001980 10/23/2017 60 60
8 2001980 10/22/2017 0 59
9 2001980 10/21/2017 0 58
10 2002222 10/21/2017 0 0
11 2002222 10/20/2017 0 0
12 2002222 10/19/2017 16 16
13 2002222 10/18/2017 0 15
14 2002222 10/17/2017 0 14
15 2002222 10/16/2017 20 20
16 2002222 10/15/2017 19 19
17 2002222 10/14/2017 18 18
```
Details
=======
### Basically, creating series, s1 and subtracting series s2 then clipping negative values and filling nan's with zero.
```
#Let's calculate two series first a series to fill the zeros in an 'ID' with the previous non-zero value
s1 = df.groupby('ID')['current'].transform(lambda x: x.where(x.ne(0)).ffill())
s1
```
Output:
```
0 1.0
1 1.0
2 1.0
3 40.0
4 39.0
5 39.0
6 39.0
7 60.0
8 60.0
9 60.0
10 NaN
11 NaN
12 16.0
13 16.0
14 16.0
15 20.0
16 19.0
17 18.0
Name: current, dtype: float64
#Second series is a cumulative count of zeroes in a group by 'ID'
s2 = df.groupby(['ID',df.current.ne(0).cumsum()])['current'].transform(lambda x: x.eq(0).cumsum()).mul(-1)
s2
```
Output:
```
0 0
1 -1
2 -2
3 0
4 0
5 -1
6 -2
7 0
8 -1
9 -2
10 -1
11 -2
12 0
13 -1
14 -2
15 0
16 0
17 0
Name: current, dtype: int32
```
### Add series together clip and fillna.
```
(s1 + s2).clip(0, np.inf).fillna(0)
```
Output:
```
0 1.0
1 0.0
2 0.0
3 40.0
4 39.0
5 38.0
6 37.0
7 60.0
8 59.0
9 58.0
10 0.0
11 0.0
12 16.0
13 15.0
14 14.0
15 20.0
16 19.0
17 18.0
Name: current, dtype: float64
``` | You can use a conditional statement combined with [`.shift()`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html) to get previous row, and [`np.where`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html) which AFAIK does *not* rely on loops as mentioned in a comment as something to avoid:
```
df['test'] = np.where(df['current'].shift() <
df['current'], df['current'] - 1, df['current'])
```
Result (I added a `'test'` column) with the result; you can change to `'expected'` if you so desire):
```
>>> df
ID Date current expected test
0 2001980 10/30/2017 1 1 1
1 2001980 10/29/2017 0 0 0
2 2001980 10/28/2017 0 0 0
3 2001980 10/27/2017 40 40 39
4 2001980 10/26/2017 39 39 39
5 2001980 10/25/2017 38 38 38
6 2001980 10/24/2017 37 37 37
7 2001980 10/18/2017 0 36 0
8 2001980 10/17/2017 0 35 0
9 2001980 10/16/2017 60 60 59
10 2001980 10/15/2017 0 59 0
11 2001980 10/14/2017 0 58 0
12 2001980 10/13/2017 0 57 0
13 2001980 10/12/2017 0 56 0
14 2002222 10/21/2017 0 0 0
15 2002222 10/20/2017 0 0 0
16 2002222 10/19/2017 16 16 15
17 2002222 10/18/2017 0 15 0
18 2002222 10/17/2017 0 14 0
19 2002222 10/16/2017 13 13 12
20 2002222 10/15/2017 12 12 12
21 2002222 10/14/2017 11 11 11
22 2002222 10/13/2017 10 10 10
23 2002222 10/12/2017 9 9 9
``` |
49,074,101 | This is the current dataframe:
```
> ID Date current
> 2001980 10/30/2017 1
> 2001980 10/29/2017 0
> 2001980 10/28/2017 0
> 2001980 10/27/2017 40
> 2001980 10/26/2017 39
> 2001980 10/25/2017 0
> 2001980 10/24/2017 0
> 2001980 10/23/2017 60
> 2001980 10/22/2017 0
> 2001980 10/21/2017 0
> 2002222 10/21/2017 0
> 2002222 10/20/2017 0
> 2002222 10/19/2017 16
> 2002222 10/18/2017 0
> 2002222 10/17/2017 0
> 2002222 10/16/2017 20
> 2002222 10/15/2017 19
> 2002222 10/14/2017 18
```
Below is the final data frame. Column `expected` is what I am trying to get.
1. One ID might have multiple date/record/rows. (ID+Date) is unique.
2. this row's expected value = last row's expected - 1
3. the minimum value is 0.
4. Based on the formula in 2, if this row's expected value < this row's current value, then use this row's current value. for example, for ID 2001980 on 10/23/2017. Based on rule 2, the value should be 36, but based on rule 4, 36<60, so we use 60.
thank you so much.
```
> ID Date current expected
> 2001980 10/30/2017 1 1
> 2001980 10/29/2017 0 0
> 2001980 10/28/2017 0 0
> 2001980 10/27/2017 40 40
> 2001980 10/26/2017 39 39
> 2001980 10/25/2017 0 38
> 2001980 10/24/2017 0 37
> 2001980 10/23/2017 60 60
> 2001980 10/22/2017 0 59
> 2001980 10/21/2017 0 58
> 2002222 10/21/2017 0 0
> 2002222 10/20/2017 0 0
> 2002222 10/19/2017 16 16
> 2002222 10/18/2017 0 15
> 2002222 10/17/2017 0 14
> 2002222 10/16/2017 20 20
> 2002222 10/15/2017 19 19
> 2002222 10/14/2017 18 18
```
I am using Excel with the formula below:
= if(this row's ID = last row's ID,
max(last row's expected value - 1, this row's current value),
this row's current value) | 2018/03/02 | [
"https://Stackoverflow.com/questions/49074101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6256904/"
] | So you can do this used `apply` and `nested functions`
```
import pandas as pd
ID = [2001980,2001980,2001980,2001980,2001980,2001980,2001980,2001980,2001980,2001980,2002222,2002222,2002222,2002222,2002222,2002222,2002222,2002222,]
Date = ["10/30/2017","10/29/2017","10/28/2017","10/27/2017","10/26/2017","10/25/2017","10/24/2017","10/23/2017","10/22/2017","10/21/2017","10/21/2017","10/20/2017","10/19/2017","10/18/2017","10/17/2017","10/16/2017","10/15/2017","10/14/2017",]
current = [1 ,0 ,0 ,40,39,0 ,0 ,60,0 ,0 ,0 ,0 ,16,0 ,0 ,20,19,18,]
df = pd.DataFrame({"ID": ID, "Date": Date, "current": current})
```
Then create the function to update the frame
**Python 3.X**
```
def update_frame(df):
last_expected = None
def apply_logic(row):
nonlocal last_expected
last_row_id = row.name - 1
if row.name == 0:
last_expected = row["current"]
return last_expected
last_row = df.iloc[[last_row_id]].iloc[0].to_dict()
last_expected = max(last_expected-1,row['current']) if last_row['ID'] == row['ID'] else row['current']
return last_expected
return apply_logic
```
**Python 2.X**
```
def update_frame(df):
sd = {"last_expected": None}
def apply_logic(row):
last_row_id = row.name - 1
if row.name == 0:
sd['last_expected'] = row["current"]
return sd['last_expected']
last_row = df.iloc[[last_row_id]].iloc[0].to_dict()
sd['last_expected'] = max(sd['last_expected'] - 1,row['current']) if last_row['ID'] == row['ID'] else row['current']
return sd['last_expected']
return apply_logic
```
And run the function like below
```
df['expected'] = df.apply(update_frame(df), axis=1)
```
The output is as expected
[](https://i.stack.imgur.com/yKlwN.png) | Revised simpler:
```
df['expected'] = df.groupby(['ID',df.current.ne(0).cumsum()])['current']\
.transform(lambda x: x.eq(0).cumsum().mul(-1).add(x.iloc[0])).clip(0,np.inf)
```
Let's have a little fun:
```
df['expected'] = (df.groupby('ID')['current'].transform(lambda x: x.where(x.ne(0)).ffill()) +
df.groupby(['ID',df.current.ne(0).cumsum()])['current'].transform(lambda x: x.eq(0).cumsum()).mul(-1))\
.clip(0,np.inf).fillna(0).astype(int)
print(df)
```
Output:
```
ID Date current expected
0 2001980 10/30/2017 1 1
1 2001980 10/29/2017 0 0
2 2001980 10/28/2017 0 0
3 2001980 10/27/2017 40 40
4 2001980 10/26/2017 39 39
5 2001980 10/25/2017 0 38
6 2001980 10/24/2017 0 37
7 2001980 10/23/2017 60 60
8 2001980 10/22/2017 0 59
9 2001980 10/21/2017 0 58
10 2002222 10/21/2017 0 0
11 2002222 10/20/2017 0 0
12 2002222 10/19/2017 16 16
13 2002222 10/18/2017 0 15
14 2002222 10/17/2017 0 14
15 2002222 10/16/2017 20 20
16 2002222 10/15/2017 19 19
17 2002222 10/14/2017 18 18
```
Details
=======
### Basically, creating series, s1 and subtracting series s2 then clipping negative values and filling nan's with zero.
```
#Let's calculate two series first a series to fill the zeros in an 'ID' with the previous non-zero value
s1 = df.groupby('ID')['current'].transform(lambda x: x.where(x.ne(0)).ffill())
s1
```
Output:
```
0 1.0
1 1.0
2 1.0
3 40.0
4 39.0
5 39.0
6 39.0
7 60.0
8 60.0
9 60.0
10 NaN
11 NaN
12 16.0
13 16.0
14 16.0
15 20.0
16 19.0
17 18.0
Name: current, dtype: float64
#Second series is a cumulative count of zeroes in a group by 'ID'
s2 = df.groupby(['ID',df.current.ne(0).cumsum()])['current'].transform(lambda x: x.eq(0).cumsum()).mul(-1)
s2
```
Output:
```
0 0
1 -1
2 -2
3 0
4 0
5 -1
6 -2
7 0
8 -1
9 -2
10 -1
11 -2
12 0
13 -1
14 -2
15 0
16 0
17 0
Name: current, dtype: int32
```
### Add series together clip and fillna.
```
(s1 + s2).clip(0, np.inf).fillna(0)
```
Output:
```
0 1.0
1 0.0
2 0.0
3 40.0
4 39.0
5 38.0
6 37.0
7 60.0
8 59.0
9 58.0
10 0.0
11 0.0
12 16.0
13 15.0
14 14.0
15 20.0
16 19.0
17 18.0
Name: current, dtype: float64
``` |
49,074,101 | This is the current dataframe:
```
> ID Date current
> 2001980 10/30/2017 1
> 2001980 10/29/2017 0
> 2001980 10/28/2017 0
> 2001980 10/27/2017 40
> 2001980 10/26/2017 39
> 2001980 10/25/2017 0
> 2001980 10/24/2017 0
> 2001980 10/23/2017 60
> 2001980 10/22/2017 0
> 2001980 10/21/2017 0
> 2002222 10/21/2017 0
> 2002222 10/20/2017 0
> 2002222 10/19/2017 16
> 2002222 10/18/2017 0
> 2002222 10/17/2017 0
> 2002222 10/16/2017 20
> 2002222 10/15/2017 19
> 2002222 10/14/2017 18
```
Below is the final data frame. Column `expected` is what I am trying to get.
1. One ID might have multiple date/record/rows. (ID+Date) is unique.
2. this row's expected value = last row's expected - 1
3. the minimum value is 0.
4. Based on the formula in 2, if this row's expected value < this row's current value, then use this row's current value. for example, for ID 2001980 on 10/23/2017. Based on rule 2, the value should be 36, but based on rule 4, 36<60, so we use 60.
thank you so much.
```
> ID Date current expected
> 2001980 10/30/2017 1 1
> 2001980 10/29/2017 0 0
> 2001980 10/28/2017 0 0
> 2001980 10/27/2017 40 40
> 2001980 10/26/2017 39 39
> 2001980 10/25/2017 0 38
> 2001980 10/24/2017 0 37
> 2001980 10/23/2017 60 60
> 2001980 10/22/2017 0 59
> 2001980 10/21/2017 0 58
> 2002222 10/21/2017 0 0
> 2002222 10/20/2017 0 0
> 2002222 10/19/2017 16 16
> 2002222 10/18/2017 0 15
> 2002222 10/17/2017 0 14
> 2002222 10/16/2017 20 20
> 2002222 10/15/2017 19 19
> 2002222 10/14/2017 18 18
```
I am using Excel with the formula below:
= if(this row's ID = last row's ID,
max(last row's expected value - 1, this row's current value),
this row's current value) | 2018/03/02 | [
"https://Stackoverflow.com/questions/49074101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6256904/"
] | So you can do this used `apply` and `nested functions`
```
import pandas as pd
ID = [2001980,2001980,2001980,2001980,2001980,2001980,2001980,2001980,2001980,2001980,2002222,2002222,2002222,2002222,2002222,2002222,2002222,2002222,]
Date = ["10/30/2017","10/29/2017","10/28/2017","10/27/2017","10/26/2017","10/25/2017","10/24/2017","10/23/2017","10/22/2017","10/21/2017","10/21/2017","10/20/2017","10/19/2017","10/18/2017","10/17/2017","10/16/2017","10/15/2017","10/14/2017",]
current = [1 ,0 ,0 ,40,39,0 ,0 ,60,0 ,0 ,0 ,0 ,16,0 ,0 ,20,19,18,]
df = pd.DataFrame({"ID": ID, "Date": Date, "current": current})
```
Then create the function to update the frame
**Python 3.X**
```
def update_frame(df):
last_expected = None
def apply_logic(row):
nonlocal last_expected
last_row_id = row.name - 1
if row.name == 0:
last_expected = row["current"]
return last_expected
last_row = df.iloc[[last_row_id]].iloc[0].to_dict()
last_expected = max(last_expected-1,row['current']) if last_row['ID'] == row['ID'] else row['current']
return last_expected
return apply_logic
```
**Python 2.X**
```
def update_frame(df):
sd = {"last_expected": None}
def apply_logic(row):
last_row_id = row.name - 1
if row.name == 0:
sd['last_expected'] = row["current"]
return sd['last_expected']
last_row = df.iloc[[last_row_id]].iloc[0].to_dict()
sd['last_expected'] = max(sd['last_expected'] - 1,row['current']) if last_row['ID'] == row['ID'] else row['current']
return sd['last_expected']
return apply_logic
```
And run the function like below
```
df['expected'] = df.apply(update_frame(df), axis=1)
```
The output is as expected
[](https://i.stack.imgur.com/yKlwN.png) | EDIT: To address OP's concern about scaling up to millions of rows.
Yes, my original answer will not scale to very large dataframes. However, with minor edits, this easy-to-read solution will scale. The optimizations that follow take advantage of the JIT compiler in Numba. After importing Numba, I add the jit decorator and modified the function to operate on a numpy arrays instead of the pandas objects. Numba is numpy-aware and cannot optimize pandas objects.
```
import numba
@numba.jit
def expected(id_col, current_col):
lexp = []
lstID = 0
expected = 0
for i in range(len(id_col)):
id, current = id_col[i], current_col[i]
if id == lstID:
expected = max(current, max(expected - 1, 0))
else:
expected = current
lexp.append(expected)
lstID = id
return np.array(lexp)
```
To pass a numpy array to the function, use the `.values` attribute of the pandas series.
```
df1['expected'] = expected(df1.ID.values, df1.current.values)
```
To test the performance, I scaled up your original dataframe to more than 1 million rows.
```
df1 = df
while len(df1) < 1000000:
df1 = pd.concat([df1, df1])
df1.reset_index(inplace=True, drop=True)
```
The new changes perform very well.
```
%timeit expected(df1.ID.values, df1.current.values)
44.9 ms ± 249 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
df1.shape
Out[65]: (1179648, 4)
df1.tail(15)
Out[66]:
ID Date current expected
1179633 2001980 10/27/2017 40 40
1179634 2001980 10/26/2017 39 39
1179635 2001980 10/25/2017 0 38
1179636 2001980 10/24/2017 0 37
1179637 2001980 10/23/2017 60 60
1179638 2001980 10/22/2017 0 59
1179639 2001980 10/21/2017 0 58
1179640 2002222 10/21/2017 0 0
1179641 2002222 10/20/2017 0 0
1179642 2002222 10/19/2017 16 16
1179643 2002222 10/18/2017 0 15
1179644 2002222 10/17/2017 0 14
1179645 2002222 10/16/2017 20 20
1179646 2002222 10/15/2017 19 19
1179647 2002222 10/14/2017 18 18
```
---
ORIGINAL ANSWER
A little brute force but really easy to follow.
```
def expected(df):
lexp = []
lstID = None
expected = 0
for i in range(len(df)):
id, current = df[['ID', 'current']].iloc[i]
if id == lstID:
expected = max(expected - 1, 0)
expected = max(current, expected)
else:
expected = current
lexp.append(expected)
lstID = id
return pd.Series(lexp)
```
Output
```
df['expected'] = expected(df)
df
Out[53]:
ID Date current expected
0 2001980 10/30/2017 1 1
1 2001980 10/29/2017 0 0
2 2001980 10/28/2017 0 0
3 2001980 10/27/2017 40 40
4 2001980 10/26/2017 39 39
5 2001980 10/25/2017 0 38
6 2001980 10/24/2017 0 37
7 2001980 10/23/2017 60 60
8 2001980 10/22/2017 0 59
9 2001980 10/21/2017 0 58
10 2002222 10/21/2017 0 0
11 2002222 10/20/2017 0 0
12 2002222 10/19/2017 16 16
13 2002222 10/18/2017 0 15
14 2002222 10/17/2017 0 14
15 2002222 10/16/2017 20 20
16 2002222 10/15/2017 19 19
17 2002222 10/14/2017 18 18
``` |
49,074,101 | This is the current dataframe:
```
> ID Date current
> 2001980 10/30/2017 1
> 2001980 10/29/2017 0
> 2001980 10/28/2017 0
> 2001980 10/27/2017 40
> 2001980 10/26/2017 39
> 2001980 10/25/2017 0
> 2001980 10/24/2017 0
> 2001980 10/23/2017 60
> 2001980 10/22/2017 0
> 2001980 10/21/2017 0
> 2002222 10/21/2017 0
> 2002222 10/20/2017 0
> 2002222 10/19/2017 16
> 2002222 10/18/2017 0
> 2002222 10/17/2017 0
> 2002222 10/16/2017 20
> 2002222 10/15/2017 19
> 2002222 10/14/2017 18
```
Below is the final data frame. Column `expected` is what I am trying to get.
1. One ID might have multiple date/record/rows. (ID+Date) is unique.
2. this row's expected value = last row's expected - 1
3. the minimum value is 0.
4. Based on the formula in 2, if this row's expected value < this row's current value, then use this row's current value. for example, for ID 2001980 on 10/23/2017. Based on rule 2, the value should be 36, but based on rule 4, 36<60, so we use 60.
thank you so much.
```
> ID Date current expected
> 2001980 10/30/2017 1 1
> 2001980 10/29/2017 0 0
> 2001980 10/28/2017 0 0
> 2001980 10/27/2017 40 40
> 2001980 10/26/2017 39 39
> 2001980 10/25/2017 0 38
> 2001980 10/24/2017 0 37
> 2001980 10/23/2017 60 60
> 2001980 10/22/2017 0 59
> 2001980 10/21/2017 0 58
> 2002222 10/21/2017 0 0
> 2002222 10/20/2017 0 0
> 2002222 10/19/2017 16 16
> 2002222 10/18/2017 0 15
> 2002222 10/17/2017 0 14
> 2002222 10/16/2017 20 20
> 2002222 10/15/2017 19 19
> 2002222 10/14/2017 18 18
```
I am using Excel with the formula below:
= if(this row's ID = last row's ID,
max(last row's expected value - 1, this row's current value),
this row's current value) | 2018/03/02 | [
"https://Stackoverflow.com/questions/49074101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6256904/"
] | So you can do this used `apply` and `nested functions`
```
import pandas as pd
ID = [2001980,2001980,2001980,2001980,2001980,2001980,2001980,2001980,2001980,2001980,2002222,2002222,2002222,2002222,2002222,2002222,2002222,2002222,]
Date = ["10/30/2017","10/29/2017","10/28/2017","10/27/2017","10/26/2017","10/25/2017","10/24/2017","10/23/2017","10/22/2017","10/21/2017","10/21/2017","10/20/2017","10/19/2017","10/18/2017","10/17/2017","10/16/2017","10/15/2017","10/14/2017",]
current = [1 ,0 ,0 ,40,39,0 ,0 ,60,0 ,0 ,0 ,0 ,16,0 ,0 ,20,19,18,]
df = pd.DataFrame({"ID": ID, "Date": Date, "current": current})
```
Then create the function to update the frame
**Python 3.X**
```
def update_frame(df):
last_expected = None
def apply_logic(row):
nonlocal last_expected
last_row_id = row.name - 1
if row.name == 0:
last_expected = row["current"]
return last_expected
last_row = df.iloc[[last_row_id]].iloc[0].to_dict()
last_expected = max(last_expected-1,row['current']) if last_row['ID'] == row['ID'] else row['current']
return last_expected
return apply_logic
```
**Python 2.X**
```
def update_frame(df):
sd = {"last_expected": None}
def apply_logic(row):
last_row_id = row.name - 1
if row.name == 0:
sd['last_expected'] = row["current"]
return sd['last_expected']
last_row = df.iloc[[last_row_id]].iloc[0].to_dict()
sd['last_expected'] = max(sd['last_expected'] - 1,row['current']) if last_row['ID'] == row['ID'] else row['current']
return sd['last_expected']
return apply_logic
```
And run the function like below
```
df['expected'] = df.apply(update_frame(df), axis=1)
```
The output is as expected
[](https://i.stack.imgur.com/yKlwN.png) | I believe @Tarun Lalwani had pointed you to one right direction. that is to save some critical information outside the DataFrame. the code can be simplified though, and there is nothing wrong with using global variables as long as you manage name properly. it's one of the design patterns which can often make things simpler and improve readability.
```
cached_last = { 'expected': None, 'ID': None }
def set_expected(x):
if cached_last['ID'] is None or x.ID != cached_last['ID']:
expected = x.current
else:
expected = max(cached_last['expected'] - 1, x.current)
cached_last['ID'] = x.ID
cached_last['expected'] = expected
return expected
df['expected'] = df.apply(set_expected, axis=1)
```
From the documentation on pandas.DataFrame.apply, do be careful about the potential side-effects of the `apply` function.
```
In the current implementation apply calls func twice on the first column/row to decide whether it can take a fast or slow code path. This can lead to unexpected behavior if func has side-effects, as they will take effect twice for the first column/row.
``` |
49,074,101 | This is the current dataframe:
```
> ID Date current
> 2001980 10/30/2017 1
> 2001980 10/29/2017 0
> 2001980 10/28/2017 0
> 2001980 10/27/2017 40
> 2001980 10/26/2017 39
> 2001980 10/25/2017 0
> 2001980 10/24/2017 0
> 2001980 10/23/2017 60
> 2001980 10/22/2017 0
> 2001980 10/21/2017 0
> 2002222 10/21/2017 0
> 2002222 10/20/2017 0
> 2002222 10/19/2017 16
> 2002222 10/18/2017 0
> 2002222 10/17/2017 0
> 2002222 10/16/2017 20
> 2002222 10/15/2017 19
> 2002222 10/14/2017 18
```
Below is the final data frame. Column `expected` is what I am trying to get.
1. One ID might have multiple date/record/rows. (ID+Date) is unique.
2. this row's expected value = last row's expected - 1
3. the minimum value is 0.
4. Based on the formula in 2, if this row's expected value < this row's current value, then use this row's current value. for example, for ID 2001980 on 10/23/2017. Based on rule 2, the value should be 36, but based on rule 4, 36<60, so we use 60.
thank you so much.
```
> ID Date current expected
> 2001980 10/30/2017 1 1
> 2001980 10/29/2017 0 0
> 2001980 10/28/2017 0 0
> 2001980 10/27/2017 40 40
> 2001980 10/26/2017 39 39
> 2001980 10/25/2017 0 38
> 2001980 10/24/2017 0 37
> 2001980 10/23/2017 60 60
> 2001980 10/22/2017 0 59
> 2001980 10/21/2017 0 58
> 2002222 10/21/2017 0 0
> 2002222 10/20/2017 0 0
> 2002222 10/19/2017 16 16
> 2002222 10/18/2017 0 15
> 2002222 10/17/2017 0 14
> 2002222 10/16/2017 20 20
> 2002222 10/15/2017 19 19
> 2002222 10/14/2017 18 18
```
I am using Excel with the formula below:
= if(this row's ID = last row's ID,
max(last row's expected value - 1, this row's current value),
this row's current value) | 2018/03/02 | [
"https://Stackoverflow.com/questions/49074101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6256904/"
] | So you can do this used `apply` and `nested functions`
```
import pandas as pd
ID = [2001980,2001980,2001980,2001980,2001980,2001980,2001980,2001980,2001980,2001980,2002222,2002222,2002222,2002222,2002222,2002222,2002222,2002222,]
Date = ["10/30/2017","10/29/2017","10/28/2017","10/27/2017","10/26/2017","10/25/2017","10/24/2017","10/23/2017","10/22/2017","10/21/2017","10/21/2017","10/20/2017","10/19/2017","10/18/2017","10/17/2017","10/16/2017","10/15/2017","10/14/2017",]
current = [1 ,0 ,0 ,40,39,0 ,0 ,60,0 ,0 ,0 ,0 ,16,0 ,0 ,20,19,18,]
df = pd.DataFrame({"ID": ID, "Date": Date, "current": current})
```
Then create the function to update the frame
**Python 3.X**
```
def update_frame(df):
last_expected = None
def apply_logic(row):
nonlocal last_expected
last_row_id = row.name - 1
if row.name == 0:
last_expected = row["current"]
return last_expected
last_row = df.iloc[[last_row_id]].iloc[0].to_dict()
last_expected = max(last_expected-1,row['current']) if last_row['ID'] == row['ID'] else row['current']
return last_expected
return apply_logic
```
**Python 2.X**
```
def update_frame(df):
sd = {"last_expected": None}
def apply_logic(row):
last_row_id = row.name - 1
if row.name == 0:
sd['last_expected'] = row["current"]
return sd['last_expected']
last_row = df.iloc[[last_row_id]].iloc[0].to_dict()
sd['last_expected'] = max(sd['last_expected'] - 1,row['current']) if last_row['ID'] == row['ID'] else row['current']
return sd['last_expected']
return apply_logic
```
And run the function like below
```
df['expected'] = df.apply(update_frame(df), axis=1)
```
The output is as expected
[](https://i.stack.imgur.com/yKlwN.png) | Logic here should be work
```
lst=[]
for _, y in df.groupby('ID'):
z=[]
for i,(_, x) in enumerate(y.iterrows()):
print(x)
if x['current'] > 0:
z.append(x['current'])
else:
try:
z.append(max(z[i-1]-1,0))
except:
z.append(0)
lst.extend(z)
lst
Out[484]: [1, 0, 0, 40, 39, 38, 37, 60, 59, 58, 0, 0, 16, 15, 14, 20, 19, 18]
``` |
49,074,101 | This is the current dataframe:
```
> ID Date current
> 2001980 10/30/2017 1
> 2001980 10/29/2017 0
> 2001980 10/28/2017 0
> 2001980 10/27/2017 40
> 2001980 10/26/2017 39
> 2001980 10/25/2017 0
> 2001980 10/24/2017 0
> 2001980 10/23/2017 60
> 2001980 10/22/2017 0
> 2001980 10/21/2017 0
> 2002222 10/21/2017 0
> 2002222 10/20/2017 0
> 2002222 10/19/2017 16
> 2002222 10/18/2017 0
> 2002222 10/17/2017 0
> 2002222 10/16/2017 20
> 2002222 10/15/2017 19
> 2002222 10/14/2017 18
```
Below is the final data frame. Column `expected` is what I am trying to get.
1. One ID might have multiple date/record/rows. (ID+Date) is unique.
2. this row's expected value = last row's expected - 1
3. the minimum value is 0.
4. Based on the formula in 2, if this row's expected value < this row's current value, then use this row's current value. for example, for ID 2001980 on 10/23/2017. Based on rule 2, the value should be 36, but based on rule 4, 36<60, so we use 60.
thank you so much.
```
> ID Date current expected
> 2001980 10/30/2017 1 1
> 2001980 10/29/2017 0 0
> 2001980 10/28/2017 0 0
> 2001980 10/27/2017 40 40
> 2001980 10/26/2017 39 39
> 2001980 10/25/2017 0 38
> 2001980 10/24/2017 0 37
> 2001980 10/23/2017 60 60
> 2001980 10/22/2017 0 59
> 2001980 10/21/2017 0 58
> 2002222 10/21/2017 0 0
> 2002222 10/20/2017 0 0
> 2002222 10/19/2017 16 16
> 2002222 10/18/2017 0 15
> 2002222 10/17/2017 0 14
> 2002222 10/16/2017 20 20
> 2002222 10/15/2017 19 19
> 2002222 10/14/2017 18 18
```
I am using Excel with the formula below:
= if(this row's ID = last row's ID,
max(last row's expected value - 1, this row's current value),
this row's current value) | 2018/03/02 | [
"https://Stackoverflow.com/questions/49074101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6256904/"
] | Revised simpler:
```
df['expected'] = df.groupby(['ID',df.current.ne(0).cumsum()])['current']\
.transform(lambda x: x.eq(0).cumsum().mul(-1).add(x.iloc[0])).clip(0,np.inf)
```
Let's have a little fun:
```
df['expected'] = (df.groupby('ID')['current'].transform(lambda x: x.where(x.ne(0)).ffill()) +
df.groupby(['ID',df.current.ne(0).cumsum()])['current'].transform(lambda x: x.eq(0).cumsum()).mul(-1))\
.clip(0,np.inf).fillna(0).astype(int)
print(df)
```
Output:
```
ID Date current expected
0 2001980 10/30/2017 1 1
1 2001980 10/29/2017 0 0
2 2001980 10/28/2017 0 0
3 2001980 10/27/2017 40 40
4 2001980 10/26/2017 39 39
5 2001980 10/25/2017 0 38
6 2001980 10/24/2017 0 37
7 2001980 10/23/2017 60 60
8 2001980 10/22/2017 0 59
9 2001980 10/21/2017 0 58
10 2002222 10/21/2017 0 0
11 2002222 10/20/2017 0 0
12 2002222 10/19/2017 16 16
13 2002222 10/18/2017 0 15
14 2002222 10/17/2017 0 14
15 2002222 10/16/2017 20 20
16 2002222 10/15/2017 19 19
17 2002222 10/14/2017 18 18
```
Details
=======
### Basically, creating series, s1 and subtracting series s2 then clipping negative values and filling nan's with zero.
```
#Let's calculate two series first a series to fill the zeros in an 'ID' with the previous non-zero value
s1 = df.groupby('ID')['current'].transform(lambda x: x.where(x.ne(0)).ffill())
s1
```
Output:
```
0 1.0
1 1.0
2 1.0
3 40.0
4 39.0
5 39.0
6 39.0
7 60.0
8 60.0
9 60.0
10 NaN
11 NaN
12 16.0
13 16.0
14 16.0
15 20.0
16 19.0
17 18.0
Name: current, dtype: float64
#Second series is a cumulative count of zeroes in a group by 'ID'
s2 = df.groupby(['ID',df.current.ne(0).cumsum()])['current'].transform(lambda x: x.eq(0).cumsum()).mul(-1)
s2
```
Output:
```
0 0
1 -1
2 -2
3 0
4 0
5 -1
6 -2
7 0
8 -1
9 -2
10 -1
11 -2
12 0
13 -1
14 -2
15 0
16 0
17 0
Name: current, dtype: int32
```
### Add series together clip and fillna.
```
(s1 + s2).clip(0, np.inf).fillna(0)
```
Output:
```
0 1.0
1 0.0
2 0.0
3 40.0
4 39.0
5 38.0
6 37.0
7 60.0
8 59.0
9 58.0
10 0.0
11 0.0
12 16.0
13 15.0
14 14.0
15 20.0
16 19.0
17 18.0
Name: current, dtype: float64
``` | EDIT: To address OP's concern about scaling up to millions of rows.
Yes, my original answer will not scale to very large dataframes. However, with minor edits, this easy-to-read solution will scale. The optimizations that follow take advantage of the JIT compiler in Numba. After importing Numba, I add the jit decorator and modified the function to operate on a numpy arrays instead of the pandas objects. Numba is numpy-aware and cannot optimize pandas objects.
```
import numba
@numba.jit
def expected(id_col, current_col):
lexp = []
lstID = 0
expected = 0
for i in range(len(id_col)):
id, current = id_col[i], current_col[i]
if id == lstID:
expected = max(current, max(expected - 1, 0))
else:
expected = current
lexp.append(expected)
lstID = id
return np.array(lexp)
```
To pass a numpy array to the function, use the `.values` attribute of the pandas series.
```
df1['expected'] = expected(df1.ID.values, df1.current.values)
```
To test the performance, I scaled up your original dataframe to more than 1 million rows.
```
df1 = df
while len(df1) < 1000000:
df1 = pd.concat([df1, df1])
df1.reset_index(inplace=True, drop=True)
```
The new changes perform very well.
```
%timeit expected(df1.ID.values, df1.current.values)
44.9 ms ± 249 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
df1.shape
Out[65]: (1179648, 4)
df1.tail(15)
Out[66]:
ID Date current expected
1179633 2001980 10/27/2017 40 40
1179634 2001980 10/26/2017 39 39
1179635 2001980 10/25/2017 0 38
1179636 2001980 10/24/2017 0 37
1179637 2001980 10/23/2017 60 60
1179638 2001980 10/22/2017 0 59
1179639 2001980 10/21/2017 0 58
1179640 2002222 10/21/2017 0 0
1179641 2002222 10/20/2017 0 0
1179642 2002222 10/19/2017 16 16
1179643 2002222 10/18/2017 0 15
1179644 2002222 10/17/2017 0 14
1179645 2002222 10/16/2017 20 20
1179646 2002222 10/15/2017 19 19
1179647 2002222 10/14/2017 18 18
```
---
ORIGINAL ANSWER
A little brute force but really easy to follow.
```
def expected(df):
lexp = []
lstID = None
expected = 0
for i in range(len(df)):
id, current = df[['ID', 'current']].iloc[i]
if id == lstID:
expected = max(expected - 1, 0)
expected = max(current, expected)
else:
expected = current
lexp.append(expected)
lstID = id
return pd.Series(lexp)
```
Output
```
df['expected'] = expected(df)
df
Out[53]:
ID Date current expected
0 2001980 10/30/2017 1 1
1 2001980 10/29/2017 0 0
2 2001980 10/28/2017 0 0
3 2001980 10/27/2017 40 40
4 2001980 10/26/2017 39 39
5 2001980 10/25/2017 0 38
6 2001980 10/24/2017 0 37
7 2001980 10/23/2017 60 60
8 2001980 10/22/2017 0 59
9 2001980 10/21/2017 0 58
10 2002222 10/21/2017 0 0
11 2002222 10/20/2017 0 0
12 2002222 10/19/2017 16 16
13 2002222 10/18/2017 0 15
14 2002222 10/17/2017 0 14
15 2002222 10/16/2017 20 20
16 2002222 10/15/2017 19 19
17 2002222 10/14/2017 18 18
``` |
49,074,101 | This is the current dataframe:
```
> ID Date current
> 2001980 10/30/2017 1
> 2001980 10/29/2017 0
> 2001980 10/28/2017 0
> 2001980 10/27/2017 40
> 2001980 10/26/2017 39
> 2001980 10/25/2017 0
> 2001980 10/24/2017 0
> 2001980 10/23/2017 60
> 2001980 10/22/2017 0
> 2001980 10/21/2017 0
> 2002222 10/21/2017 0
> 2002222 10/20/2017 0
> 2002222 10/19/2017 16
> 2002222 10/18/2017 0
> 2002222 10/17/2017 0
> 2002222 10/16/2017 20
> 2002222 10/15/2017 19
> 2002222 10/14/2017 18
```
Below is the final data frame. Column `expected` is what I am trying to get.
1. One ID might have multiple date/record/rows. (ID+Date) is unique.
2. this row's expected value = last row's expected - 1
3. the minimum value is 0.
4. Based on the formula in 2, if this row's expected value < this row's current value, then use this row's current value. for example, for ID 2001980 on 10/23/2017. Based on rule 2, the value should be 36, but based on rule 4, 36<60, so we use 60.
thank you so much.
```
> ID Date current expected
> 2001980 10/30/2017 1 1
> 2001980 10/29/2017 0 0
> 2001980 10/28/2017 0 0
> 2001980 10/27/2017 40 40
> 2001980 10/26/2017 39 39
> 2001980 10/25/2017 0 38
> 2001980 10/24/2017 0 37
> 2001980 10/23/2017 60 60
> 2001980 10/22/2017 0 59
> 2001980 10/21/2017 0 58
> 2002222 10/21/2017 0 0
> 2002222 10/20/2017 0 0
> 2002222 10/19/2017 16 16
> 2002222 10/18/2017 0 15
> 2002222 10/17/2017 0 14
> 2002222 10/16/2017 20 20
> 2002222 10/15/2017 19 19
> 2002222 10/14/2017 18 18
```
I am using Excel with the formula below:
= if(this row's ID = last row's ID,
max(last row's expected value - 1, this row's current value),
this row's current value) | 2018/03/02 | [
"https://Stackoverflow.com/questions/49074101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6256904/"
] | Revised simpler:
```
df['expected'] = df.groupby(['ID',df.current.ne(0).cumsum()])['current']\
.transform(lambda x: x.eq(0).cumsum().mul(-1).add(x.iloc[0])).clip(0,np.inf)
```
Let's have a little fun:
```
df['expected'] = (df.groupby('ID')['current'].transform(lambda x: x.where(x.ne(0)).ffill()) +
df.groupby(['ID',df.current.ne(0).cumsum()])['current'].transform(lambda x: x.eq(0).cumsum()).mul(-1))\
.clip(0,np.inf).fillna(0).astype(int)
print(df)
```
Output:
```
ID Date current expected
0 2001980 10/30/2017 1 1
1 2001980 10/29/2017 0 0
2 2001980 10/28/2017 0 0
3 2001980 10/27/2017 40 40
4 2001980 10/26/2017 39 39
5 2001980 10/25/2017 0 38
6 2001980 10/24/2017 0 37
7 2001980 10/23/2017 60 60
8 2001980 10/22/2017 0 59
9 2001980 10/21/2017 0 58
10 2002222 10/21/2017 0 0
11 2002222 10/20/2017 0 0
12 2002222 10/19/2017 16 16
13 2002222 10/18/2017 0 15
14 2002222 10/17/2017 0 14
15 2002222 10/16/2017 20 20
16 2002222 10/15/2017 19 19
17 2002222 10/14/2017 18 18
```
Details
=======
### Basically, creating series, s1 and subtracting series s2 then clipping negative values and filling nan's with zero.
```
#Let's calculate two series first a series to fill the zeros in an 'ID' with the previous non-zero value
s1 = df.groupby('ID')['current'].transform(lambda x: x.where(x.ne(0)).ffill())
s1
```
Output:
```
0 1.0
1 1.0
2 1.0
3 40.0
4 39.0
5 39.0
6 39.0
7 60.0
8 60.0
9 60.0
10 NaN
11 NaN
12 16.0
13 16.0
14 16.0
15 20.0
16 19.0
17 18.0
Name: current, dtype: float64
#Second series is a cumulative count of zeroes in a group by 'ID'
s2 = df.groupby(['ID',df.current.ne(0).cumsum()])['current'].transform(lambda x: x.eq(0).cumsum()).mul(-1)
s2
```
Output:
```
0 0
1 -1
2 -2
3 0
4 0
5 -1
6 -2
7 0
8 -1
9 -2
10 -1
11 -2
12 0
13 -1
14 -2
15 0
16 0
17 0
Name: current, dtype: int32
```
### Add series together clip and fillna.
```
(s1 + s2).clip(0, np.inf).fillna(0)
```
Output:
```
0 1.0
1 0.0
2 0.0
3 40.0
4 39.0
5 38.0
6 37.0
7 60.0
8 59.0
9 58.0
10 0.0
11 0.0
12 16.0
13 15.0
14 14.0
15 20.0
16 19.0
17 18.0
Name: current, dtype: float64
``` | I believe @Tarun Lalwani had pointed you to one right direction. that is to save some critical information outside the DataFrame. the code can be simplified though, and there is nothing wrong with using global variables as long as you manage name properly. it's one of the design patterns which can often make things simpler and improve readability.
```
cached_last = { 'expected': None, 'ID': None }
def set_expected(x):
if cached_last['ID'] is None or x.ID != cached_last['ID']:
expected = x.current
else:
expected = max(cached_last['expected'] - 1, x.current)
cached_last['ID'] = x.ID
cached_last['expected'] = expected
return expected
df['expected'] = df.apply(set_expected, axis=1)
```
From the documentation on pandas.DataFrame.apply, do be careful about the potential side-effects of the `apply` function.
```
In the current implementation apply calls func twice on the first column/row to decide whether it can take a fast or slow code path. This can lead to unexpected behavior if func has side-effects, as they will take effect twice for the first column/row.
``` |
49,074,101 | This is the current dataframe:
```
> ID Date current
> 2001980 10/30/2017 1
> 2001980 10/29/2017 0
> 2001980 10/28/2017 0
> 2001980 10/27/2017 40
> 2001980 10/26/2017 39
> 2001980 10/25/2017 0
> 2001980 10/24/2017 0
> 2001980 10/23/2017 60
> 2001980 10/22/2017 0
> 2001980 10/21/2017 0
> 2002222 10/21/2017 0
> 2002222 10/20/2017 0
> 2002222 10/19/2017 16
> 2002222 10/18/2017 0
> 2002222 10/17/2017 0
> 2002222 10/16/2017 20
> 2002222 10/15/2017 19
> 2002222 10/14/2017 18
```
Below is the final data frame. Column `expected` is what I am trying to get.
1. One ID might have multiple date/record/rows. (ID+Date) is unique.
2. this row's expected value = last row's expected - 1
3. the minimum value is 0.
4. Based on the formula in 2, if this row's expected value < this row's current value, then use this row's current value. for example, for ID 2001980 on 10/23/2017. Based on rule 2, the value should be 36, but based on rule 4, 36<60, so we use 60.
thank you so much.
```
> ID Date current expected
> 2001980 10/30/2017 1 1
> 2001980 10/29/2017 0 0
> 2001980 10/28/2017 0 0
> 2001980 10/27/2017 40 40
> 2001980 10/26/2017 39 39
> 2001980 10/25/2017 0 38
> 2001980 10/24/2017 0 37
> 2001980 10/23/2017 60 60
> 2001980 10/22/2017 0 59
> 2001980 10/21/2017 0 58
> 2002222 10/21/2017 0 0
> 2002222 10/20/2017 0 0
> 2002222 10/19/2017 16 16
> 2002222 10/18/2017 0 15
> 2002222 10/17/2017 0 14
> 2002222 10/16/2017 20 20
> 2002222 10/15/2017 19 19
> 2002222 10/14/2017 18 18
```
I am using Excel with the formula below:
= if(this row's ID = last row's ID,
max(last row's expected value - 1, this row's current value),
this row's current value) | 2018/03/02 | [
"https://Stackoverflow.com/questions/49074101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6256904/"
] | Revised simpler:
```
df['expected'] = df.groupby(['ID',df.current.ne(0).cumsum()])['current']\
.transform(lambda x: x.eq(0).cumsum().mul(-1).add(x.iloc[0])).clip(0,np.inf)
```
Let's have a little fun:
```
df['expected'] = (df.groupby('ID')['current'].transform(lambda x: x.where(x.ne(0)).ffill()) +
df.groupby(['ID',df.current.ne(0).cumsum()])['current'].transform(lambda x: x.eq(0).cumsum()).mul(-1))\
.clip(0,np.inf).fillna(0).astype(int)
print(df)
```
Output:
```
ID Date current expected
0 2001980 10/30/2017 1 1
1 2001980 10/29/2017 0 0
2 2001980 10/28/2017 0 0
3 2001980 10/27/2017 40 40
4 2001980 10/26/2017 39 39
5 2001980 10/25/2017 0 38
6 2001980 10/24/2017 0 37
7 2001980 10/23/2017 60 60
8 2001980 10/22/2017 0 59
9 2001980 10/21/2017 0 58
10 2002222 10/21/2017 0 0
11 2002222 10/20/2017 0 0
12 2002222 10/19/2017 16 16
13 2002222 10/18/2017 0 15
14 2002222 10/17/2017 0 14
15 2002222 10/16/2017 20 20
16 2002222 10/15/2017 19 19
17 2002222 10/14/2017 18 18
```
Details
=======
### Basically, creating series, s1 and subtracting series s2 then clipping negative values and filling nan's with zero.
```
#Let's calculate two series first a series to fill the zeros in an 'ID' with the previous non-zero value
s1 = df.groupby('ID')['current'].transform(lambda x: x.where(x.ne(0)).ffill())
s1
```
Output:
```
0 1.0
1 1.0
2 1.0
3 40.0
4 39.0
5 39.0
6 39.0
7 60.0
8 60.0
9 60.0
10 NaN
11 NaN
12 16.0
13 16.0
14 16.0
15 20.0
16 19.0
17 18.0
Name: current, dtype: float64
#Second series is a cumulative count of zeroes in a group by 'ID'
s2 = df.groupby(['ID',df.current.ne(0).cumsum()])['current'].transform(lambda x: x.eq(0).cumsum()).mul(-1)
s2
```
Output:
```
0 0
1 -1
2 -2
3 0
4 0
5 -1
6 -2
7 0
8 -1
9 -2
10 -1
11 -2
12 0
13 -1
14 -2
15 0
16 0
17 0
Name: current, dtype: int32
```
### Add series together clip and fillna.
```
(s1 + s2).clip(0, np.inf).fillna(0)
```
Output:
```
0 1.0
1 0.0
2 0.0
3 40.0
4 39.0
5 38.0
6 37.0
7 60.0
8 59.0
9 58.0
10 0.0
11 0.0
12 16.0
13 15.0
14 14.0
15 20.0
16 19.0
17 18.0
Name: current, dtype: float64
``` | Logic here should be work
```
lst=[]
for _, y in df.groupby('ID'):
z=[]
for i,(_, x) in enumerate(y.iterrows()):
print(x)
if x['current'] > 0:
z.append(x['current'])
else:
try:
z.append(max(z[i-1]-1,0))
except:
z.append(0)
lst.extend(z)
lst
Out[484]: [1, 0, 0, 40, 39, 38, 37, 60, 59, 58, 0, 0, 16, 15, 14, 20, 19, 18]
``` |
8,143,471 | I realize that this question spans many technologies, but I am only looking for high-level contributions here.
I am currently tasked with exporting from a SQL Server proc into Excel, and then email the Excel file as attachment through SQL Agent. The SQL Agent job must be run daily.
What I have tried:
* SQL -> Excel using xp\_cmdshell & bcp. This is fine but then the excel output changes non-alpha text fields to numbers. (ie. phone numbers)
* SQL OpenRowset. I can't overcome the lack of the Jet 4.0 provider to use OpenRowset due to 64bit Win7 -- from what I understand.
* SSIS. After overcoming the dynamic file name predicament, I get stuck when my data types in from SQL to Excel didn't match up. (some Unicode to non Unicode issue)
* I can write the export process in .NET but then I do not know how to attach it to SQL Agent.
I guess my biggest question is, if you were going to address this yourself (as I am sure many of you must) which technology path should I take?
NOTE: I am almost certain I should not install Office on the Server
Thanks in advance. | 2011/11/15 | [
"https://Stackoverflow.com/questions/8143471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/844877/"
] | I'd definitely use SSIS. I'd have a Data Flow task reading the stored procedure output and writing to the Excel file, then a Send Mail task to handle the emailing of the resulting spreadsheet. (I've cleaned up Unicode vs. non-Unicode confusion in the past using Derived Column transformations in my Data Flows.)
SQL Agent could be used to kick off the SSIS package, although I haven't used it. | If you can write the export in .net, then in setting up the step for your job, one of the steps options is "Operating system (CmdExec)" which would allow you to point it to your .net application. |
8,143,471 | I realize that this question spans many technologies, but I am only looking for high-level contributions here.
I am currently tasked with exporting from a SQL Server proc into Excel, and then email the Excel file as attachment through SQL Agent. The SQL Agent job must be run daily.
What I have tried:
* SQL -> Excel using xp\_cmdshell & bcp. This is fine but then the excel output changes non-alpha text fields to numbers. (ie. phone numbers)
* SQL OpenRowset. I can't overcome the lack of the Jet 4.0 provider to use OpenRowset due to 64bit Win7 -- from what I understand.
* SSIS. After overcoming the dynamic file name predicament, I get stuck when my data types in from SQL to Excel didn't match up. (some Unicode to non Unicode issue)
* I can write the export process in .NET but then I do not know how to attach it to SQL Agent.
I guess my biggest question is, if you were going to address this yourself (as I am sure many of you must) which technology path should I take?
NOTE: I am almost certain I should not install Office on the Server
Thanks in advance. | 2011/11/15 | [
"https://Stackoverflow.com/questions/8143471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/844877/"
] | If you don't have SSIS on the server available to you, you can email attached CSV files using `sp_send_dbmail` with the right combination of parameters:
```
declare @tab char(1) = CHAR(9)
exec msdb.dbo.sp_send_dbmail @profile_name='dbProfile', @recipients='email@domain.com', @subject=@emailsubject, @attach_query_result_as_file=1,
@query = @sqlQuery, @query_attachment_filename='filename.csv',@query_result_separator=@tab,@query_result_no_padding=1
```
The full list of parameters and what they do is here: [sp\_send\_dbmail (Transact-SQL)](http://technet.microsoft.com/en-us/library/ms190307.aspx)
This SQL can then easily be added to a stored procedure and run as a Job. | If you can write the export in .net, then in setting up the step for your job, one of the steps options is "Operating system (CmdExec)" which would allow you to point it to your .net application. |
8,143,471 | I realize that this question spans many technologies, but I am only looking for high-level contributions here.
I am currently tasked with exporting from a SQL Server proc into Excel, and then email the Excel file as attachment through SQL Agent. The SQL Agent job must be run daily.
What I have tried:
* SQL -> Excel using xp\_cmdshell & bcp. This is fine but then the excel output changes non-alpha text fields to numbers. (ie. phone numbers)
* SQL OpenRowset. I can't overcome the lack of the Jet 4.0 provider to use OpenRowset due to 64bit Win7 -- from what I understand.
* SSIS. After overcoming the dynamic file name predicament, I get stuck when my data types in from SQL to Excel didn't match up. (some Unicode to non Unicode issue)
* I can write the export process in .NET but then I do not know how to attach it to SQL Agent.
I guess my biggest question is, if you were going to address this yourself (as I am sure many of you must) which technology path should I take?
NOTE: I am almost certain I should not install Office on the Server
Thanks in advance. | 2011/11/15 | [
"https://Stackoverflow.com/questions/8143471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/844877/"
] | I'd definitely use SSIS. I'd have a Data Flow task reading the stored procedure output and writing to the Excel file, then a Send Mail task to handle the emailing of the resulting spreadsheet. (I've cleaned up Unicode vs. non-Unicode confusion in the past using Derived Column transformations in my Data Flows.)
SQL Agent could be used to kick off the SSIS package, although I haven't used it. | If you don't have SSIS on the server available to you, you can email attached CSV files using `sp_send_dbmail` with the right combination of parameters:
```
declare @tab char(1) = CHAR(9)
exec msdb.dbo.sp_send_dbmail @profile_name='dbProfile', @recipients='email@domain.com', @subject=@emailsubject, @attach_query_result_as_file=1,
@query = @sqlQuery, @query_attachment_filename='filename.csv',@query_result_separator=@tab,@query_result_no_padding=1
```
The full list of parameters and what they do is here: [sp\_send\_dbmail (Transact-SQL)](http://technet.microsoft.com/en-us/library/ms190307.aspx)
This SQL can then easily be added to a stored procedure and run as a Job. |
31,183,332 | When you open an image in a text editor you get some characters which don't really makes sense (at least not to me). Is there a way to add comments to that text, so the file would not apear damaged when opened with an image viewer.
So, something like this:

Would turn into this:
 | 2015/07/02 | [
"https://Stackoverflow.com/questions/31183332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4153931/"
] | yes i find it, in file system/modification.xml
it was
```
<file path="system/{engine,library}/{action,loader,config,language}*.php">
```
now you can do it like this
```
<file path="system/engine/action.php,system/engine/loader.php,system/library/config.php,system/library/language.php">
``` | after i debug the code i found this
[error in modifications](https://drive.google.com/open?id=0B2-nzvg31rU7bUhRVlNKenRybDQ)
it seems there big hole there..
so you can use this to downgrade modifications to ver 2.0.1.1
[modification.ocmod.zip](https://drive.google.com/open?id=0B2-nzvg31rU7bU5zZWFaaEc4aGc)
this mod will remove all current mods, so you need upload them again
you may need to use this ocmod, if you have error in FTP
localcopy.ocmod.xml |
31,183,332 | When you open an image in a text editor you get some characters which don't really makes sense (at least not to me). Is there a way to add comments to that text, so the file would not apear damaged when opened with an image viewer.
So, something like this:

Would turn into this:
 | 2015/07/02 | [
"https://Stackoverflow.com/questions/31183332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4153931/"
] | Same for me in 2.2.0.0.
This will not work in 2.2.0.0 (although it would in 2.1.0.x):
`<file path="catalog/file-1.php,catalog/file-2.php,catalog/file-3.php">`
But this will work in 2.2.0.0:
`<file path="catalog/file-{1,2,3}.php">` | after i debug the code i found this
[error in modifications](https://drive.google.com/open?id=0B2-nzvg31rU7bUhRVlNKenRybDQ)
it seems there big hole there..
so you can use this to downgrade modifications to ver 2.0.1.1
[modification.ocmod.zip](https://drive.google.com/open?id=0B2-nzvg31rU7bU5zZWFaaEc4aGc)
this mod will remove all current mods, so you need upload them again
you may need to use this ocmod, if you have error in FTP
localcopy.ocmod.xml |
31,183,332 | When you open an image in a text editor you get some characters which don't really makes sense (at least not to me). Is there a way to add comments to that text, so the file would not apear damaged when opened with an image viewer.
So, something like this:

Would turn into this:
 | 2015/07/02 | [
"https://Stackoverflow.com/questions/31183332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4153931/"
] | Same for me in 2.2.0.0.
This will not work in 2.2.0.0 (although it would in 2.1.0.x):
`<file path="catalog/file-1.php,catalog/file-2.php,catalog/file-3.php">`
But this will work in 2.2.0.0:
`<file path="catalog/file-{1,2,3}.php">` | yes i find it, in file system/modification.xml
it was
```
<file path="system/{engine,library}/{action,loader,config,language}*.php">
```
now you can do it like this
```
<file path="system/engine/action.php,system/engine/loader.php,system/library/config.php,system/library/language.php">
``` |
38,066,209 | i want to show the image before inserting it to database after selecting an image from file, i want the image to show in the page. Can someone help me? im new to php and html and starting learn it. And if u know what will do can u explain it to me.
here is my php code.
```
<?php
session_start();
if(isset($_SESSION['username'])){
include_once('connection.php');
$username = ucfirst($_SESSION['username']);
if(isset($_POST['submit'])){
$title = $_POST['title'];
$date = $_POST['date'];
$content = $_POST['content'];
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"img/" . $_FILES["image"]["name"]);
$newsimage="img/" . $_FILES["image"]["name"];
if(empty($title)){
echo "Please enter a title";
}
else if(empty($date)){
echo "Please enter a date";
}
else if(empty($content)){
echo "Please enter content";
}
else{
$sql ="INSERT into news (news_title, news_date, news_content, news_image) VALUES ('$title', '$date', '$content', '$newsimage')";
mysqli_query($con, $sql);
echo "news entry posted";
}
}
}
else{
header('Location: login.php');
die();
}
if(isset($_POST['image'])){
}
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<h1>Welcome, <?php echo $_SESSION['username']; ?>!</h1>
<form method="post" action ="admin.php" enctype="multipart/form-data">
Title<input type ="text" name ="title" /><br>
Date<input type ="text" name="date" /><br>
Content<textarea name="content"></textarea>
<input type="submit" name="submit" value="Post News Entry" />
<input class="form-control" id="image" name="image" type="file" onchange='AlertFilesize();'/>
</form>
</body>
</html>
``` | 2016/06/28 | [
"https://Stackoverflow.com/questions/38066209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5438871/"
] | You can change the width and height of your imageview programmatically. Since vector drawables will preserve the original quality of the image, this will make the desired output happen.
```
ImageView iv = (ImageView) findViewById(R.id.imgview);
int width = 60;
int height = 60;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width,height);
iv.setLayoutParams(params);
``` | I'm currently facing the same problem.
I'm trying something like this, cause ViewParent has actually height set explicitly, so I use match\_parent and set margins. It doesn't work all the time though, cause I simply use this view in a viewholder for RecyclerView... Also I've noticed that sometimes I see scaled up version with artifacts, sometimes full size, sometimes there are margins, and bigger margins... But it still might work for you, if you use it in a simpler scenario.
```
mImageViewFront.setImageDrawable(vectorDrawable);
final int paddingLR = mImageViewFront.getWidth() / 4;
final int paddingTB = mImageViewFront.getHeight() / 4;
LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.setMargins(paddingLR, paddingTB, paddingLR, paddingTB);
mImageViewFront.setLayoutParams(params);
``` |
27,942,930 | We have a timestamp epoch column (BIGINT) stored in Hive.
We want to get Date 'yyyy-MM-dd' for this epoch.
Problem is my epoch is in milliseconds e.g. 1409535303522.
So select timestamp, from\_unixtime(timestamp,'yyyy-MM-dd') gives wrong results for date as it expects epoch in seconds.
So i tried dividing it by 1000. But then it gets converted to Double and we can not apply function to it. Even CAST is not working when I try to Convert this double to Bigint. | 2015/01/14 | [
"https://Stackoverflow.com/questions/27942930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3322308/"
] | Solved it by following query:
```
select timestamp, from_unixtime(CAST(timestamp/1000 as BIGINT), 'yyyy-MM-dd') from Hadoop_V1_Main_text_archieved limit 10;
``` | **timestamp\_ms** is unixtime in milliseconds
>
> SELECT from\_unixtime(floor(CAST(timestamp\_ms AS BIGINT)/1000), 'yyyy-MM-dd HH:mm:ss.SSS') as created\_timestamp FROM table\_name;
>
>
> |
27,942,930 | We have a timestamp epoch column (BIGINT) stored in Hive.
We want to get Date 'yyyy-MM-dd' for this epoch.
Problem is my epoch is in milliseconds e.g. 1409535303522.
So select timestamp, from\_unixtime(timestamp,'yyyy-MM-dd') gives wrong results for date as it expects epoch in seconds.
So i tried dividing it by 1000. But then it gets converted to Double and we can not apply function to it. Even CAST is not working when I try to Convert this double to Bigint. | 2015/01/14 | [
"https://Stackoverflow.com/questions/27942930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3322308/"
] | Solved it by following query:
```
select timestamp, from_unixtime(CAST(timestamp/1000 as BIGINT), 'yyyy-MM-dd') from Hadoop_V1_Main_text_archieved limit 10;
``` | In the original answer you'll get string, but if you'd like to get date you need to call extra cast with date:
```
select
timestamp,
cast(from_unixtime(CAST(timestamp/1000 as BIGINT), 'yyyy-MM-dd') as date) as date_col
from Hadoop_V1_Main_text_archieved
limit 10;
```
---
[Docs](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Types#LanguageManualTypes-date) for casting dates and timestamps. For converting string to date:
>
> `cast(string as date)`
>
> If the string is in the form 'YYYY-MM-DD', then a date value corresponding to that year/month/day is returned. If the string value does not match this formate, then NULL is returned.
>
>
>
Date type is available only from Hive > `0.12.0` as mentioned [here](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Types):
>
> `DATE` (Note: Only available starting with Hive 0.12.0)
>
>
> |
27,942,930 | We have a timestamp epoch column (BIGINT) stored in Hive.
We want to get Date 'yyyy-MM-dd' for this epoch.
Problem is my epoch is in milliseconds e.g. 1409535303522.
So select timestamp, from\_unixtime(timestamp,'yyyy-MM-dd') gives wrong results for date as it expects epoch in seconds.
So i tried dividing it by 1000. But then it gets converted to Double and we can not apply function to it. Even CAST is not working when I try to Convert this double to Bigint. | 2015/01/14 | [
"https://Stackoverflow.com/questions/27942930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3322308/"
] | Solved it by following query:
```
select timestamp, from_unixtime(CAST(timestamp/1000 as BIGINT), 'yyyy-MM-dd') from Hadoop_V1_Main_text_archieved limit 10;
``` | The type should be `double` to ensure precision is not lost:
```
select from_unixtime(cast(1601256179170 as double)/1000.0, "yyyy-MM-dd hh:mm:ss.SSS") as event_timestamp
``` |
46,429,251 | I've recently programmed a lot in javascript and I was trying to use some shorthands in PHP.
Consider this statement:
```
$value = 1;
return $value == 1 ?
'a' : $value == 2 ? 'b' : 'c';
```
Could anyone explain me why this returns `'a'` in jQuery and `'b'` in php? | 2017/09/26 | [
"https://Stackoverflow.com/questions/46429251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1272001/"
] | In PHP, the ternary operator is [left-associative](http://phpsadness.com/sad/30) (or from [the manual](http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary), a little less clear).
>
> this is because ternary expressions are evaluated from left to right
>
>
>
In Javascript, the ternary operator is [right-associative](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator).
>
> note: the conditional operator is right associative
>
>
>
So, in PHP your code executes like this:
```
($value == 1 ?
'a' : $value == 2) ? 'b' : 'c';
```
And in Javascript, it executes like this:
```
value == 1 ?
'a' : (value == 2 ? 'b' : 'c');
```
So, to get the same results, you need to tell either one to act like the other:
```
echo $value == 1 ?
'a' : ($value == 2 ? 'b' : 'c');
```
This is (one of the?) the reason why nested ternary operators are a bad idea. [They're not readable](http://twistedoakstudios.com/blog/Post5273_how-to-read-nested-ternary-operators) and prone to these kind of mistakes! | You need to wrap the "else" part of the condition in parantheses
```
$value = 1;
echo $value == 1 ? 'a' : ($value == 2 ? 'b' : 'c');
```
This would return 'a' in php |
46,429,251 | I've recently programmed a lot in javascript and I was trying to use some shorthands in PHP.
Consider this statement:
```
$value = 1;
return $value == 1 ?
'a' : $value == 2 ? 'b' : 'c';
```
Could anyone explain me why this returns `'a'` in jQuery and `'b'` in php? | 2017/09/26 | [
"https://Stackoverflow.com/questions/46429251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1272001/"
] | In PHP, the ternary operator is [left-associative](http://phpsadness.com/sad/30) (or from [the manual](http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary), a little less clear).
>
> this is because ternary expressions are evaluated from left to right
>
>
>
In Javascript, the ternary operator is [right-associative](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator).
>
> note: the conditional operator is right associative
>
>
>
So, in PHP your code executes like this:
```
($value == 1 ?
'a' : $value == 2) ? 'b' : 'c';
```
And in Javascript, it executes like this:
```
value == 1 ?
'a' : (value == 2 ? 'b' : 'c');
```
So, to get the same results, you need to tell either one to act like the other:
```
echo $value == 1 ?
'a' : ($value == 2 ? 'b' : 'c');
```
This is (one of the?) the reason why nested ternary operators are a bad idea. [They're not readable](http://twistedoakstudios.com/blog/Post5273_how-to-read-nested-ternary-operators) and prone to these kind of mistakes! | Use parenthesis do define the correct order of evaluation :
```
$value == 1 ? 'a' : ($value == 2 ? 'b' : 'c')
``` |
17,084,128 | How to create a new `dm_document` object using document from local system using DQL? I have tried the following but it's not working:
```
create dm_document object
SET title = 'TEST',
SET subject = 'TRIAL',
set object_name = 'Test123',
SETFILE 'c:\test.txt' with CONTENT_FORMAT= 'msww'
``` | 2013/06/13 | [
"https://Stackoverflow.com/questions/17084128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2481709/"
] | How do you run this DQL?
If you're doing it via Documentum Administrator, Documentum looks for the file with path 'C:\test.txt' on an application server machine wherer DA runs. So if you want to upload it into documentum you must place this file into appserver machine or use another tool for execution DQL.
And could you please show us an error, that you got | **Your DQL works for me** (!) but after clean any line-warp, so try this
```
create dm_document object SET title = 'TEST', SET subject = 'TRIAL', set object_name = 'Test123', SETFILE 'c:\test.txt' with CONTENT_FORMAT= 'msww'
```
...and be sure there is a such file on Content Server (not local) file system
good luck |
39,026,100 | Say I want to `touch` six files
```
one.html
one.css
two.html
two.css
three.html
three.css
```
How can I use `xargs` for this? I'm looking at the man page but I'm not sure on the syntax for getting the stdin pipe.
```
$ echo one two three | xargs -n 1 touch $1.html $1.css // nope
``` | 2016/08/18 | [
"https://Stackoverflow.com/questions/39026100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4769440/"
] | It is easier to do via shell ist:
```
touch {one,two,three}.{css,html}
```
This will create 6 files:
```
one.css one.html two.css two.html three.css three.html
``` | alternative with for loop
```
for f in one two three; do touch $f.html $f.css; done
``` |
39,026,100 | Say I want to `touch` six files
```
one.html
one.css
two.html
two.css
three.html
three.css
```
How can I use `xargs` for this? I'm looking at the man page but I'm not sure on the syntax for getting the stdin pipe.
```
$ echo one two three | xargs -n 1 touch $1.html $1.css // nope
``` | 2016/08/18 | [
"https://Stackoverflow.com/questions/39026100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4769440/"
] | If it is important to use `xargs`:
```
printf "%s\n" one two three | xargs -I{} touch {}.html {}.css
``` | alternative with for loop
```
for f in one two three; do touch $f.html $f.css; done
``` |
51,561,839 | I am implementing the CORS protocol within a server, following the [CORS standard](https://fetch.spec.whatwg.org/#cors-protocol "CORS standard"). My question is how the server should respond when it wishes to deny a *particular* Origin.
I understand how to respond to simple and preflight requests when the Origin is allowed. But how to respond for those Origins that the server does not want to allow? My initial guess is simply to not return any CORS headers, which would cause a preflight request to fail, as desired.
The standard briefly mentions this in section 3.2.3, but it sounds like it's describing a server that doesn't wish to participate in CORS *at all* (as opposed to a server that wants to participate in CORS and allow some Origins, but not others):
>
> In case a server does not wish to participate in the CORS protocol,
> its HTTP response to the CORS or CORS-preflight request must not
> include any of the above headers. The server is encouraged to use the
> 403 status in such HTTP responses.
>
>
>
Is this the correct way to respond to Origins that the server does not want to allow? It seems it could be misinterpreted by the client as "this server won't allow *any* cross origin requests" (when in reality, the problem is with this particular Origin, and the server would allow other Origins).
I am aware of [this question](https://stackoverflow.com/questions/14015118/what-is-the-expected-response-to-an-invalid-cors-request), but it's referring to an obsolete version of the spec, and the answer does not seem to be definitive. | 2018/07/27 | [
"https://Stackoverflow.com/questions/51561839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1538270/"
] | >
> Is [a 403 error status] the correct way to respond to Origins that the server does not want to allow? It seems it could be misinterpreted by the client as "this server won't allow any cross origin requests" (when in reality, the problem is with this particular Origin, and the server would allow other Origins).
>
>
>
There's nothing wrong with sending an error code that the requesting *script* could misinterpret. It's part of the design of CORS. To avoid confusing the browser, be sure to send the header `Vary: Origin` with the response. This tells the client's browser that if a script with a different origin tries to access the same resource, it should check again instead of looking up the cached CORS parameters. See [here](https://security.stackexchange.com/questions/151590/vary-origin-response-header-and-cors-exploitation) for some discussion. | CORS is disabled by default so if you do not want a given host to get the response, do not add them to the CORS Access-Control-Allow-Origin header returned by the server
>
> Access-Control-Allow-Origin: <https://www.example.com>
>
>
>
If a host makes a request to your server and they are not listed in this header, they will receive a error response on their preflight request.
A sample of an nginx config with CORS would look like this
```
server {
listen 80;
server_name api.example.com;
location / {
# Simple requests
if ($request_method ~* "(GET|POST)") {
add_header "Access-Control-Allow-Origin" "https://example.com";
}
# Preflighted requests
if ($request_method = OPTIONS) {
add_header "Access-Control-Allow-Origin" "https://example.com";
add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
return 200;
}
# Handle request
}
}
```
Also, an important note from the spec regarding errors on preflight requests:
>
> CORS failures result in errors, but for security reasons, specifics about what went wrong are not available to JavaScript code. All the code knows is that an error occurred. The only way to determine what specifically went wrong is to look at the browser's console for details.
>
>
>
<https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS> |
27,264 | How can I find a Chevalley basis of a type $B\_2$ when the related Lie algebra is defined as a linear Lie algebra of elements of the form $$x= \begin{pmatrix} 0 & b\_1 & b\_2 \\ c\_1 & m & n \\ c\_2 & p & q \end{pmatrix},$$ where $c\_1=-b\_2^t$, $c\_2=-b\_1^t$, $q=-m^t$, $n^t=-n$, $p^t=-p$?
When trying to find such a base, the constraints, especially $[x\_{\alpha}x\_{\beta}]=c\_{\alpha,\beta}x\_{\alpha+\beta}$ for $\alpha,\beta$ independent, and $\alpha+\beta$ being a root, turn out to be very hard to follow.
Thank you~ :) | 2011/03/15 | [
"https://math.stackexchange.com/questions/27264",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/4736/"
] | Try
>
> Assuming[Element[b,Reals],~rest of your code~]
>
>
>
**EDIT** then how about
>
> b /. Solve[expr == 0, b]
>
>
> N[b]
>
>
> Select[%,Element[#,Reals] & ]
>
>
>
I tried this using a regular polynomial with complex solutions and it worked in my case, should work in yours.
i.e, Create a list of solutions sols=Solve[expr==0,b]. Type sol// N to convert the fractional powers of 1 to "numerical" complex numbers Then use either Select or DeleteCases, which is a bit twisted and venture there only if Select didnt work. Or just numerically select sol[[n]] where n is the index of your real solution if you are willing to work the "shortcut" way. | Look at the FullForm to see what pattern you need to match.
In[1]:= FullForm[(-1)^(1/5)]
Out[1]//FullForm= Power[-1,Rational[1,5]]
Use DeleteCases to discard the unwanted solutions.
In[2]:= DeleteCases[{(-1)^(1/5)\*p/q\*4,(-1)^(1/5)\*Pi,-p/q\*5Pi},Power[-1,Rational[1,5]]\*\_]
Out[2]= {-(5 p Pi)/q)}
That will work as long as each of your solutions are a product of terms. If this doesn't work then post your actual solutions and I'll try to show how to craft a pattern to discard the unwanted solutions. |
27,264 | How can I find a Chevalley basis of a type $B\_2$ when the related Lie algebra is defined as a linear Lie algebra of elements of the form $$x= \begin{pmatrix} 0 & b\_1 & b\_2 \\ c\_1 & m & n \\ c\_2 & p & q \end{pmatrix},$$ where $c\_1=-b\_2^t$, $c\_2=-b\_1^t$, $q=-m^t$, $n^t=-n$, $p^t=-p$?
When trying to find such a base, the constraints, especially $[x\_{\alpha}x\_{\beta}]=c\_{\alpha,\beta}x\_{\alpha+\beta}$ for $\alpha,\beta$ independent, and $\alpha+\beta$ being a root, turn out to be very hard to follow.
Thank you~ :) | 2011/03/15 | [
"https://math.stackexchange.com/questions/27264",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/4736/"
] | Try
>
> Assuming[Element[b,Reals],~rest of your code~]
>
>
>
**EDIT** then how about
>
> b /. Solve[expr == 0, b]
>
>
> N[b]
>
>
> Select[%,Element[#,Reals] & ]
>
>
>
I tried this using a regular polynomial with complex solutions and it worked in my case, should work in yours.
i.e, Create a list of solutions sols=Solve[expr==0,b]. Type sol// N to convert the fractional powers of 1 to "numerical" complex numbers Then use either Select or DeleteCases, which is a bit twisted and venture there only if Select didnt work. Or just numerically select sol[[n]] where n is the index of your real solution if you are willing to work the "shortcut" way. | Method 1
```
roots = x /. Solve[x^5 == 1, x]
result1 = Select[roots, Im@# == 0 &]
```
Method 2
```
result2 = Solve[x^5 == 1, x, Reals]
```
Method 3
```
result3 = Reduce[x^5==1&&Element[x,Reals]]
```
Note that `result1` is a list of numbers, `result2` is list of lists of rules and `result3` is an expression |
27,264 | How can I find a Chevalley basis of a type $B\_2$ when the related Lie algebra is defined as a linear Lie algebra of elements of the form $$x= \begin{pmatrix} 0 & b\_1 & b\_2 \\ c\_1 & m & n \\ c\_2 & p & q \end{pmatrix},$$ where $c\_1=-b\_2^t$, $c\_2=-b\_1^t$, $q=-m^t$, $n^t=-n$, $p^t=-p$?
When trying to find such a base, the constraints, especially $[x\_{\alpha}x\_{\beta}]=c\_{\alpha,\beta}x\_{\alpha+\beta}$ for $\alpha,\beta$ independent, and $\alpha+\beta$ being a root, turn out to be very hard to follow.
Thank you~ :) | 2011/03/15 | [
"https://math.stackexchange.com/questions/27264",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/4736/"
] | Method 1
```
roots = x /. Solve[x^5 == 1, x]
result1 = Select[roots, Im@# == 0 &]
```
Method 2
```
result2 = Solve[x^5 == 1, x, Reals]
```
Method 3
```
result3 = Reduce[x^5==1&&Element[x,Reals]]
```
Note that `result1` is a list of numbers, `result2` is list of lists of rules and `result3` is an expression | Look at the FullForm to see what pattern you need to match.
In[1]:= FullForm[(-1)^(1/5)]
Out[1]//FullForm= Power[-1,Rational[1,5]]
Use DeleteCases to discard the unwanted solutions.
In[2]:= DeleteCases[{(-1)^(1/5)\*p/q\*4,(-1)^(1/5)\*Pi,-p/q\*5Pi},Power[-1,Rational[1,5]]\*\_]
Out[2]= {-(5 p Pi)/q)}
That will work as long as each of your solutions are a product of terms. If this doesn't work then post your actual solutions and I'll try to show how to craft a pattern to discard the unwanted solutions. |
368,512 | [This answer](https://stackoverflow.com/a/50485404/3094533) was accepted as correct.
It contains only a line of code (that actually does what the OP is asking) without any explanation whatsoever. Another user commented with a link to a Wikipedia explaining the math behind it, and I've left a comment asking the author of the answer to include some explanation. The answer was not edited, so now I'm wondering what should I do about it.
I mean, one one hand, it does solve the problem, so I don't think I should downvote it or flag it as low quality, but on the other hand, it just throws a line of code, that unless you know the mathematic formula in advance, is anything but self explanatory, so I don't think I should upvote it either.
I could just ignore it, knowing I did my part, but something bugs me about this answer.
I think what bugs me the most about it is that I would like to upvote it, but as it is now I don't think it deserves an upvote.
So after I've already asked nicely for an explanation, what else can I do about it? Should I do anything else? | 2018/05/24 | [
"https://meta.stackoverflow.com/questions/368512",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/3094533/"
] | >
> So after I've already asked nicely for an explanation, what else can I do about it? Should I do anything else?
>
>
>
You could always add an answer with an explanation if you are knowledgeable on the subject. Just because the answer is accepted by OP does not mean it is a good/helpful for others. Neither does it mean more posts cannot be added. It means it worked for the asker and nothing more.
Over time the community will decide on the better answer by voting on the posts.
I wouldn't suggest editing the post yourself since you would be changing it more than what the author intended. | If the explanation is straightforward and obvious, and you are confident in your ability to write it in a clear way, editing it into the answer can be a reasonable thing to do -- if that is the case, you can be reasonably sure you won't end up accidentally changing the meaning of the answer.
A few things to keep in mind:
* Adding an explanation is more likely to work well if the answer is simple. In your case, it being a one-liner based on a small nugget of math means the odds of success are good. It would be a riskier move for an answer consisting of a larger code snippet.
* Make your explanation as succinct and to-the-point as possible. This decreases the risk of putting words in the author's mouth. (If you do have a substantial amount of additional things to say that go beyond the minimum necessary to explain the solution, it is better to post your own answer. You can mention the other answer in passing and link to it in order to give it credit for the idea.)
* Leave a comment to the answer explaining what you have done -- it is both courteous and transparent to do so. Here is one way of phrasing it, adapted from past comments of mine:
>
> I took the liberty of adding a brief explanatory remark. Feel free to edit it as much as you find appropriate.
>
>
>
In the specific case of your answer, the Wikipedia article linked to in a comment helpfully provides detailed commentary on what is behind the solution. Since it isn't necessary to cover the math in depth in the answer, a minimal explanation can be as straightforward as this:
>
> The result you are looking for is known as the [digital root](https://en.wikipedia.org/wiki/Digital_root) of an integer. It can be calculated as follows: [...]
>
>
> |
63,324,647 | I am plotting countries on map using plotly and r shiny. I would like subset of data containing rows about the country to appear in the form of data table on clicking on country on a map. But I am unable to implement it. I get the table but there is not data displayed in the table. Any help would be appreciated!
```
Mapbox_Token= 'Mapbox token'
library(plotly)
library("readxl")
library(dplyr)
library(readxl)
library(writexl)
library(shiny)
library(htmlwidgets)
data_1<- read.csv(".file.csv")
print(data_1)
library(formattable)
Sys.setenv("MAPBOX_TOKEN" = Mapbox_Token) # for Orca
ui <- fluidPage(
plotlyOutput(outputId = "Plot"),
DT::dataTableOutput('click')
)
server <- function(input, output,session) {
output$Plot <- renderPlotly({
df=read.csv("file2.csv")
render_value(data_1)
fig <- df%>% plot_mapbox(lat = ~lat, lon = ~lng,split = ~Country,
size=0, type= 'scattermapbox',mode='markers',hoverinfo="none",showlegend=F,source='subset'
)
fig <- fig %>% layout(title = 'No Of Companies',font=
list(color='white'),plot_bgcolor = '#191A1A', paper_bgcolor =
'#191A1A',mapbox = list(style = 'dark'),legend = list(orientation ='v',font = list(size = 6)),margin = list(l = 25, r = 25,b = 75, t = 25,pad =
2))
fig<-fig %>% add_annotations(text ='Map shows number of
companies by country. The size of the circles correspond to
the number of
companies.',x=0.5,y=-0.2,showarrow=FALSE,font=list(color='red'))
fig<- fig %>% add_markers(text = ~paste(paste('Country:',Country),
paste("Number of Companies:",Name ), paste("Dataset:", Url),sep = "
<br />"), size=~Name, hoverinfo = "text",marker=list(sizeref=0.1,
sizemode="area"),showlegend=T)%>%
onRender(fig, "function(el) {el.on('plotly_click', function(d) {var
url = d.points[0].customdata;window.open(url);});}")
fig <- fig %>% config(mapboxAccessToken = Sys.getenv("MAPBOX_TOKEN"))
})
render_value=function(df){
output$click <- renderDataTable({
s <- event_data("plotly_click",source = "subset")
print(s$y)
return(DT::datatable(data_1[data_1$Country==s$y,]))
})
}
}
shinyApp(ui,server)
``` | 2020/08/09 | [
"https://Stackoverflow.com/questions/63324647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13017372/"
] | Try running the command `flutter pub get -v`.
It shows the log and can even solve the problem. | When all other command don't working (in my case is my antivirus block `flutter` command), I launch in my project folder:
>
> /flutter/bin/cache/dart-sdk/bin/dart
> \_\_deprecated\_pub --verbose get --no-precompile
>
>
>
the command stop on rename folder error.
I rename with `cp` command the folder and after the command `flutter pub get` working fine. |
63,324,647 | I am plotting countries on map using plotly and r shiny. I would like subset of data containing rows about the country to appear in the form of data table on clicking on country on a map. But I am unable to implement it. I get the table but there is not data displayed in the table. Any help would be appreciated!
```
Mapbox_Token= 'Mapbox token'
library(plotly)
library("readxl")
library(dplyr)
library(readxl)
library(writexl)
library(shiny)
library(htmlwidgets)
data_1<- read.csv(".file.csv")
print(data_1)
library(formattable)
Sys.setenv("MAPBOX_TOKEN" = Mapbox_Token) # for Orca
ui <- fluidPage(
plotlyOutput(outputId = "Plot"),
DT::dataTableOutput('click')
)
server <- function(input, output,session) {
output$Plot <- renderPlotly({
df=read.csv("file2.csv")
render_value(data_1)
fig <- df%>% plot_mapbox(lat = ~lat, lon = ~lng,split = ~Country,
size=0, type= 'scattermapbox',mode='markers',hoverinfo="none",showlegend=F,source='subset'
)
fig <- fig %>% layout(title = 'No Of Companies',font=
list(color='white'),plot_bgcolor = '#191A1A', paper_bgcolor =
'#191A1A',mapbox = list(style = 'dark'),legend = list(orientation ='v',font = list(size = 6)),margin = list(l = 25, r = 25,b = 75, t = 25,pad =
2))
fig<-fig %>% add_annotations(text ='Map shows number of
companies by country. The size of the circles correspond to
the number of
companies.',x=0.5,y=-0.2,showarrow=FALSE,font=list(color='red'))
fig<- fig %>% add_markers(text = ~paste(paste('Country:',Country),
paste("Number of Companies:",Name ), paste("Dataset:", Url),sep = "
<br />"), size=~Name, hoverinfo = "text",marker=list(sizeref=0.1,
sizemode="area"),showlegend=T)%>%
onRender(fig, "function(el) {el.on('plotly_click', function(d) {var
url = d.points[0].customdata;window.open(url);});}")
fig <- fig %>% config(mapboxAccessToken = Sys.getenv("MAPBOX_TOKEN"))
})
render_value=function(df){
output$click <- renderDataTable({
s <- event_data("plotly_click",source = "subset")
print(s$y)
return(DT::datatable(data_1[data_1$Country==s$y,]))
})
}
}
shinyApp(ui,server)
``` | 2020/08/09 | [
"https://Stackoverflow.com/questions/63324647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13017372/"
] | Try to disable your antivirus for like 5 minutes and then go to the flutter directory
**C:\src\flutter**
and run the command
>
> *flutter pub global activate devtools*
>
>
>
**Note:** The flutter path should be set in env variables before running this. | When all other command don't working (in my case is my antivirus block `flutter` command), I launch in my project folder:
>
> /flutter/bin/cache/dart-sdk/bin/dart
> \_\_deprecated\_pub --verbose get --no-precompile
>
>
>
the command stop on rename folder error.
I rename with `cp` command the folder and after the command `flutter pub get` working fine. |
63,324,647 | I am plotting countries on map using plotly and r shiny. I would like subset of data containing rows about the country to appear in the form of data table on clicking on country on a map. But I am unable to implement it. I get the table but there is not data displayed in the table. Any help would be appreciated!
```
Mapbox_Token= 'Mapbox token'
library(plotly)
library("readxl")
library(dplyr)
library(readxl)
library(writexl)
library(shiny)
library(htmlwidgets)
data_1<- read.csv(".file.csv")
print(data_1)
library(formattable)
Sys.setenv("MAPBOX_TOKEN" = Mapbox_Token) # for Orca
ui <- fluidPage(
plotlyOutput(outputId = "Plot"),
DT::dataTableOutput('click')
)
server <- function(input, output,session) {
output$Plot <- renderPlotly({
df=read.csv("file2.csv")
render_value(data_1)
fig <- df%>% plot_mapbox(lat = ~lat, lon = ~lng,split = ~Country,
size=0, type= 'scattermapbox',mode='markers',hoverinfo="none",showlegend=F,source='subset'
)
fig <- fig %>% layout(title = 'No Of Companies',font=
list(color='white'),plot_bgcolor = '#191A1A', paper_bgcolor =
'#191A1A',mapbox = list(style = 'dark'),legend = list(orientation ='v',font = list(size = 6)),margin = list(l = 25, r = 25,b = 75, t = 25,pad =
2))
fig<-fig %>% add_annotations(text ='Map shows number of
companies by country. The size of the circles correspond to
the number of
companies.',x=0.5,y=-0.2,showarrow=FALSE,font=list(color='red'))
fig<- fig %>% add_markers(text = ~paste(paste('Country:',Country),
paste("Number of Companies:",Name ), paste("Dataset:", Url),sep = "
<br />"), size=~Name, hoverinfo = "text",marker=list(sizeref=0.1,
sizemode="area"),showlegend=T)%>%
onRender(fig, "function(el) {el.on('plotly_click', function(d) {var
url = d.points[0].customdata;window.open(url);});}")
fig <- fig %>% config(mapboxAccessToken = Sys.getenv("MAPBOX_TOKEN"))
})
render_value=function(df){
output$click <- renderDataTable({
s <- event_data("plotly_click",source = "subset")
print(s$y)
return(DT::datatable(data_1[data_1$Country==s$y,]))
})
}
}
shinyApp(ui,server)
``` | 2020/08/09 | [
"https://Stackoverflow.com/questions/63324647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13017372/"
] | Try running the command `flutter pub get -v`.
It shows the log and can even solve the problem. | run flutter pub get -v
this will show you what folder it is trying to rename to what. Manually rename the folder and place it in the path it was trying to place. re-run flutter pub get -v, repeat until it says exit with 0. |
63,324,647 | I am plotting countries on map using plotly and r shiny. I would like subset of data containing rows about the country to appear in the form of data table on clicking on country on a map. But I am unable to implement it. I get the table but there is not data displayed in the table. Any help would be appreciated!
```
Mapbox_Token= 'Mapbox token'
library(plotly)
library("readxl")
library(dplyr)
library(readxl)
library(writexl)
library(shiny)
library(htmlwidgets)
data_1<- read.csv(".file.csv")
print(data_1)
library(formattable)
Sys.setenv("MAPBOX_TOKEN" = Mapbox_Token) # for Orca
ui <- fluidPage(
plotlyOutput(outputId = "Plot"),
DT::dataTableOutput('click')
)
server <- function(input, output,session) {
output$Plot <- renderPlotly({
df=read.csv("file2.csv")
render_value(data_1)
fig <- df%>% plot_mapbox(lat = ~lat, lon = ~lng,split = ~Country,
size=0, type= 'scattermapbox',mode='markers',hoverinfo="none",showlegend=F,source='subset'
)
fig <- fig %>% layout(title = 'No Of Companies',font=
list(color='white'),plot_bgcolor = '#191A1A', paper_bgcolor =
'#191A1A',mapbox = list(style = 'dark'),legend = list(orientation ='v',font = list(size = 6)),margin = list(l = 25, r = 25,b = 75, t = 25,pad =
2))
fig<-fig %>% add_annotations(text ='Map shows number of
companies by country. The size of the circles correspond to
the number of
companies.',x=0.5,y=-0.2,showarrow=FALSE,font=list(color='red'))
fig<- fig %>% add_markers(text = ~paste(paste('Country:',Country),
paste("Number of Companies:",Name ), paste("Dataset:", Url),sep = "
<br />"), size=~Name, hoverinfo = "text",marker=list(sizeref=0.1,
sizemode="area"),showlegend=T)%>%
onRender(fig, "function(el) {el.on('plotly_click', function(d) {var
url = d.points[0].customdata;window.open(url);});}")
fig <- fig %>% config(mapboxAccessToken = Sys.getenv("MAPBOX_TOKEN"))
})
render_value=function(df){
output$click <- renderDataTable({
s <- event_data("plotly_click",source = "subset")
print(s$y)
return(DT::datatable(data_1[data_1$Country==s$y,]))
})
}
}
shinyApp(ui,server)
``` | 2020/08/09 | [
"https://Stackoverflow.com/questions/63324647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13017372/"
] | Try running the command `flutter pub get -v`.
It shows the log and can even solve the problem. | Do "pub cache repair"
and try "pub get" |
63,324,647 | I am plotting countries on map using plotly and r shiny. I would like subset of data containing rows about the country to appear in the form of data table on clicking on country on a map. But I am unable to implement it. I get the table but there is not data displayed in the table. Any help would be appreciated!
```
Mapbox_Token= 'Mapbox token'
library(plotly)
library("readxl")
library(dplyr)
library(readxl)
library(writexl)
library(shiny)
library(htmlwidgets)
data_1<- read.csv(".file.csv")
print(data_1)
library(formattable)
Sys.setenv("MAPBOX_TOKEN" = Mapbox_Token) # for Orca
ui <- fluidPage(
plotlyOutput(outputId = "Plot"),
DT::dataTableOutput('click')
)
server <- function(input, output,session) {
output$Plot <- renderPlotly({
df=read.csv("file2.csv")
render_value(data_1)
fig <- df%>% plot_mapbox(lat = ~lat, lon = ~lng,split = ~Country,
size=0, type= 'scattermapbox',mode='markers',hoverinfo="none",showlegend=F,source='subset'
)
fig <- fig %>% layout(title = 'No Of Companies',font=
list(color='white'),plot_bgcolor = '#191A1A', paper_bgcolor =
'#191A1A',mapbox = list(style = 'dark'),legend = list(orientation ='v',font = list(size = 6)),margin = list(l = 25, r = 25,b = 75, t = 25,pad =
2))
fig<-fig %>% add_annotations(text ='Map shows number of
companies by country. The size of the circles correspond to
the number of
companies.',x=0.5,y=-0.2,showarrow=FALSE,font=list(color='red'))
fig<- fig %>% add_markers(text = ~paste(paste('Country:',Country),
paste("Number of Companies:",Name ), paste("Dataset:", Url),sep = "
<br />"), size=~Name, hoverinfo = "text",marker=list(sizeref=0.1,
sizemode="area"),showlegend=T)%>%
onRender(fig, "function(el) {el.on('plotly_click', function(d) {var
url = d.points[0].customdata;window.open(url);});}")
fig <- fig %>% config(mapboxAccessToken = Sys.getenv("MAPBOX_TOKEN"))
})
render_value=function(df){
output$click <- renderDataTable({
s <- event_data("plotly_click",source = "subset")
print(s$y)
return(DT::datatable(data_1[data_1$Country==s$y,]))
})
}
}
shinyApp(ui,server)
``` | 2020/08/09 | [
"https://Stackoverflow.com/questions/63324647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13017372/"
] | Try running the command `flutter pub get -v`.
It shows the log and can even solve the problem. | Try to disable your antivirus for like 5 minutes and then go to the flutter directory
**C:\src\flutter**
and run the command
>
> *flutter pub global activate devtools*
>
>
>
**Note:** The flutter path should be set in env variables before running this. |
63,324,647 | I am plotting countries on map using plotly and r shiny. I would like subset of data containing rows about the country to appear in the form of data table on clicking on country on a map. But I am unable to implement it. I get the table but there is not data displayed in the table. Any help would be appreciated!
```
Mapbox_Token= 'Mapbox token'
library(plotly)
library("readxl")
library(dplyr)
library(readxl)
library(writexl)
library(shiny)
library(htmlwidgets)
data_1<- read.csv(".file.csv")
print(data_1)
library(formattable)
Sys.setenv("MAPBOX_TOKEN" = Mapbox_Token) # for Orca
ui <- fluidPage(
plotlyOutput(outputId = "Plot"),
DT::dataTableOutput('click')
)
server <- function(input, output,session) {
output$Plot <- renderPlotly({
df=read.csv("file2.csv")
render_value(data_1)
fig <- df%>% plot_mapbox(lat = ~lat, lon = ~lng,split = ~Country,
size=0, type= 'scattermapbox',mode='markers',hoverinfo="none",showlegend=F,source='subset'
)
fig <- fig %>% layout(title = 'No Of Companies',font=
list(color='white'),plot_bgcolor = '#191A1A', paper_bgcolor =
'#191A1A',mapbox = list(style = 'dark'),legend = list(orientation ='v',font = list(size = 6)),margin = list(l = 25, r = 25,b = 75, t = 25,pad =
2))
fig<-fig %>% add_annotations(text ='Map shows number of
companies by country. The size of the circles correspond to
the number of
companies.',x=0.5,y=-0.2,showarrow=FALSE,font=list(color='red'))
fig<- fig %>% add_markers(text = ~paste(paste('Country:',Country),
paste("Number of Companies:",Name ), paste("Dataset:", Url),sep = "
<br />"), size=~Name, hoverinfo = "text",marker=list(sizeref=0.1,
sizemode="area"),showlegend=T)%>%
onRender(fig, "function(el) {el.on('plotly_click', function(d) {var
url = d.points[0].customdata;window.open(url);});}")
fig <- fig %>% config(mapboxAccessToken = Sys.getenv("MAPBOX_TOKEN"))
})
render_value=function(df){
output$click <- renderDataTable({
s <- event_data("plotly_click",source = "subset")
print(s$y)
return(DT::datatable(data_1[data_1$Country==s$y,]))
})
}
}
shinyApp(ui,server)
``` | 2020/08/09 | [
"https://Stackoverflow.com/questions/63324647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13017372/"
] | Run the following command:
```
flutter pub global activate devtools
```
Then try to get the packages again.
I hope this helps fix the issue | run flutter pub get -v
this will show you what folder it is trying to rename to what. Manually rename the folder and place it in the path it was trying to place. re-run flutter pub get -v, repeat until it says exit with 0. |
63,324,647 | I am plotting countries on map using plotly and r shiny. I would like subset of data containing rows about the country to appear in the form of data table on clicking on country on a map. But I am unable to implement it. I get the table but there is not data displayed in the table. Any help would be appreciated!
```
Mapbox_Token= 'Mapbox token'
library(plotly)
library("readxl")
library(dplyr)
library(readxl)
library(writexl)
library(shiny)
library(htmlwidgets)
data_1<- read.csv(".file.csv")
print(data_1)
library(formattable)
Sys.setenv("MAPBOX_TOKEN" = Mapbox_Token) # for Orca
ui <- fluidPage(
plotlyOutput(outputId = "Plot"),
DT::dataTableOutput('click')
)
server <- function(input, output,session) {
output$Plot <- renderPlotly({
df=read.csv("file2.csv")
render_value(data_1)
fig <- df%>% plot_mapbox(lat = ~lat, lon = ~lng,split = ~Country,
size=0, type= 'scattermapbox',mode='markers',hoverinfo="none",showlegend=F,source='subset'
)
fig <- fig %>% layout(title = 'No Of Companies',font=
list(color='white'),plot_bgcolor = '#191A1A', paper_bgcolor =
'#191A1A',mapbox = list(style = 'dark'),legend = list(orientation ='v',font = list(size = 6)),margin = list(l = 25, r = 25,b = 75, t = 25,pad =
2))
fig<-fig %>% add_annotations(text ='Map shows number of
companies by country. The size of the circles correspond to
the number of
companies.',x=0.5,y=-0.2,showarrow=FALSE,font=list(color='red'))
fig<- fig %>% add_markers(text = ~paste(paste('Country:',Country),
paste("Number of Companies:",Name ), paste("Dataset:", Url),sep = "
<br />"), size=~Name, hoverinfo = "text",marker=list(sizeref=0.1,
sizemode="area"),showlegend=T)%>%
onRender(fig, "function(el) {el.on('plotly_click', function(d) {var
url = d.points[0].customdata;window.open(url);});}")
fig <- fig %>% config(mapboxAccessToken = Sys.getenv("MAPBOX_TOKEN"))
})
render_value=function(df){
output$click <- renderDataTable({
s <- event_data("plotly_click",source = "subset")
print(s$y)
return(DT::datatable(data_1[data_1$Country==s$y,]))
})
}
}
shinyApp(ui,server)
``` | 2020/08/09 | [
"https://Stackoverflow.com/questions/63324647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13017372/"
] | Try to disable your antivirus for like 5 minutes and then go to the flutter directory
**C:\src\flutter**
and run the command
>
> *flutter pub global activate devtools*
>
>
>
**Note:** The flutter path should be set in env variables before running this. | run flutter pub get -v
this will show you what folder it is trying to rename to what. Manually rename the folder and place it in the path it was trying to place. re-run flutter pub get -v, repeat until it says exit with 0. |
63,324,647 | I am plotting countries on map using plotly and r shiny. I would like subset of data containing rows about the country to appear in the form of data table on clicking on country on a map. But I am unable to implement it. I get the table but there is not data displayed in the table. Any help would be appreciated!
```
Mapbox_Token= 'Mapbox token'
library(plotly)
library("readxl")
library(dplyr)
library(readxl)
library(writexl)
library(shiny)
library(htmlwidgets)
data_1<- read.csv(".file.csv")
print(data_1)
library(formattable)
Sys.setenv("MAPBOX_TOKEN" = Mapbox_Token) # for Orca
ui <- fluidPage(
plotlyOutput(outputId = "Plot"),
DT::dataTableOutput('click')
)
server <- function(input, output,session) {
output$Plot <- renderPlotly({
df=read.csv("file2.csv")
render_value(data_1)
fig <- df%>% plot_mapbox(lat = ~lat, lon = ~lng,split = ~Country,
size=0, type= 'scattermapbox',mode='markers',hoverinfo="none",showlegend=F,source='subset'
)
fig <- fig %>% layout(title = 'No Of Companies',font=
list(color='white'),plot_bgcolor = '#191A1A', paper_bgcolor =
'#191A1A',mapbox = list(style = 'dark'),legend = list(orientation ='v',font = list(size = 6)),margin = list(l = 25, r = 25,b = 75, t = 25,pad =
2))
fig<-fig %>% add_annotations(text ='Map shows number of
companies by country. The size of the circles correspond to
the number of
companies.',x=0.5,y=-0.2,showarrow=FALSE,font=list(color='red'))
fig<- fig %>% add_markers(text = ~paste(paste('Country:',Country),
paste("Number of Companies:",Name ), paste("Dataset:", Url),sep = "
<br />"), size=~Name, hoverinfo = "text",marker=list(sizeref=0.1,
sizemode="area"),showlegend=T)%>%
onRender(fig, "function(el) {el.on('plotly_click', function(d) {var
url = d.points[0].customdata;window.open(url);});}")
fig <- fig %>% config(mapboxAccessToken = Sys.getenv("MAPBOX_TOKEN"))
})
render_value=function(df){
output$click <- renderDataTable({
s <- event_data("plotly_click",source = "subset")
print(s$y)
return(DT::datatable(data_1[data_1$Country==s$y,]))
})
}
}
shinyApp(ui,server)
``` | 2020/08/09 | [
"https://Stackoverflow.com/questions/63324647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13017372/"
] | I had the same issue. None of the answers worked. I deleted .dart\_tool folder in the project folder and it worked :) | Do "pub cache repair"
and try "pub get" |
63,324,647 | I am plotting countries on map using plotly and r shiny. I would like subset of data containing rows about the country to appear in the form of data table on clicking on country on a map. But I am unable to implement it. I get the table but there is not data displayed in the table. Any help would be appreciated!
```
Mapbox_Token= 'Mapbox token'
library(plotly)
library("readxl")
library(dplyr)
library(readxl)
library(writexl)
library(shiny)
library(htmlwidgets)
data_1<- read.csv(".file.csv")
print(data_1)
library(formattable)
Sys.setenv("MAPBOX_TOKEN" = Mapbox_Token) # for Orca
ui <- fluidPage(
plotlyOutput(outputId = "Plot"),
DT::dataTableOutput('click')
)
server <- function(input, output,session) {
output$Plot <- renderPlotly({
df=read.csv("file2.csv")
render_value(data_1)
fig <- df%>% plot_mapbox(lat = ~lat, lon = ~lng,split = ~Country,
size=0, type= 'scattermapbox',mode='markers',hoverinfo="none",showlegend=F,source='subset'
)
fig <- fig %>% layout(title = 'No Of Companies',font=
list(color='white'),plot_bgcolor = '#191A1A', paper_bgcolor =
'#191A1A',mapbox = list(style = 'dark'),legend = list(orientation ='v',font = list(size = 6)),margin = list(l = 25, r = 25,b = 75, t = 25,pad =
2))
fig<-fig %>% add_annotations(text ='Map shows number of
companies by country. The size of the circles correspond to
the number of
companies.',x=0.5,y=-0.2,showarrow=FALSE,font=list(color='red'))
fig<- fig %>% add_markers(text = ~paste(paste('Country:',Country),
paste("Number of Companies:",Name ), paste("Dataset:", Url),sep = "
<br />"), size=~Name, hoverinfo = "text",marker=list(sizeref=0.1,
sizemode="area"),showlegend=T)%>%
onRender(fig, "function(el) {el.on('plotly_click', function(d) {var
url = d.points[0].customdata;window.open(url);});}")
fig <- fig %>% config(mapboxAccessToken = Sys.getenv("MAPBOX_TOKEN"))
})
render_value=function(df){
output$click <- renderDataTable({
s <- event_data("plotly_click",source = "subset")
print(s$y)
return(DT::datatable(data_1[data_1$Country==s$y,]))
})
}
}
shinyApp(ui,server)
``` | 2020/08/09 | [
"https://Stackoverflow.com/questions/63324647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13017372/"
] | Try to disable your antivirus for like 5 minutes and then go to the flutter directory
**C:\src\flutter**
and run the command
>
> *flutter pub global activate devtools*
>
>
>
**Note:** The flutter path should be set in env variables before running this. | This is how I proceeded to resolve that problem:
First I had to run the command bellow to see in details what he is trying to rename:
```
flutter pub get -v
```
After that in the console I searched for the term "**renaming**" and I found this:
[](https://i.stack.imgur.com/XvNlu.png)
So I had to go to the path specified in the console where flutter was installed, and I found this:
[](https://i.stack.imgur.com/2m9G9.png)
Then I deleted all the folders, and tried to run the command **flutter pub get** again. it didn't work, so I restored the deleted folders, and I tried again for the second time. And magically the command worked successfully. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.