qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
45,401,378
so im making the board game GO for javascript and im having trouble counting the territories. If you didnt know, GO is like a complex checkers where you place stones horizontally and vertically instead of diagonally. A territory comes when the game has ended and you have made a border of your stones (the board edges count as anyones). [![territory](https://i.stack.imgur.com/nIizS.png)](https://i.stack.imgur.com/nIizS.png) So the image above is what i have so far. White = player 1, Black = player 2, Green = territory So the green only comes at the end of the game. The game has now finished, black has control of the top left corner of the board taking 2 prisoners. The group inside has been identified and coloured in green. Problem is, how do i know what player the green territory belongs to? Any human can see black owns all sides/ border of the territory (remember the board edges are anyones). It starts to get hard when there are prisoners inside. I could just check every cell adjacent to every green cell. If there is black and white, its not a territory but that wouldnt work if there is prisoners. One way im thinking might be an option is to try identify the border going around it. If i can do that i can easily check whos territory it is. Calculating the border peices would be easy with a square but a circle or any morphed shape? im not sure. Any help is appriciated :)
2017/07/30
[ "https://Stackoverflow.com/questions/45401378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6799727/" ]
I managed to do this very effectively in the end using my own algorithm. It will first identify the territory in question and get the lowX, lowY, highX, highY. So in this case it would be 0, 0, 5, 5 respectivly. I then do a for loop like this: ``` for (var j = lowX; j < highX + 1; j++) { var lowColumnY = null; var highColumnY = null; for (var k = 0; k < territories[i].length; k++) { if (territories[i][k].x == j) { if ((lowColumnY == null) || (territories[i][k].y < lowColumnY)) { lowColumnY = territories[i][k].y; console.log(lowColumnY); } if ((territories[i][k].y > highColumnY) || (highColumnY == null)) { highColumnY = territories[i][k].y; } } } ``` So that scrolls through all the columns of the territory and works out the low and high point which are the first 2 variables declared. I then repeat the for loop for the Y and in the end im left with every coordinate of the border. I have demonstrated this by drawing red circles so its easy to visualist and as you can see it doesnt interfere with any prisoners. [![territory](https://i.stack.imgur.com/jJsIU.png)](https://i.stack.imgur.com/jJsIU.png) So lastly i just check each colour of the stones where the red circles are. If there is any conflicting colours, it cant be a territory. As in this case the only colour was black, we know its a black territory.
Im going to post an idea myself and try this method. So i will first get the most left column in the territory, in this case its index 0. i will use a for loop to scroll through every column finding out the most up and the most down stone in the column. So first is column 0. the most up stone is 0 and the most down is 5. (ignore the board markings). As that must be the top and bottom border for this shape I will check the stones above the top one and below the bottom one and note them down. As the top of stone 0,0 is the edge of the board, its marked "both". Now for the bottom, below it will be marked "black". We now have an owner of this territory. I will repeat this for all the columns and then all the rows and if it gets any conflicting owner, i will break the loop as it cant be a territory. I just thought of this in my head and im going to try it now
17,149,200
I have graph class that looks like: ``` class Graph { public: typedef unsigned int size_type; typedef std::list<size_type> Neighbours; protected: size_type m_nodes_count, m_edges_count; public: Graph(size_type nodes_count = 0) : m_nodes_count(nodes_count), m_edges_count(0) {} virtual bool is_edge(size_type from, size_type to) = 0; virtual Neighbours neighbours(size_type node) = 0; virtual Graph& add_edge(size_type from, size_type to) = 0; virtual void delete_edge(size_type from, size_type to) = 0; size_type nodes_count() { return m_nodes_count; } size_type edges_count() { return m_edges_count; } virtual ~Graph() {} }; class AdjList : public Graph { private: typedef std::list<size_type> Row; std::vector<Row> m_list; public: AdjList(size_type nodes_count) : Graph(nodes_count) { m_list.resize(nodes_count); } AdjList(const AdjList& g) : AdjList(g.m_nodes_count) { for (int i = 0; i < nodes_count(); i++) std::copy(g.m_list[i].begin(), g.m_list[i].end(), std::back_inserter(m_list[i])); } virtual bool is_edge(size_type from, size_type to) override { return std::find(m_list[from].begin(), m_list[from].end(), to) != m_list[from].end(); } virtual Graph& add_edge(size_type from, size_type to) override { if (!is_edge(from, to) && !is_edge(to, from)) { m_list[from].push_back(to); m_list[to].push_back(from); m_edges_count++; } return *this; } virtual void delete_edge(size_type from, size_type to) override { m_list[from].remove(to); m_list[to].remove(to); m_edges_count--; } virtual Neighbours neighbours(size_type node) { return m_list[node]; } }; ``` but when I try to get `graph.neighbours(v)` I get big amount of trash in it: ``` (gdb) p graph $1 = {<Graph> = {_vptr.Graph = 0x406210 <vtable for AdjList+16>, m_nodes_count = 3, m_edges_count = 3}, m_list = std::vector of length 3, capacity 3 = {std::list = {[0] = 2, [1] = 1}, std::list = {[0] = 0, [1] = 2}, std::list = {[0] = 0, [1] = 1}}} (gdb) p graph.neighbours(0) $2 = std::list = {[0] = 2, [1] = 1, [2] = 4294956560, [3] = 2, [4] = 1, [5] = 4294956560, [6] = 2, [7] = 1, [8] = 4294956560, [9] = 2, [10] = 1, [11] = 4294956560, [12] = 2, [13] = 1, [14] = 4294956560, [15] = 2, [16] = 1, [17] = 4294956560, [18] = 2, [19] = 1, [20] = 4294956560, [21] = 2, [22] = 1, [23] = 4294956560, [24] = 2, [25] = 1,... ``` How to fix that?
2013/06/17
[ "https://Stackoverflow.com/questions/17149200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1017941/" ]
`gdb` is probably getting confused by an **implementation detail** the `std::list`. E.g. the old [SGI STL `list`](http://www.sgi.com/tech/stl/stl_list.h) was implemented as a **circular list**. Inside the `list` object, there is only a singly `_List_node<_Tp>` pointer called `_M_node`. The constructor puts the internal `_M_next` pointer of the final node element equal to `_M_node` itself. The reason Standard Library implementations of `std::list` use this circular implementation is to avoid special cases for the final element (e.g. they could also use a a sentinel element with a `nullptr` next pointer). Matt Austern has a nice [ACCU presentation](http://www.accu-usa.org/Slides/SinglyLinkedLists.ppt) about this (but the link is currently to a corrupted file, see [archived version here](http://web.archive.org/web/20090618135116/http://www.accu-usa.org/Slides/SinglyLinkedLists.ppt)). This circular implementation explains why your `gdb` output for `g.neighbors()` has the repeating pattern of `[0] = 2, [1] = 1, [2] = 4294956560, /* etcetera */`. The value 4294956560 is simply the memory address of the internal `_M_node` variable of your `std::list`, so if `gdb` only does simnple pointer chasing, it will get confused. Notice that it is less than `2^32`, i.e. you are probably compiling this for 32-bits. You should probably verify this in your own `<list>` header of the Standard Library on your system. A bug report for `gdb` might also be in order.
I think that the problem is on the copy constructor, just do this: ``` AdjList(const AdjList& g) : AdjList(g.m_nodes_count) { m_list = g.m_list ; } ``` The `operator=()` method should create a new `Vector<Row>` with the same nodes that `g.m_list` has.
3,071,254
> > If $A\_1,A\_2,\dots,A\_m$ are independent and $\mathbb{P}(A\_i)=p$ for > $i=1,\dots,m$, find the probability that: > > > * none of the $A\_i$ occur, > * an even number of the $A\_i$ occur. > > > For the first question, I would say the required probability is: $$ 1 - \mathbb{P}(\cup\_i A\_i) = 1- \mathbb{P}(\cap\_i A\_i^c) = 1 - \prod\_{i=1}^m (1-p) = 1 - (1-p)^m. $$ The independence requirement is what allows to expand: $$ \mathbb{P}(\cap\_i A\_i^c) = \prod\_i\mathbb{P}(A\_i^c). $$ As for the second point, I was thinking for example that the case that exactly 2 events out of $m$ occur is: $$ {m \choose 2}p^2(1-p)^{m-2}, $$ the case that exactly four events occur is: $$ {m\choose 4}p^4(1-p)^{m-4}, $$ and so on, and then we would have to sum over all the even numbers less or equal than $m$. I am not sure of my answers though.
2019/01/12
[ "https://math.stackexchange.com/questions/3071254", "https://math.stackexchange.com", "https://math.stackexchange.com/users/517825/" ]
$\DeclareMathOperator{\im}{Im}\DeclareMathOperator{sp}{Span}\require{AMScd}$First, let us understand where all the maps are going in the Smith normal form: \begin{CD} \mathbb{Z}^4 @>A>> \mathbb{Z}^3\\ @APAA @AAQA \\ \mathbb{Z}^4 @>>D> \mathbb{Z}^3 \end{CD} $P$ and $Q$ are isomorphisms (invertible), $D$ is diagonal and $A = QDP^{-1}$. The point of $P$ and $Q$ is that they are a change of basis such that in the new basis, $A$ acts diagonally. We want to compute the image of $A$, or equivalently, the image of $QDP^{-1}$. First, I claim that $\im(A) = \im(QD)$ and this is because $P$ is invertible. > > Let $y \in \im(A)$. Then $y = Ax = QDP^{-1}$ for some $x$. So $y = QD(P^{-1}x)$ is in the image of $QD$. Next, let $y \in \im(QD)$. Then $y = QDx$ for some $x$. Since $P$ (and also $P^{-1}$) is invertible, there must be some $x'$ such that $x = P^{-1}x'$ (namely: $x' = Px$). Then $y = QDP^{-1}x' = Ax' \in \im{A}$. > > > The general rule here is that if $A = BC$ and $C$ is invertible, then $\im(A) = \im(B)$. Next, given any matrix, the image of that matrix is the same as the column space. > > To demonstrate, let $B$ have columns $v\_1, \dots, v\_n$ and let $x = (x\_1,\dots,x\_n)$. Then > $$ Bx = \begin{pmatrix} v\_1 & \cdots & v\_n \end{pmatrix} \begin{pmatrix} x\_1 \\ \vdots \\ x\_n \end{pmatrix} = x\_1v\_1 + \cdots + x\_nv\_n \in \sp\{v\_1,\dots,v\_n\}$$ > And conversely, any element $x\_1v\_1 + \cdots + x\_n v\_n \in \sp\{v\_1,\dots,v\_n\}$ can be written as $Bx$ where $x = (x\_1,\dots,x\_n)$. > > > So what we have shown is that $\im(A) = \im(QD) = \sp\{\text{columns of $QD$}\}$. Now the last step is what I said near the beginning: $P$ and $Q$ represent a change of basis. So the columns of $Q$ are a basis for $\mathbb{Z}^3$ and the columns of $P$ are a basis for $\mathbb{Z}^4$. (In fact, the same is true for $P^{-1}, Q^{-1}$ as well as $P^T$ and $Q^T$ or, more generally, any invertible matrix.) So the columns of $Q$ are a basis for $\mathbb{Z^3}$ and the (non-zero) columns of $QD$ are a basis for $\im(A)$. Then it's just a matter of understanding how diagonal matrices act on other matrices. Multiplying by a diagonal matrix on the right multiplies the columns by the corresponding diagonal element. Multiplying by a diagonal matrix on the left multiplies the rows by the corresponding diagonal element. This is why $QD$ is obtained from $Q$ by multiplying the columns by $-1, -2$, and $2$ respectively.
I don't know if you are follow the same course as mine but I had this exact exercice this semester with D. Testerman. Here is the solution : [![First Part](https://i.stack.imgur.com/zgTMp.png)](https://i.stack.imgur.com/zgTMp.png) [![Second Part](https://i.stack.imgur.com/ZwFIN.png)](https://i.stack.imgur.com/ZwFIN.png)
3,071,254
> > If $A\_1,A\_2,\dots,A\_m$ are independent and $\mathbb{P}(A\_i)=p$ for > $i=1,\dots,m$, find the probability that: > > > * none of the $A\_i$ occur, > * an even number of the $A\_i$ occur. > > > For the first question, I would say the required probability is: $$ 1 - \mathbb{P}(\cup\_i A\_i) = 1- \mathbb{P}(\cap\_i A\_i^c) = 1 - \prod\_{i=1}^m (1-p) = 1 - (1-p)^m. $$ The independence requirement is what allows to expand: $$ \mathbb{P}(\cap\_i A\_i^c) = \prod\_i\mathbb{P}(A\_i^c). $$ As for the second point, I was thinking for example that the case that exactly 2 events out of $m$ occur is: $$ {m \choose 2}p^2(1-p)^{m-2}, $$ the case that exactly four events occur is: $$ {m\choose 4}p^4(1-p)^{m-4}, $$ and so on, and then we would have to sum over all the even numbers less or equal than $m$. I am not sure of my answers though.
2019/01/12
[ "https://math.stackexchange.com/questions/3071254", "https://math.stackexchange.com", "https://math.stackexchange.com/users/517825/" ]
$\DeclareMathOperator{\im}{Im}\DeclareMathOperator{sp}{Span}\require{AMScd}$First, let us understand where all the maps are going in the Smith normal form: \begin{CD} \mathbb{Z}^4 @>A>> \mathbb{Z}^3\\ @APAA @AAQA \\ \mathbb{Z}^4 @>>D> \mathbb{Z}^3 \end{CD} $P$ and $Q$ are isomorphisms (invertible), $D$ is diagonal and $A = QDP^{-1}$. The point of $P$ and $Q$ is that they are a change of basis such that in the new basis, $A$ acts diagonally. We want to compute the image of $A$, or equivalently, the image of $QDP^{-1}$. First, I claim that $\im(A) = \im(QD)$ and this is because $P$ is invertible. > > Let $y \in \im(A)$. Then $y = Ax = QDP^{-1}$ for some $x$. So $y = QD(P^{-1}x)$ is in the image of $QD$. Next, let $y \in \im(QD)$. Then $y = QDx$ for some $x$. Since $P$ (and also $P^{-1}$) is invertible, there must be some $x'$ such that $x = P^{-1}x'$ (namely: $x' = Px$). Then $y = QDP^{-1}x' = Ax' \in \im{A}$. > > > The general rule here is that if $A = BC$ and $C$ is invertible, then $\im(A) = \im(B)$. Next, given any matrix, the image of that matrix is the same as the column space. > > To demonstrate, let $B$ have columns $v\_1, \dots, v\_n$ and let $x = (x\_1,\dots,x\_n)$. Then > $$ Bx = \begin{pmatrix} v\_1 & \cdots & v\_n \end{pmatrix} \begin{pmatrix} x\_1 \\ \vdots \\ x\_n \end{pmatrix} = x\_1v\_1 + \cdots + x\_nv\_n \in \sp\{v\_1,\dots,v\_n\}$$ > And conversely, any element $x\_1v\_1 + \cdots + x\_n v\_n \in \sp\{v\_1,\dots,v\_n\}$ can be written as $Bx$ where $x = (x\_1,\dots,x\_n)$. > > > So what we have shown is that $\im(A) = \im(QD) = \sp\{\text{columns of $QD$}\}$. Now the last step is what I said near the beginning: $P$ and $Q$ represent a change of basis. So the columns of $Q$ are a basis for $\mathbb{Z}^3$ and the columns of $P$ are a basis for $\mathbb{Z}^4$. (In fact, the same is true for $P^{-1}, Q^{-1}$ as well as $P^T$ and $Q^T$ or, more generally, any invertible matrix.) So the columns of $Q$ are a basis for $\mathbb{Z^3}$ and the (non-zero) columns of $QD$ are a basis for $\im(A)$. Then it's just a matter of understanding how diagonal matrices act on other matrices. Multiplying by a diagonal matrix on the right multiplies the columns by the corresponding diagonal element. Multiplying by a diagonal matrix on the left multiplies the rows by the corresponding diagonal element. This is why $QD$ is obtained from $Q$ by multiplying the columns by $-1, -2$, and $2$ respectively.
This took me six elementary column matrices, the 4 by 4 square matrix has determinant $1.$ Actually, I combined some steps, so it might be more reasonable to indicate the square matrix as $R = R\_1 R\_2R\_3R\_4R\_5R\_6R\_7 R\_8,$ this is the order when using column operations rather than the more familiar row operations. $$ \left( \begin{array}{rrrr} 2& 5& -1& 2 \\ -2& -16& -4& 4 \\ -2& -2& 0& 6 \\ \end{array} \right) \left( \begin{array}{rrrr} 1 &-3& -10 & -56 \\ 0 &1 & 3 & 17 \\ 1 &-3 & -9 &-53 \\ 0& -1 & -2 & -13 \\ \end{array} \right) = \left( \begin{array}{rrrr} 1 & 0 &0& 0 \\ -6 &-2& 0& 0 \\ -2 &-2& 2 & 0 \\ \end{array} \right) $$
69,062,041
Example: =MIN({"510";"515";"503";"";"";""}) How to get the min value of this array from **non-empty** items. Item *503* to be the minimum here and is the answer.
2021/09/05
[ "https://Stackoverflow.com/questions/69062041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1979578/" ]
This problem is about creating [disjoint sets](https://en.wikipedia.org/wiki/Disjoint-set_data_structure) and so I would use union-find methods. Now Python is not particularly known for being fast, but for the sake of showing the algorithm, here is an implementation of a `DisjointSet` class without libraries: ``` class DisjointSet: class Element: def __init__(self): self.parent = self self.rank = 0 def __init__(self): self.elements = {} def find(self, key): el = self.elements.get(key, None) if not el: el = self.Element() self.elements[key] = el else: # Path splitting algorithm while el.parent != el: el, el.parent = el.parent, el.parent.parent return el def union(self, key=None, *otherkeys): if key is not None: root = self.find(key) for otherkey in otherkeys: el = self.find(otherkey) if el != root: # Union by rank if root.rank < el.rank: root, el = el, root el.parent = root if root.rank == el.rank: root.rank += 1 def groups(self): result = { el: [] for el in self.elements.values() if el.parent == el } for key in self.elements: result[self.find(key)].append(key) return result ``` Here is how you could use it for this particular problem: ``` def solve(lists): disjoint = DisjointSet() for lst in lists: disjoint.union(*lst) groups = disjoint.groups() return [lst and groups[disjoint.find(lst[0])] for lst in lists] ``` Example call: ``` data = [ [0, 5, 101], [8, 9, 19, 21], [], [78, 79], [5, 7, 63, 64] ] result = solve(data) ``` The result will be: ``` [[0, 5, 101, 7, 63, 64], [8, 9, 19, 21], [], [78, 79], [0, 5, 101, 7, 63, 64]] ``` Note that I added an empty list in the input list, so to illustrate that this boundary case remains unaltered. NB: There are libraries out there that provide union-find/disjoint set functionality, each with a slightly different API, but I suppose that using one of those can give a better performance.
Do you mean by?: ``` from itertools import combinations l1 = [0, 5, 7, 63, 64, 101] l2 = [8, 9, 19] l3 = [78, 79] l4 = [5, 4, 34] print([v for x, y in combinations([l1, l2, l3, l4], 2) for v in {*x} & {*y}]) ``` Output: ``` [5] ```
17,447
I'm new to Arduino and microcontroller . I want to connect my Arduino Mega to three slaves which Arduino Unos. I know that these slaves will share MISO, MOSI, and SCK lines. However, SS is unique to each slave. For single slave, the SS is pin 53. So, for three slaves, which other two pins can I use as SS? Thank you for your help.
2015/11/03
[ "https://arduino.stackexchange.com/questions/17447", "https://arduino.stackexchange.com", "https://arduino.stackexchange.com/users/14543/" ]
To better understand how you can do this it is good to understand first just what goes on when a button bounces. It is, literally, bouncing - just like a ball when you drop it. Due to the fact that it's either connected to ground or pulled up to +5V by the pullup resistor it's either going to be LOW or HIGH with very little time between when it's not in either state, so we can pretty much ignore the rise and fall times of the signal. It's either connected to ground, or it's not connected to ground. And we're only really interested in when it's connected to ground. More importantly we're interested in *how long* it's been connected to ground for. By remembering the time it transitioned from HIGH to LOW and then comparing that time to the current time you can know how long it has been connected to ground. By noticing when it's no longer connected to ground and "forgetting" the time you remembered you can start counting afresh with the next transition from HIGH to LOW. Take the following diagram for instance: [![enter image description here](https://i.stack.imgur.com/S2wVC.png)](https://i.stack.imgur.com/S2wVC.png) The blue line is the state of the button. As you can see it starts HIGH, then it gets pressed to be LOW and bounces between HIGH and LOW a number of times before it settles on being LOW. The red line is the difference between a timestamp that is set to be equal to `millis()` at the moment the button transitions from HIGH to LOW and the current `millis()` value, and is ignored when the button is HIGH. As you can see the difference between that timestamp and the current `millis()` value steadily increases. Whenever the button bounces to the HIGH state it resets that difference, and it starts again with the next LOW transition. When the button has finished bouncing there is nothing to change the state of the timestamp, so the difference keeps increasing. Eventually that difference will pass a trigger point (the yellow line in this diagram) and at that point you can be fairly sure that the button has finished bouncing and you should react to it. To translate that into some code, you may end up with something like this (untested): ``` // Two variables to store remembered state information - the time // of the last HIGH-LOW transition and the previous state of the // button. static uint32_t debounceTime = 0; static uint8_t buttonState = HIGH; // Check to see if the button has changed state if (digitalRead(buttonPin) != buttonState) { // Remember the new state buttonState = digitalRead(buttonPin); // If the new state is LOW ... if (buttonState == LOW) { // ... then record the time stamp debounceTime = millis(); } else { // ... otherwise set the time stamp to 0 for "don't care". debounceTime = 0; } } // If the time stamp is more than 0 and the difference between now and // then is greater than 10ms ... if (debounceTime > 0 && (millis() - debounceTime > 10)) { // ... set the time stamp to 0 to say we have finished debouncing debounceTime = 0; // and do whatever it is you need to do. digitalWrite(ledPin, HIGH); } ``` There are various tweaks and additions that could be made to that method, but that gives you the basic idea of how you split the debouncing away from the reacting, and it's the *results* of the debouncing that you react to, not the button state itself.
Actually, Majenko's diagram assumes the interplay of the pullup resistor forces the line back to a HIGH position (as quickly as the internal transistors can overpower the drop from the switch). If the switch itself is mechanical with a pullup resistor (external or internal), then the only thing "bouncing" is the switch. If you use a digital switch, the rise is much sharper without significant bounce. A cheap and effective debouncing tactic is to add a capacitor in parallel with the switch. The cap will drop to GND quickly as the switch drains the charge stored in the cap. But the cap will take a while to recharge since its only source is through the resistor (during which time the mechanicals settle down). (This looks much better in a diagram, but I haven't figured out how to draw on here yet.) I wish I could recommend values, but it really depends on the mechanicals of the switch and the certainty of the debounce desired--make everything HUGE and you're guaranteed no bounce, use values in between and you go on probabilities. I usually start out with 0.1uF and vary it up or down until I get a balance between reliability and speed. The main advantage is, of course, you use absolutely no computing time to debounce any number of switches. Potential disadvantages: * Added hardware cost for each switch, making this technique less desirable in production scenarios * 0/1 thresholds of input pins will vary across the manufacturing process, so one cap / input pin may have a different debounce time than another on an identical circuit. * Software debouncing schemes can note that the switch is pushed on the first drop to GND, where this hardware-only tactic relies on the last actual contact with GND. As the switch ages, I've seen this delay exceed 50 mSec. * Since the bounce is mechanical at its core, bounce worsens over the life of the mechanical part (in this case the switch). Typically, software can be fine-tuned easier than hardware. Often, however, swapping out a cap is easier than reflashing firmware.
195,030
I'm just throwing this out there for discussion/answering: If person A sat in a chair all his life, in a house on earth (let's say 100 years), and person B flew around in earth's atmosphere at let's say 1000km/h or 1000mph (which ever is easiest to comprehend) for 100 years. Would there be a time difference for those people at the end of their life? would person B's clock have ran slower than person A, as person B was traveling at a speed closer to the speed of light, or is this speed too slow to be relevant?
2015/07/20
[ "https://physics.stackexchange.com/questions/195030", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/86302/" ]
As I understand it regular fusion in a star takes light elements as input and the output is heavier elements and energy. There are several potential steps in the regular process, e.g: * Hydrogen fusing to helium **and producing energy** which keeps the star from collapsing. * After a lot of hydrygen is spent and helium has collected in the center of the star the hydrogen fusion reactions tapers off. The star shrinks. **Pressure and heat increase in the core**. The core starts burning helium. * Repeat for heavier elements. E.g. up to oxygen/carbon. Now I stressed a few points in the regular process: * "and producing energy": The reaction is endothermic. If you needed to add energy instead then processes tend not to work or much slower. * Add to that that fusing iron does **not** produce energy. Lighter element than iron/tin produce energy if fused. Heavier elements produce energy when split. Iron/Ni is the most stable element. * "Pressure and heat increase in the core": There is no fusion to produce heat, but you can increase pressure by just adding a lot of mass. If you add enough mass then you will get very dense iron. At some point the mass gets big enough to that it is not merely resisted by the electric charges of the charged iron aton cores, but also by the pressure of electrons. (See [Degenerate matter](https://en.wikipedia.org/wiki/Degenerate_matter)). Add enough and you might get neutronium rather than heavier elements. > > To be plain, I am not talking about stellar fusion or whether there is enough latent > energy to continue fusion at an already existing core. I want to know if there was > enough collective mass in the debris field, could the field itself, coalesce to the > point where the heavy elements will fuse. > > > Well, yes and no. Add enough and it will change to a neutron star or beyond. I guess you could consider that a technical yes with a single star sized atom. It also feels as if I am playing word games. Everything I have read (but I am not a physic person) seems to say that fusion stops. You will get very many iron atoms close to each other. Statistically I guess some might fuse and thereby cool the coalicing mass of iron. But intuition tells me that most will stay iron. Add more and it just gets denser and denser until it become energytically advantageous to capture elctrons and change to neutronium. (which, though very heavy/dense) is the opposite. It goes to element 0, not to classic 'heavier' elements.
As I understand it, iron will not be able to fuse with iron no matter how much of it you have gravitationally bound. Instead to fuse iron atoms together requires a supernova.
195,030
I'm just throwing this out there for discussion/answering: If person A sat in a chair all his life, in a house on earth (let's say 100 years), and person B flew around in earth's atmosphere at let's say 1000km/h or 1000mph (which ever is easiest to comprehend) for 100 years. Would there be a time difference for those people at the end of their life? would person B's clock have ran slower than person A, as person B was traveling at a speed closer to the speed of light, or is this speed too slow to be relevant?
2015/07/20
[ "https://physics.stackexchange.com/questions/195030", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/86302/" ]
> > Let's say a field of stars all die within a short amount of time. Just > for argument's sake they produce a debris field of iron ( or any other > heavy element). Provided that there is enough time the debris will > agglomerate, we know this. > > > My question: Given enough mass, will this agglomeration of heavy > elements fuse into even heavier elements? > > > Short answer, no, as others have said. At least, not in the stellar fusion sense, because heavier than Iron doesn't fuse in stellar fusion. Heavier than Iron fuses in supernova explosions. Quick Source: <http://curious.astro.cornell.edu/copyright-notice/85-the-universe/supernovae/general-questions/418-how-are-elements-heavier-than-iron-formed-intermediate> More info here: [Origin of elements heavier than Iron (Fe)](https://physics.stackexchange.com/questions/7131/origin-of-elements-heavier-than-iron-fe) > > To be plain, I am not talking about stellar fusion or whether there is > enough latent energy to continue fusion at an already existing core. I > want to know if there was enough collective mass in the debris field, > could the field itself, coalesce to the point where the heavy elements > will fuse. > > > Lets examine what happens when the iron coalesces, and in reality, it's unlikely that you'd have Iron and nothing else. It's hard to imagine a share of hydrogen, helium, carbon, etc, wouldn't be present, but assuming just Iron: First, you get something similar to a planet or a planet core. That gets bigger as more coalesces. Then something cool happens (or, well, hot more specifically), but it's kinda neat. At a certain point, the planet stops getting bigger and starts getting smaller, and as it gets smaller, it gets hotter, not from fusion, just the energy of coalescing. In time, it could glow hot like the sun, but much smaller than a sun. If I was to guess, the peak size might be around the size of Neptune. (Peak hydrogen planet size is about the size of Jupiter, peak Iron planet size would, I would think, be a fair bit smaller). Eventually, with enough mass, you get something something similar to a white dwarf. Iron white dwarfs don't exist because stars that become white dwarfs don't get to the Iron creation stage. There's some metallicity, but essentially, white dwarfs are carbon/Oxygen, or, smaller ones can be made of Helium and sometimes, there's some Neon, Magnesium - more on that here: <https://en.wikipedia.org/wiki/White_dwarf> Your scenario would essentially become an Iron white dwarf. Then, as with any white dwarf, at a certain mass, it reaches the Chandrasekhar limit and the inside of the star would begin to degenerate into a Neutron Star and once that process begins, it moves quickly and you basically have a really really really big boom and a type 1a supernova. And during the supernova, a lot of the Iron would fuse into heavier elements, but it would kind of happen all of a sudden, in the reasonably short period of time.
As I understand it, iron will not be able to fuse with iron no matter how much of it you have gravitationally bound. Instead to fuse iron atoms together requires a supernova.
195,030
I'm just throwing this out there for discussion/answering: If person A sat in a chair all his life, in a house on earth (let's say 100 years), and person B flew around in earth's atmosphere at let's say 1000km/h or 1000mph (which ever is easiest to comprehend) for 100 years. Would there be a time difference for those people at the end of their life? would person B's clock have ran slower than person A, as person B was traveling at a speed closer to the speed of light, or is this speed too slow to be relevant?
2015/07/20
[ "https://physics.stackexchange.com/questions/195030", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/86302/" ]
The answer is a qualified yes, depending on your definition of fusion. If you collect together a mass of iron less than about $1.2M\_{\odot}$ it is possible for that to form a stable configuration, a little smaller than the size of the Earth, supported by electron degeneracy pressure. Such a star would just sit there and cool forever and all that would happen is that the iron would crystallise. However, if you added more mass and tipped it over about $1.2M\_{\odot}$ then the degenerate electrons have enough energy to begin inverse beta (electron capture) reactions onto iron nuclei. This raises the number of mass units per electron, takes free electrons out of the gas and causes a catastrophic softening of the equation of state. The result would perhaps be some sort of weird supernova explosion, perhaps leaving behind a neutron star remnant (or the whole thing might explosively deflagrate). Many elements heavier than iron could be produced by the r-process in such an explosion. *If* a neutron star remains, then the neutron star will have a crust above its mostly neutron interior. The crust composition will be determined by minimising its energy density subject to the constraints of charge and baryon conservation. Such calculations routinely show that a density-dependent equilibrium composition is reached that features increasingly neutron-rich nuclei with depth, that can have atomic numbers *much higher than iron* and atomic masses of up to 200 or more. So, if you count that as fusion (I wouldn't) then yes, you could ultimately produce nuclei that were much heavier than iron.
As I understand it, iron will not be able to fuse with iron no matter how much of it you have gravitationally bound. Instead to fuse iron atoms together requires a supernova.
195,030
I'm just throwing this out there for discussion/answering: If person A sat in a chair all his life, in a house on earth (let's say 100 years), and person B flew around in earth's atmosphere at let's say 1000km/h or 1000mph (which ever is easiest to comprehend) for 100 years. Would there be a time difference for those people at the end of their life? would person B's clock have ran slower than person A, as person B was traveling at a speed closer to the speed of light, or is this speed too slow to be relevant?
2015/07/20
[ "https://physics.stackexchange.com/questions/195030", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/86302/" ]
> > Let's say a field of stars all die within a short amount of time. Just > for argument's sake they produce a debris field of iron ( or any other > heavy element). Provided that there is enough time the debris will > agglomerate, we know this. > > > My question: Given enough mass, will this agglomeration of heavy > elements fuse into even heavier elements? > > > Short answer, no, as others have said. At least, not in the stellar fusion sense, because heavier than Iron doesn't fuse in stellar fusion. Heavier than Iron fuses in supernova explosions. Quick Source: <http://curious.astro.cornell.edu/copyright-notice/85-the-universe/supernovae/general-questions/418-how-are-elements-heavier-than-iron-formed-intermediate> More info here: [Origin of elements heavier than Iron (Fe)](https://physics.stackexchange.com/questions/7131/origin-of-elements-heavier-than-iron-fe) > > To be plain, I am not talking about stellar fusion or whether there is > enough latent energy to continue fusion at an already existing core. I > want to know if there was enough collective mass in the debris field, > could the field itself, coalesce to the point where the heavy elements > will fuse. > > > Lets examine what happens when the iron coalesces, and in reality, it's unlikely that you'd have Iron and nothing else. It's hard to imagine a share of hydrogen, helium, carbon, etc, wouldn't be present, but assuming just Iron: First, you get something similar to a planet or a planet core. That gets bigger as more coalesces. Then something cool happens (or, well, hot more specifically), but it's kinda neat. At a certain point, the planet stops getting bigger and starts getting smaller, and as it gets smaller, it gets hotter, not from fusion, just the energy of coalescing. In time, it could glow hot like the sun, but much smaller than a sun. If I was to guess, the peak size might be around the size of Neptune. (Peak hydrogen planet size is about the size of Jupiter, peak Iron planet size would, I would think, be a fair bit smaller). Eventually, with enough mass, you get something something similar to a white dwarf. Iron white dwarfs don't exist because stars that become white dwarfs don't get to the Iron creation stage. There's some metallicity, but essentially, white dwarfs are carbon/Oxygen, or, smaller ones can be made of Helium and sometimes, there's some Neon, Magnesium - more on that here: <https://en.wikipedia.org/wiki/White_dwarf> Your scenario would essentially become an Iron white dwarf. Then, as with any white dwarf, at a certain mass, it reaches the Chandrasekhar limit and the inside of the star would begin to degenerate into a Neutron Star and once that process begins, it moves quickly and you basically have a really really really big boom and a type 1a supernova. And during the supernova, a lot of the Iron would fuse into heavier elements, but it would kind of happen all of a sudden, in the reasonably short period of time.
As I understand it regular fusion in a star takes light elements as input and the output is heavier elements and energy. There are several potential steps in the regular process, e.g: * Hydrogen fusing to helium **and producing energy** which keeps the star from collapsing. * After a lot of hydrygen is spent and helium has collected in the center of the star the hydrogen fusion reactions tapers off. The star shrinks. **Pressure and heat increase in the core**. The core starts burning helium. * Repeat for heavier elements. E.g. up to oxygen/carbon. Now I stressed a few points in the regular process: * "and producing energy": The reaction is endothermic. If you needed to add energy instead then processes tend not to work or much slower. * Add to that that fusing iron does **not** produce energy. Lighter element than iron/tin produce energy if fused. Heavier elements produce energy when split. Iron/Ni is the most stable element. * "Pressure and heat increase in the core": There is no fusion to produce heat, but you can increase pressure by just adding a lot of mass. If you add enough mass then you will get very dense iron. At some point the mass gets big enough to that it is not merely resisted by the electric charges of the charged iron aton cores, but also by the pressure of electrons. (See [Degenerate matter](https://en.wikipedia.org/wiki/Degenerate_matter)). Add enough and you might get neutronium rather than heavier elements. > > To be plain, I am not talking about stellar fusion or whether there is enough latent > energy to continue fusion at an already existing core. I want to know if there was > enough collective mass in the debris field, could the field itself, coalesce to the > point where the heavy elements will fuse. > > > Well, yes and no. Add enough and it will change to a neutron star or beyond. I guess you could consider that a technical yes with a single star sized atom. It also feels as if I am playing word games. Everything I have read (but I am not a physic person) seems to say that fusion stops. You will get very many iron atoms close to each other. Statistically I guess some might fuse and thereby cool the coalicing mass of iron. But intuition tells me that most will stay iron. Add more and it just gets denser and denser until it become energytically advantageous to capture elctrons and change to neutronium. (which, though very heavy/dense) is the opposite. It goes to element 0, not to classic 'heavier' elements.
195,030
I'm just throwing this out there for discussion/answering: If person A sat in a chair all his life, in a house on earth (let's say 100 years), and person B flew around in earth's atmosphere at let's say 1000km/h or 1000mph (which ever is easiest to comprehend) for 100 years. Would there be a time difference for those people at the end of their life? would person B's clock have ran slower than person A, as person B was traveling at a speed closer to the speed of light, or is this speed too slow to be relevant?
2015/07/20
[ "https://physics.stackexchange.com/questions/195030", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/86302/" ]
As I understand it regular fusion in a star takes light elements as input and the output is heavier elements and energy. There are several potential steps in the regular process, e.g: * Hydrogen fusing to helium **and producing energy** which keeps the star from collapsing. * After a lot of hydrygen is spent and helium has collected in the center of the star the hydrogen fusion reactions tapers off. The star shrinks. **Pressure and heat increase in the core**. The core starts burning helium. * Repeat for heavier elements. E.g. up to oxygen/carbon. Now I stressed a few points in the regular process: * "and producing energy": The reaction is endothermic. If you needed to add energy instead then processes tend not to work or much slower. * Add to that that fusing iron does **not** produce energy. Lighter element than iron/tin produce energy if fused. Heavier elements produce energy when split. Iron/Ni is the most stable element. * "Pressure and heat increase in the core": There is no fusion to produce heat, but you can increase pressure by just adding a lot of mass. If you add enough mass then you will get very dense iron. At some point the mass gets big enough to that it is not merely resisted by the electric charges of the charged iron aton cores, but also by the pressure of electrons. (See [Degenerate matter](https://en.wikipedia.org/wiki/Degenerate_matter)). Add enough and you might get neutronium rather than heavier elements. > > To be plain, I am not talking about stellar fusion or whether there is enough latent > energy to continue fusion at an already existing core. I want to know if there was > enough collective mass in the debris field, could the field itself, coalesce to the > point where the heavy elements will fuse. > > > Well, yes and no. Add enough and it will change to a neutron star or beyond. I guess you could consider that a technical yes with a single star sized atom. It also feels as if I am playing word games. Everything I have read (but I am not a physic person) seems to say that fusion stops. You will get very many iron atoms close to each other. Statistically I guess some might fuse and thereby cool the coalicing mass of iron. But intuition tells me that most will stay iron. Add more and it just gets denser and denser until it become energytically advantageous to capture elctrons and change to neutronium. (which, though very heavy/dense) is the opposite. It goes to element 0, not to classic 'heavier' elements.
Iron won't fuse into heavier elements. It's a question of nuclear physics. Iron is the most stable form of nuclear matter. In other words, iron has the lowest energy configuration of all nuclear matter. Fusion can appear in the cores of stars because it's an exothermic process, that is, fusing nuclei lighter than iron can lower the nuclear matter's energy state and release heat in the process. Once the nuclei become made of iron, fusion will not be energetically favorable. Nuclei heavier than iron are created by neutron capture processes, which is not the same as fusion. So you can't just "clump" iron nuclei together to form heavier elements, you need to bombard them with neutrons somehow.
195,030
I'm just throwing this out there for discussion/answering: If person A sat in a chair all his life, in a house on earth (let's say 100 years), and person B flew around in earth's atmosphere at let's say 1000km/h or 1000mph (which ever is easiest to comprehend) for 100 years. Would there be a time difference for those people at the end of their life? would person B's clock have ran slower than person A, as person B was traveling at a speed closer to the speed of light, or is this speed too slow to be relevant?
2015/07/20
[ "https://physics.stackexchange.com/questions/195030", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/86302/" ]
> > Let's say a field of stars all die within a short amount of time. Just > for argument's sake they produce a debris field of iron ( or any other > heavy element). Provided that there is enough time the debris will > agglomerate, we know this. > > > My question: Given enough mass, will this agglomeration of heavy > elements fuse into even heavier elements? > > > Short answer, no, as others have said. At least, not in the stellar fusion sense, because heavier than Iron doesn't fuse in stellar fusion. Heavier than Iron fuses in supernova explosions. Quick Source: <http://curious.astro.cornell.edu/copyright-notice/85-the-universe/supernovae/general-questions/418-how-are-elements-heavier-than-iron-formed-intermediate> More info here: [Origin of elements heavier than Iron (Fe)](https://physics.stackexchange.com/questions/7131/origin-of-elements-heavier-than-iron-fe) > > To be plain, I am not talking about stellar fusion or whether there is > enough latent energy to continue fusion at an already existing core. I > want to know if there was enough collective mass in the debris field, > could the field itself, coalesce to the point where the heavy elements > will fuse. > > > Lets examine what happens when the iron coalesces, and in reality, it's unlikely that you'd have Iron and nothing else. It's hard to imagine a share of hydrogen, helium, carbon, etc, wouldn't be present, but assuming just Iron: First, you get something similar to a planet or a planet core. That gets bigger as more coalesces. Then something cool happens (or, well, hot more specifically), but it's kinda neat. At a certain point, the planet stops getting bigger and starts getting smaller, and as it gets smaller, it gets hotter, not from fusion, just the energy of coalescing. In time, it could glow hot like the sun, but much smaller than a sun. If I was to guess, the peak size might be around the size of Neptune. (Peak hydrogen planet size is about the size of Jupiter, peak Iron planet size would, I would think, be a fair bit smaller). Eventually, with enough mass, you get something something similar to a white dwarf. Iron white dwarfs don't exist because stars that become white dwarfs don't get to the Iron creation stage. There's some metallicity, but essentially, white dwarfs are carbon/Oxygen, or, smaller ones can be made of Helium and sometimes, there's some Neon, Magnesium - more on that here: <https://en.wikipedia.org/wiki/White_dwarf> Your scenario would essentially become an Iron white dwarf. Then, as with any white dwarf, at a certain mass, it reaches the Chandrasekhar limit and the inside of the star would begin to degenerate into a Neutron Star and once that process begins, it moves quickly and you basically have a really really really big boom and a type 1a supernova. And during the supernova, a lot of the Iron would fuse into heavier elements, but it would kind of happen all of a sudden, in the reasonably short period of time.
Iron won't fuse into heavier elements. It's a question of nuclear physics. Iron is the most stable form of nuclear matter. In other words, iron has the lowest energy configuration of all nuclear matter. Fusion can appear in the cores of stars because it's an exothermic process, that is, fusing nuclei lighter than iron can lower the nuclear matter's energy state and release heat in the process. Once the nuclei become made of iron, fusion will not be energetically favorable. Nuclei heavier than iron are created by neutron capture processes, which is not the same as fusion. So you can't just "clump" iron nuclei together to form heavier elements, you need to bombard them with neutrons somehow.
195,030
I'm just throwing this out there for discussion/answering: If person A sat in a chair all his life, in a house on earth (let's say 100 years), and person B flew around in earth's atmosphere at let's say 1000km/h or 1000mph (which ever is easiest to comprehend) for 100 years. Would there be a time difference for those people at the end of their life? would person B's clock have ran slower than person A, as person B was traveling at a speed closer to the speed of light, or is this speed too slow to be relevant?
2015/07/20
[ "https://physics.stackexchange.com/questions/195030", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/86302/" ]
> > Let's say a field of stars all die within a short amount of time. Just > for argument's sake they produce a debris field of iron ( or any other > heavy element). Provided that there is enough time the debris will > agglomerate, we know this. > > > My question: Given enough mass, will this agglomeration of heavy > elements fuse into even heavier elements? > > > Short answer, no, as others have said. At least, not in the stellar fusion sense, because heavier than Iron doesn't fuse in stellar fusion. Heavier than Iron fuses in supernova explosions. Quick Source: <http://curious.astro.cornell.edu/copyright-notice/85-the-universe/supernovae/general-questions/418-how-are-elements-heavier-than-iron-formed-intermediate> More info here: [Origin of elements heavier than Iron (Fe)](https://physics.stackexchange.com/questions/7131/origin-of-elements-heavier-than-iron-fe) > > To be plain, I am not talking about stellar fusion or whether there is > enough latent energy to continue fusion at an already existing core. I > want to know if there was enough collective mass in the debris field, > could the field itself, coalesce to the point where the heavy elements > will fuse. > > > Lets examine what happens when the iron coalesces, and in reality, it's unlikely that you'd have Iron and nothing else. It's hard to imagine a share of hydrogen, helium, carbon, etc, wouldn't be present, but assuming just Iron: First, you get something similar to a planet or a planet core. That gets bigger as more coalesces. Then something cool happens (or, well, hot more specifically), but it's kinda neat. At a certain point, the planet stops getting bigger and starts getting smaller, and as it gets smaller, it gets hotter, not from fusion, just the energy of coalescing. In time, it could glow hot like the sun, but much smaller than a sun. If I was to guess, the peak size might be around the size of Neptune. (Peak hydrogen planet size is about the size of Jupiter, peak Iron planet size would, I would think, be a fair bit smaller). Eventually, with enough mass, you get something something similar to a white dwarf. Iron white dwarfs don't exist because stars that become white dwarfs don't get to the Iron creation stage. There's some metallicity, but essentially, white dwarfs are carbon/Oxygen, or, smaller ones can be made of Helium and sometimes, there's some Neon, Magnesium - more on that here: <https://en.wikipedia.org/wiki/White_dwarf> Your scenario would essentially become an Iron white dwarf. Then, as with any white dwarf, at a certain mass, it reaches the Chandrasekhar limit and the inside of the star would begin to degenerate into a Neutron Star and once that process begins, it moves quickly and you basically have a really really really big boom and a type 1a supernova. And during the supernova, a lot of the Iron would fuse into heavier elements, but it would kind of happen all of a sudden, in the reasonably short period of time.
The answer is a qualified yes, depending on your definition of fusion. If you collect together a mass of iron less than about $1.2M\_{\odot}$ it is possible for that to form a stable configuration, a little smaller than the size of the Earth, supported by electron degeneracy pressure. Such a star would just sit there and cool forever and all that would happen is that the iron would crystallise. However, if you added more mass and tipped it over about $1.2M\_{\odot}$ then the degenerate electrons have enough energy to begin inverse beta (electron capture) reactions onto iron nuclei. This raises the number of mass units per electron, takes free electrons out of the gas and causes a catastrophic softening of the equation of state. The result would perhaps be some sort of weird supernova explosion, perhaps leaving behind a neutron star remnant (or the whole thing might explosively deflagrate). Many elements heavier than iron could be produced by the r-process in such an explosion. *If* a neutron star remains, then the neutron star will have a crust above its mostly neutron interior. The crust composition will be determined by minimising its energy density subject to the constraints of charge and baryon conservation. Such calculations routinely show that a density-dependent equilibrium composition is reached that features increasingly neutron-rich nuclei with depth, that can have atomic numbers *much higher than iron* and atomic masses of up to 200 or more. So, if you count that as fusion (I wouldn't) then yes, you could ultimately produce nuclei that were much heavier than iron.
195,030
I'm just throwing this out there for discussion/answering: If person A sat in a chair all his life, in a house on earth (let's say 100 years), and person B flew around in earth's atmosphere at let's say 1000km/h or 1000mph (which ever is easiest to comprehend) for 100 years. Would there be a time difference for those people at the end of their life? would person B's clock have ran slower than person A, as person B was traveling at a speed closer to the speed of light, or is this speed too slow to be relevant?
2015/07/20
[ "https://physics.stackexchange.com/questions/195030", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/86302/" ]
The answer is a qualified yes, depending on your definition of fusion. If you collect together a mass of iron less than about $1.2M\_{\odot}$ it is possible for that to form a stable configuration, a little smaller than the size of the Earth, supported by electron degeneracy pressure. Such a star would just sit there and cool forever and all that would happen is that the iron would crystallise. However, if you added more mass and tipped it over about $1.2M\_{\odot}$ then the degenerate electrons have enough energy to begin inverse beta (electron capture) reactions onto iron nuclei. This raises the number of mass units per electron, takes free electrons out of the gas and causes a catastrophic softening of the equation of state. The result would perhaps be some sort of weird supernova explosion, perhaps leaving behind a neutron star remnant (or the whole thing might explosively deflagrate). Many elements heavier than iron could be produced by the r-process in such an explosion. *If* a neutron star remains, then the neutron star will have a crust above its mostly neutron interior. The crust composition will be determined by minimising its energy density subject to the constraints of charge and baryon conservation. Such calculations routinely show that a density-dependent equilibrium composition is reached that features increasingly neutron-rich nuclei with depth, that can have atomic numbers *much higher than iron* and atomic masses of up to 200 or more. So, if you count that as fusion (I wouldn't) then yes, you could ultimately produce nuclei that were much heavier than iron.
Iron won't fuse into heavier elements. It's a question of nuclear physics. Iron is the most stable form of nuclear matter. In other words, iron has the lowest energy configuration of all nuclear matter. Fusion can appear in the cores of stars because it's an exothermic process, that is, fusing nuclei lighter than iron can lower the nuclear matter's energy state and release heat in the process. Once the nuclei become made of iron, fusion will not be energetically favorable. Nuclei heavier than iron are created by neutron capture processes, which is not the same as fusion. So you can't just "clump" iron nuclei together to form heavier elements, you need to bombard them with neutrons somehow.
34,066,607
When I have to write a reference to a callable function I use the standard syntax of PHP [defined as](http://php.net/manual/it/language.types.callable.php): > > A PHP function is **passed by its name as a string**. Any built-in or user-defined function can be used *[... omitted...]*. > > > A method of an instantiated object is passed as an array containing an object at index 0 and the **method name** *(aka string)* > at index 1. > > > Static class methods can also be passed without instantiating an object of that class by passing the **class name** *(still a string)* > instead of an object at index 0. > > > As of PHP 5.2.3, it is also possible to pass *(the string)* **'ClassName::methodName'**. > > > Apart from common user-defined function, anonymous functions can also be passed to a callback parameter. > > > All of these ways are not "IDE friendly" for operations like *function name refactor* or *find usage of*. In my answer I propose a solution, but there are other approaches that can be applied, even totally different, that allow to IDE to "find" the invocation of the methods?
2015/12/03
[ "https://Stackoverflow.com/questions/34066607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7002281/" ]
You already are next to the shortest thing you can do You can perfectly call your anonymous function directly in your function call without using a variable For instance, you can replace: ``` $callable=function($param) use ($object){ return $object->myMethod($param); } call_user_func($callable, $param); ``` by: ``` call_user_func(function($param) use ($object){ return $object->myMethod($param); }, $param); ``` You will have to wait for [arrow functions](https://wiki.php.net/rfc/arrow_functions) in future PHP versions, and you should be able to use something like: ``` call_user_func(fn($a) => $object->myMethod($a), $param); ```
I became to a solution, always based on the [anonymous-functions](http://php.net/manual/it/functions.anonymous.php) that solve the problem but leave me not full satisfied: **Static method of a class** ``` $callable = function($param){ return \my\namespace\myClass::myMethod($param); } ``` **method of a object** ``` $callable = function($param) use ($object){ return $object->myMethod($param); } ``` **method of $this object** ``` $callable = function($param){ return self::myMethod($param); } ``` --- **Alternatives for oldest php versions** Inside the all classess you gonna call (or in their parents) define the function *classname()* as follow: ``` public static function className() { return get_called_class(); } ``` or for *very* old PHP: ``` public static function className() { return "MyClass"; } ``` Then ``` call_user_func(array(MyClass::className(), 'myCallbackMethod')); ```
34,440,838
WebBrowser control has a ContextMenuStrip property that can be set to a context menu. But this menu appears by right-click, how can I show it by left-click? There is no `Click` event for WebBrowser control and the `MousePosition` of `WebBrowser.Document` click event is not precise. It seems it depends on the element the mouse is over and also if the browser scrolls isn't shown in right place.
2015/12/23
[ "https://Stackoverflow.com/questions/34440838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2651073/" ]
You can assign a handler to [`Click`](https://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.click(v=vs.110).aspx) event or other mouse events of [`Document`](https://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.document(v=vs.110).aspx) and show the context menu at [`Cursor.Position`](https://msdn.microsoft.com/en-us/library/system.windows.forms.cursor.position(v=vs.110).aspx). You can also prevent the default click action `e.ReturnValue = false;`. ``` private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { this.webBrowser1.Document.Click += Document_Click; } void Document_Click(object sender, HtmlElementEventArgs e) { //To prevent the default click action you can uncomment next line: //e.ReturnValue = false; this.contextMenuStrip1.Show(Cursor.Position); } ```
Here is some code for you. What you are looking for is doable with an event handler. If you need help please ask in comments. ``` this._browser.DocumentCompleted+=new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted); ... private void browser_DocumentCompleted(Object sender, WebBrowserDocumentCompletedEventArgs e) { this._browser.Document.Body.MouseDown += new HtmlElementEventHandler(Body_MouseDown); } ... void Body_MouseDown(Object sender, HtmlElementEventArgs e) { switch(e.MouseButtonsPressed) { case MouseButtons.Left: //your code break; } } ```
70,423,477
I have a C++ class which I intend to call from python's mpi4py interface such that each node spawns the class. On the C++ side, I'm using the [Open MPI](https://www.open-mpi.org/) library (installed via [homebrew](https://formulae.brew.sh/formula/open-mpi)) and [pybind11](https://github.com/pybind/pybind11). The C++ class is as follows: ```cpp #include <pybind11/pybind11.h> #include <iostream> #include <chrono> #include <thread> #include <vector> #include <mpi.h> // #define PyMPI_HAVE_MPI_Message 1 // #include <mpi4py/mpi4py.h> namespace py = pybind11; class SomeComputation { float multiplier; std::vector<int> test; MPI_Comm comm_; public: void Init() { int rank; MPI_Comm_rank(comm_, &rank); test.clear(); test.resize(10, rank); } void set_comm(MPI_Comm comm){ this->comm_ = comm; } SomeComputation(float multiplier_) : multiplier(multiplier_){} ~SomeComputation() { std::cout << "Destructor Called!\n"; } float compute(float input) { std::this_thread::sleep_for(std::chrono::milliseconds((int)input * 10)); for (int i = 0; i != 10; ++i) { std::cout << test[i] << " "; } std::cout << std::endl; return multiplier * input; } }; PYBIND11_MODULE(module_name, handle) { py::class_<SomeComputation>(handle, "Cpp_computation") .def(py::init<float>()) // args of constructers are template args .def("set_comm", &SomeComputation::set_comm) .def("compute", &SomeComputation::compute) .def("cpp_init", &SomeComputation::Init); } ``` and here's the python interface spawning the same C++: ```py from build.module_name import * import time from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() m = Cpp_computation(44.0) # send communicator to cpp m.cpp_init() i = 0 while i < 5: print(m.compute(i)) time.sleep(1) i+=1 ``` I've already tried "[Sharing an MPI communicator using pybind11](https://stackoverflow.com/q/52657173/4593199)" but I'm stuck at a long unhelpful error ([full message](https://pastebin.com/raw/zfEJGh27)): ```none [...] /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22: required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]' /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7: required from here /opt/homebrew/Cellar/gcc/11.2.0_3/include/c++/11/type_traits:1372:38: error: invalid use of incomplete type 'struct ompi_communicator_t' 1372 | : public integral_constant<bool, __is_base_of(_Base, _Derived)> | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:6: /opt/homebrew/Cellar/open-mpi/4.1.2/include/mpi.h:419:16: note: forward declaration of 'struct ompi_communicator_t' 419 | typedef struct ompi_communicator_t *MPI_Comm; | ^~~~~~~~~~~~~~~~~~~ [...] /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22: required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]' /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7: required from here /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/detail/descr.h:40:19: error: invalid use of incomplete type 'struct ompi_communicator_t' 40 | return {{&typeid(Ts)..., nullptr}}; | ^~~~~~~~~~ In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:6: /opt/homebrew/Cellar/open-mpi/4.1.2/include/mpi.h:419:16: note: forward declaration of 'struct ompi_communicator_t' 419 | typedef struct ompi_communicator_t *MPI_Comm; | ^~~~~~~~~~~~~~~~~~~ [...] from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:1: /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/detail/descr.h:40:42: error: could not convert '{{<expression error>, nullptr}}' from '<brace-enclosed initializer list>' to 'std::array<const std::type_info*, 3>' 40 | return {{&typeid(Ts)..., nullptr}}; | ^ | | | <brace-enclosed initializer list> [...] In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:1: /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h: In instantiation of 'void pybind11::cpp_function::initialize(Func&&, Return (*)(Args ...), const Extra& ...) [with Func = pybind11::cpp_function::cpp_function<void, SomeComputation, ompi_communicator_t*, pybind11::name, pybind11::is_method, pybind11::sibling>(void (SomeComputation::*)(ompi_communicator_t*), const pybind11::name&, const pybind11::is_method&, const pybind11::sibling&)::<lambda(SomeComputation*, ompi_communicator_t*)>; Return = void; Args = {SomeComputation*, ompi_communicator_t*}; Extra = {pybind11::name, pybind11::is_method, pybind11::sibling}]': [..] /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22: required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]' /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7: required from here /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:266:73: in 'constexpr' expansion of 'pybind11::detail::descr<18, SomeComputation, ompi_communicator_t>::types()' /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:266:39: error: 'constexpr' call flows off the end of the function 266 | PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types(); | ^~~~~ ``` The error points to `.def("set_comm", &SomeComputation::set_comm)` What is the cause of these errors, and how should they be resolved? UPDATE: Added answer below by using custom type caster as explained in [this answer](https://stackoverflow.com/questions/49259704/pybind11-possible-to-use-mpi4py). But is it the *only* way to go about it?
2021/12/20
[ "https://Stackoverflow.com/questions/70423477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593199/" ]
I understand that you would like to have an explanation and not just a code dump or some comments. So, let me try to explain you. As you know: Numbers like 12345 in a base 10 numbering system or decimal system are build of a digit and a power of 10. Mathematically you could write 12345 also a `5*10^0 + 4*10^1 + 3*10^2 + 2*10^3 + 1*10^4`. Or, we can write: ``` number = 0; number = number + 1; number = number * 10; number = number + 2; number = number * 10; number = number + 3; number = number * 10; number = number + 4; number = number * 10; number = number + 5; ``` That is nothing new. But it is important to understand, how to get back the digits from a number. Obviously we need to make an integer division by 10 somewhen. But this alone does not give us the digits. If we perform a division o 12345 by 10, then the result is 1234.5. And for the intger devision it os 1234 with a rest of 5. And now, we can see that the rest is the digit that we are looking for. And in C++ we have a function that gives us the rest of an integer division. It is the modulo operator %. Let us look, how this works: ``` int number = 12345; int digit = number % 10; // Result will be 5 // Do something with digit number = number / 10; // Now number is 1234 (Integer division will truncate the fraction) digit = number % 10; // Result is now 4 // Do something with digit number = number / 10; // Now number is 123 (Integer division will truncate the fraction) digit = number % 10; // Result is now 3 // Do something with digit number = number / 10; // Now number is 12 (Integer division will truncate the fraction) digit = number % 10; // Result is now 2 // Do something with digit number = number / 10; // Now number is 1 (Integer division will truncate the fraction) digit = number % 10; // Result is now 1 number = number / 10; // Now number is 0, and we can stop the operation. ``` And later we can do all this in a loop. Like with ``` int number = 12345; while (number > 0) { int digit = number % 10; // Extract next digit from number // Do something with digit number /= 10; } ``` And thats it. Now we extracted all digits. --- Next is counting. We have 10 different digits. So, we could now define 10 counter variables like "int counterFor0, counterFor1, counterFor2 ..... , counterFor9" and the compare the digit with "0,1,2,...9" and then increment the related counter. But that is too much typing work. But, luckily, we have arrays in C++. So we can define an array with 10 counters like: `int counterForDigit[10]`. OK, understood. You remember that we had in the above code a comment "// Do something with digit ". And this we will do now. If we have a digit, then we use that as an index in our array and increment the related counter. So, finally. One possible solution would be: ``` #include <iostream> int main() { // Test number. Can be anything int number = 12344555; // Counter for our digits int counterForDigits[10]{}; // The {} will initialize all values in the array with 0 // Extract all digits while (number > 0) { // Get digit int digit = number % 10; // Increment related counter counterForDigits[digit]++; // Get next number number /= 10; } // Show result for (int k = 0; k < 10; ++k) std::cout << k << " : " << counterForDigits[k] << '\n'; } ``` If you do not want to show 0 outputs, then please add `if (counterForDigits[k] > 0)` after the `for` statement. If you should have further questions, then please ask
I can offer the solution of your problem: ``` #include <iostream> #include <vector> #include <map> #include <set> #include <tuple> using namespace std; void showContentVector(vector<int>& input) { for(int i=0; i<input.size(); ++i) { cout<<input[i]<<", "; } return; } void showContentMap(map<int, int>& input) { for(auto iterator=input.begin(); iterator!=input.end(); ++iterator) { cout<<iterator->first<<" : "<<iterator->second<<endl; } return; } void solve() { int number=1004; vector<int> digits; map<int, int> repetitions; while(number) { digits.push_back(number%10); number/=10; } cout<<"digits <- "; showContentVector(digits); cout<<endl; for(int i=0; i<digits.size(); ++i) { int count=0; for(int j=0; j<digits.size(); ++j) { if(digits[i]==digits[j]) { ++count; } } repetitions.insert(pair<int, int>(digits[i], count)); } cout<<"repetitions <- "<<endl; showContentMap(repetitions); cout<<endl; return; } int main() { solve(); return 0; } ``` Here is the result: ``` digits <- 4, 0, 0, 1, repetitions <- 0 : 2 1 : 1 4 : 1 ```
70,423,477
I have a C++ class which I intend to call from python's mpi4py interface such that each node spawns the class. On the C++ side, I'm using the [Open MPI](https://www.open-mpi.org/) library (installed via [homebrew](https://formulae.brew.sh/formula/open-mpi)) and [pybind11](https://github.com/pybind/pybind11). The C++ class is as follows: ```cpp #include <pybind11/pybind11.h> #include <iostream> #include <chrono> #include <thread> #include <vector> #include <mpi.h> // #define PyMPI_HAVE_MPI_Message 1 // #include <mpi4py/mpi4py.h> namespace py = pybind11; class SomeComputation { float multiplier; std::vector<int> test; MPI_Comm comm_; public: void Init() { int rank; MPI_Comm_rank(comm_, &rank); test.clear(); test.resize(10, rank); } void set_comm(MPI_Comm comm){ this->comm_ = comm; } SomeComputation(float multiplier_) : multiplier(multiplier_){} ~SomeComputation() { std::cout << "Destructor Called!\n"; } float compute(float input) { std::this_thread::sleep_for(std::chrono::milliseconds((int)input * 10)); for (int i = 0; i != 10; ++i) { std::cout << test[i] << " "; } std::cout << std::endl; return multiplier * input; } }; PYBIND11_MODULE(module_name, handle) { py::class_<SomeComputation>(handle, "Cpp_computation") .def(py::init<float>()) // args of constructers are template args .def("set_comm", &SomeComputation::set_comm) .def("compute", &SomeComputation::compute) .def("cpp_init", &SomeComputation::Init); } ``` and here's the python interface spawning the same C++: ```py from build.module_name import * import time from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() m = Cpp_computation(44.0) # send communicator to cpp m.cpp_init() i = 0 while i < 5: print(m.compute(i)) time.sleep(1) i+=1 ``` I've already tried "[Sharing an MPI communicator using pybind11](https://stackoverflow.com/q/52657173/4593199)" but I'm stuck at a long unhelpful error ([full message](https://pastebin.com/raw/zfEJGh27)): ```none [...] /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22: required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]' /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7: required from here /opt/homebrew/Cellar/gcc/11.2.0_3/include/c++/11/type_traits:1372:38: error: invalid use of incomplete type 'struct ompi_communicator_t' 1372 | : public integral_constant<bool, __is_base_of(_Base, _Derived)> | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:6: /opt/homebrew/Cellar/open-mpi/4.1.2/include/mpi.h:419:16: note: forward declaration of 'struct ompi_communicator_t' 419 | typedef struct ompi_communicator_t *MPI_Comm; | ^~~~~~~~~~~~~~~~~~~ [...] /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22: required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]' /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7: required from here /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/detail/descr.h:40:19: error: invalid use of incomplete type 'struct ompi_communicator_t' 40 | return {{&typeid(Ts)..., nullptr}}; | ^~~~~~~~~~ In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:6: /opt/homebrew/Cellar/open-mpi/4.1.2/include/mpi.h:419:16: note: forward declaration of 'struct ompi_communicator_t' 419 | typedef struct ompi_communicator_t *MPI_Comm; | ^~~~~~~~~~~~~~~~~~~ [...] from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:1: /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/detail/descr.h:40:42: error: could not convert '{{<expression error>, nullptr}}' from '<brace-enclosed initializer list>' to 'std::array<const std::type_info*, 3>' 40 | return {{&typeid(Ts)..., nullptr}}; | ^ | | | <brace-enclosed initializer list> [...] In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:1: /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h: In instantiation of 'void pybind11::cpp_function::initialize(Func&&, Return (*)(Args ...), const Extra& ...) [with Func = pybind11::cpp_function::cpp_function<void, SomeComputation, ompi_communicator_t*, pybind11::name, pybind11::is_method, pybind11::sibling>(void (SomeComputation::*)(ompi_communicator_t*), const pybind11::name&, const pybind11::is_method&, const pybind11::sibling&)::<lambda(SomeComputation*, ompi_communicator_t*)>; Return = void; Args = {SomeComputation*, ompi_communicator_t*}; Extra = {pybind11::name, pybind11::is_method, pybind11::sibling}]': [..] /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22: required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]' /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7: required from here /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:266:73: in 'constexpr' expansion of 'pybind11::detail::descr<18, SomeComputation, ompi_communicator_t>::types()' /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:266:39: error: 'constexpr' call flows off the end of the function 266 | PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types(); | ^~~~~ ``` The error points to `.def("set_comm", &SomeComputation::set_comm)` What is the cause of these errors, and how should they be resolved? UPDATE: Added answer below by using custom type caster as explained in [this answer](https://stackoverflow.com/questions/49259704/pybind11-possible-to-use-mpi4py). But is it the *only* way to go about it?
2021/12/20
[ "https://Stackoverflow.com/questions/70423477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593199/" ]
I can offer the solution of your problem: ``` #include <iostream> #include <vector> #include <map> #include <set> #include <tuple> using namespace std; void showContentVector(vector<int>& input) { for(int i=0; i<input.size(); ++i) { cout<<input[i]<<", "; } return; } void showContentMap(map<int, int>& input) { for(auto iterator=input.begin(); iterator!=input.end(); ++iterator) { cout<<iterator->first<<" : "<<iterator->second<<endl; } return; } void solve() { int number=1004; vector<int> digits; map<int, int> repetitions; while(number) { digits.push_back(number%10); number/=10; } cout<<"digits <- "; showContentVector(digits); cout<<endl; for(int i=0; i<digits.size(); ++i) { int count=0; for(int j=0; j<digits.size(); ++j) { if(digits[i]==digits[j]) { ++count; } } repetitions.insert(pair<int, int>(digits[i], count)); } cout<<"repetitions <- "<<endl; showContentMap(repetitions); cout<<endl; return; } int main() { solve(); return 0; } ``` Here is the result: ``` digits <- 4, 0, 0, 1, repetitions <- 0 : 2 1 : 1 4 : 1 ```
A possible solution: * reading your input as a string, * checking if the input is a valid number (contains only digits), * then counting the digits using an array of 10 elements (one for each digit from 0 to 9). A couple of notes on the code below: 1. Why `counts[c - '0']`? Subscript operator, `[]`, will use a `size_t` as a parameter. If you don't want to have an access out of the bounds of the array, you should use an index between `size_t` `0` and `9`. But you are reading characters from a string. If you just use a `char` from `'0'` to `'9'` as an index, the corresponding `size_t` value will be between `48` and `57` (ASCII codes for `'0'` and `'9'` `char` respectively). By subtracting `c - '0'` you'll end up with an index between `size_t` `0` and `9`. More difficult to explain than to understand I guess! 2. Notice also `counts[c - '0']` returns a [reference to the element in the array](https://en.cppreference.com/w/cpp/container/array/operator_at). That's why `counts[c - '0']++` actually modifies the array contents. [[Demo]](https://godbolt.org/z/KrzW6x6od) ```cpp #include <algorithm> // all_of #include <array> #include <iostream> // cout int main() { auto is_digit = [](char c) { return c >= '0' and c <= '9'; }; const std::string n{"122333444455555"}; if (not std::all_of(std::cbegin(n), std::cend(n), is_digit)) { std::cout << "Error: input string is not a valid number.\n"; return 0; } std::array<int, 10> counts{}; for (auto c : n) { counts[c - '0']++; } for (int i{0}; i < counts.size(); ++i) { std::cout << "Number of " << i << "s in input number: " << counts[i] << "\n"; } } ```
70,423,477
I have a C++ class which I intend to call from python's mpi4py interface such that each node spawns the class. On the C++ side, I'm using the [Open MPI](https://www.open-mpi.org/) library (installed via [homebrew](https://formulae.brew.sh/formula/open-mpi)) and [pybind11](https://github.com/pybind/pybind11). The C++ class is as follows: ```cpp #include <pybind11/pybind11.h> #include <iostream> #include <chrono> #include <thread> #include <vector> #include <mpi.h> // #define PyMPI_HAVE_MPI_Message 1 // #include <mpi4py/mpi4py.h> namespace py = pybind11; class SomeComputation { float multiplier; std::vector<int> test; MPI_Comm comm_; public: void Init() { int rank; MPI_Comm_rank(comm_, &rank); test.clear(); test.resize(10, rank); } void set_comm(MPI_Comm comm){ this->comm_ = comm; } SomeComputation(float multiplier_) : multiplier(multiplier_){} ~SomeComputation() { std::cout << "Destructor Called!\n"; } float compute(float input) { std::this_thread::sleep_for(std::chrono::milliseconds((int)input * 10)); for (int i = 0; i != 10; ++i) { std::cout << test[i] << " "; } std::cout << std::endl; return multiplier * input; } }; PYBIND11_MODULE(module_name, handle) { py::class_<SomeComputation>(handle, "Cpp_computation") .def(py::init<float>()) // args of constructers are template args .def("set_comm", &SomeComputation::set_comm) .def("compute", &SomeComputation::compute) .def("cpp_init", &SomeComputation::Init); } ``` and here's the python interface spawning the same C++: ```py from build.module_name import * import time from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() m = Cpp_computation(44.0) # send communicator to cpp m.cpp_init() i = 0 while i < 5: print(m.compute(i)) time.sleep(1) i+=1 ``` I've already tried "[Sharing an MPI communicator using pybind11](https://stackoverflow.com/q/52657173/4593199)" but I'm stuck at a long unhelpful error ([full message](https://pastebin.com/raw/zfEJGh27)): ```none [...] /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22: required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]' /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7: required from here /opt/homebrew/Cellar/gcc/11.2.0_3/include/c++/11/type_traits:1372:38: error: invalid use of incomplete type 'struct ompi_communicator_t' 1372 | : public integral_constant<bool, __is_base_of(_Base, _Derived)> | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:6: /opt/homebrew/Cellar/open-mpi/4.1.2/include/mpi.h:419:16: note: forward declaration of 'struct ompi_communicator_t' 419 | typedef struct ompi_communicator_t *MPI_Comm; | ^~~~~~~~~~~~~~~~~~~ [...] /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22: required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]' /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7: required from here /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/detail/descr.h:40:19: error: invalid use of incomplete type 'struct ompi_communicator_t' 40 | return {{&typeid(Ts)..., nullptr}}; | ^~~~~~~~~~ In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:6: /opt/homebrew/Cellar/open-mpi/4.1.2/include/mpi.h:419:16: note: forward declaration of 'struct ompi_communicator_t' 419 | typedef struct ompi_communicator_t *MPI_Comm; | ^~~~~~~~~~~~~~~~~~~ [...] from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:1: /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/detail/descr.h:40:42: error: could not convert '{{<expression error>, nullptr}}' from '<brace-enclosed initializer list>' to 'std::array<const std::type_info*, 3>' 40 | return {{&typeid(Ts)..., nullptr}}; | ^ | | | <brace-enclosed initializer list> [...] In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:1: /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h: In instantiation of 'void pybind11::cpp_function::initialize(Func&&, Return (*)(Args ...), const Extra& ...) [with Func = pybind11::cpp_function::cpp_function<void, SomeComputation, ompi_communicator_t*, pybind11::name, pybind11::is_method, pybind11::sibling>(void (SomeComputation::*)(ompi_communicator_t*), const pybind11::name&, const pybind11::is_method&, const pybind11::sibling&)::<lambda(SomeComputation*, ompi_communicator_t*)>; Return = void; Args = {SomeComputation*, ompi_communicator_t*}; Extra = {pybind11::name, pybind11::is_method, pybind11::sibling}]': [..] /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22: required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]' /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7: required from here /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:266:73: in 'constexpr' expansion of 'pybind11::detail::descr<18, SomeComputation, ompi_communicator_t>::types()' /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:266:39: error: 'constexpr' call flows off the end of the function 266 | PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types(); | ^~~~~ ``` The error points to `.def("set_comm", &SomeComputation::set_comm)` What is the cause of these errors, and how should they be resolved? UPDATE: Added answer below by using custom type caster as explained in [this answer](https://stackoverflow.com/questions/49259704/pybind11-possible-to-use-mpi4py). But is it the *only* way to go about it?
2021/12/20
[ "https://Stackoverflow.com/questions/70423477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593199/" ]
I can offer the solution of your problem: ``` #include <iostream> #include <vector> #include <map> #include <set> #include <tuple> using namespace std; void showContentVector(vector<int>& input) { for(int i=0; i<input.size(); ++i) { cout<<input[i]<<", "; } return; } void showContentMap(map<int, int>& input) { for(auto iterator=input.begin(); iterator!=input.end(); ++iterator) { cout<<iterator->first<<" : "<<iterator->second<<endl; } return; } void solve() { int number=1004; vector<int> digits; map<int, int> repetitions; while(number) { digits.push_back(number%10); number/=10; } cout<<"digits <- "; showContentVector(digits); cout<<endl; for(int i=0; i<digits.size(); ++i) { int count=0; for(int j=0; j<digits.size(); ++j) { if(digits[i]==digits[j]) { ++count; } } repetitions.insert(pair<int, int>(digits[i], count)); } cout<<"repetitions <- "<<endl; showContentMap(repetitions); cout<<endl; return; } int main() { solve(); return 0; } ``` Here is the result: ``` digits <- 4, 0, 0, 1, repetitions <- 0 : 2 1 : 1 4 : 1 ```
A simple approach: Assuming you want to get the number of digits of the decimal equivalent of the number, you can convert the int to a string, then count the digit characters: ``` #include <string> [...] char digit = '3'; // or any digit int num = 321523; // or any number // convert to decimal string std::string str_num = to_string(num); // count digits int digit_count = 0; for(int i=0; i<str_num.length(); i++) if(str_num[i] == digit) digit_count++; // digit_count should now be equal to 2 ```
70,423,477
I have a C++ class which I intend to call from python's mpi4py interface such that each node spawns the class. On the C++ side, I'm using the [Open MPI](https://www.open-mpi.org/) library (installed via [homebrew](https://formulae.brew.sh/formula/open-mpi)) and [pybind11](https://github.com/pybind/pybind11). The C++ class is as follows: ```cpp #include <pybind11/pybind11.h> #include <iostream> #include <chrono> #include <thread> #include <vector> #include <mpi.h> // #define PyMPI_HAVE_MPI_Message 1 // #include <mpi4py/mpi4py.h> namespace py = pybind11; class SomeComputation { float multiplier; std::vector<int> test; MPI_Comm comm_; public: void Init() { int rank; MPI_Comm_rank(comm_, &rank); test.clear(); test.resize(10, rank); } void set_comm(MPI_Comm comm){ this->comm_ = comm; } SomeComputation(float multiplier_) : multiplier(multiplier_){} ~SomeComputation() { std::cout << "Destructor Called!\n"; } float compute(float input) { std::this_thread::sleep_for(std::chrono::milliseconds((int)input * 10)); for (int i = 0; i != 10; ++i) { std::cout << test[i] << " "; } std::cout << std::endl; return multiplier * input; } }; PYBIND11_MODULE(module_name, handle) { py::class_<SomeComputation>(handle, "Cpp_computation") .def(py::init<float>()) // args of constructers are template args .def("set_comm", &SomeComputation::set_comm) .def("compute", &SomeComputation::compute) .def("cpp_init", &SomeComputation::Init); } ``` and here's the python interface spawning the same C++: ```py from build.module_name import * import time from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() m = Cpp_computation(44.0) # send communicator to cpp m.cpp_init() i = 0 while i < 5: print(m.compute(i)) time.sleep(1) i+=1 ``` I've already tried "[Sharing an MPI communicator using pybind11](https://stackoverflow.com/q/52657173/4593199)" but I'm stuck at a long unhelpful error ([full message](https://pastebin.com/raw/zfEJGh27)): ```none [...] /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22: required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]' /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7: required from here /opt/homebrew/Cellar/gcc/11.2.0_3/include/c++/11/type_traits:1372:38: error: invalid use of incomplete type 'struct ompi_communicator_t' 1372 | : public integral_constant<bool, __is_base_of(_Base, _Derived)> | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:6: /opt/homebrew/Cellar/open-mpi/4.1.2/include/mpi.h:419:16: note: forward declaration of 'struct ompi_communicator_t' 419 | typedef struct ompi_communicator_t *MPI_Comm; | ^~~~~~~~~~~~~~~~~~~ [...] /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22: required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]' /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7: required from here /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/detail/descr.h:40:19: error: invalid use of incomplete type 'struct ompi_communicator_t' 40 | return {{&typeid(Ts)..., nullptr}}; | ^~~~~~~~~~ In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:6: /opt/homebrew/Cellar/open-mpi/4.1.2/include/mpi.h:419:16: note: forward declaration of 'struct ompi_communicator_t' 419 | typedef struct ompi_communicator_t *MPI_Comm; | ^~~~~~~~~~~~~~~~~~~ [...] from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:1: /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/detail/descr.h:40:42: error: could not convert '{{<expression error>, nullptr}}' from '<brace-enclosed initializer list>' to 'std::array<const std::type_info*, 3>' 40 | return {{&typeid(Ts)..., nullptr}}; | ^ | | | <brace-enclosed initializer list> [...] In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:1: /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h: In instantiation of 'void pybind11::cpp_function::initialize(Func&&, Return (*)(Args ...), const Extra& ...) [with Func = pybind11::cpp_function::cpp_function<void, SomeComputation, ompi_communicator_t*, pybind11::name, pybind11::is_method, pybind11::sibling>(void (SomeComputation::*)(ompi_communicator_t*), const pybind11::name&, const pybind11::is_method&, const pybind11::sibling&)::<lambda(SomeComputation*, ompi_communicator_t*)>; Return = void; Args = {SomeComputation*, ompi_communicator_t*}; Extra = {pybind11::name, pybind11::is_method, pybind11::sibling}]': [..] /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22: required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]' /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7: required from here /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:266:73: in 'constexpr' expansion of 'pybind11::detail::descr<18, SomeComputation, ompi_communicator_t>::types()' /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:266:39: error: 'constexpr' call flows off the end of the function 266 | PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types(); | ^~~~~ ``` The error points to `.def("set_comm", &SomeComputation::set_comm)` What is the cause of these errors, and how should they be resolved? UPDATE: Added answer below by using custom type caster as explained in [this answer](https://stackoverflow.com/questions/49259704/pybind11-possible-to-use-mpi4py). But is it the *only* way to go about it?
2021/12/20
[ "https://Stackoverflow.com/questions/70423477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593199/" ]
I understand that you would like to have an explanation and not just a code dump or some comments. So, let me try to explain you. As you know: Numbers like 12345 in a base 10 numbering system or decimal system are build of a digit and a power of 10. Mathematically you could write 12345 also a `5*10^0 + 4*10^1 + 3*10^2 + 2*10^3 + 1*10^4`. Or, we can write: ``` number = 0; number = number + 1; number = number * 10; number = number + 2; number = number * 10; number = number + 3; number = number * 10; number = number + 4; number = number * 10; number = number + 5; ``` That is nothing new. But it is important to understand, how to get back the digits from a number. Obviously we need to make an integer division by 10 somewhen. But this alone does not give us the digits. If we perform a division o 12345 by 10, then the result is 1234.5. And for the intger devision it os 1234 with a rest of 5. And now, we can see that the rest is the digit that we are looking for. And in C++ we have a function that gives us the rest of an integer division. It is the modulo operator %. Let us look, how this works: ``` int number = 12345; int digit = number % 10; // Result will be 5 // Do something with digit number = number / 10; // Now number is 1234 (Integer division will truncate the fraction) digit = number % 10; // Result is now 4 // Do something with digit number = number / 10; // Now number is 123 (Integer division will truncate the fraction) digit = number % 10; // Result is now 3 // Do something with digit number = number / 10; // Now number is 12 (Integer division will truncate the fraction) digit = number % 10; // Result is now 2 // Do something with digit number = number / 10; // Now number is 1 (Integer division will truncate the fraction) digit = number % 10; // Result is now 1 number = number / 10; // Now number is 0, and we can stop the operation. ``` And later we can do all this in a loop. Like with ``` int number = 12345; while (number > 0) { int digit = number % 10; // Extract next digit from number // Do something with digit number /= 10; } ``` And thats it. Now we extracted all digits. --- Next is counting. We have 10 different digits. So, we could now define 10 counter variables like "int counterFor0, counterFor1, counterFor2 ..... , counterFor9" and the compare the digit with "0,1,2,...9" and then increment the related counter. But that is too much typing work. But, luckily, we have arrays in C++. So we can define an array with 10 counters like: `int counterForDigit[10]`. OK, understood. You remember that we had in the above code a comment "// Do something with digit ". And this we will do now. If we have a digit, then we use that as an index in our array and increment the related counter. So, finally. One possible solution would be: ``` #include <iostream> int main() { // Test number. Can be anything int number = 12344555; // Counter for our digits int counterForDigits[10]{}; // The {} will initialize all values in the array with 0 // Extract all digits while (number > 0) { // Get digit int digit = number % 10; // Increment related counter counterForDigits[digit]++; // Get next number number /= 10; } // Show result for (int k = 0; k < 10; ++k) std::cout << k << " : " << counterForDigits[k] << '\n'; } ``` If you do not want to show 0 outputs, then please add `if (counterForDigits[k] > 0)` after the `for` statement. If you should have further questions, then please ask
A possible solution: * reading your input as a string, * checking if the input is a valid number (contains only digits), * then counting the digits using an array of 10 elements (one for each digit from 0 to 9). A couple of notes on the code below: 1. Why `counts[c - '0']`? Subscript operator, `[]`, will use a `size_t` as a parameter. If you don't want to have an access out of the bounds of the array, you should use an index between `size_t` `0` and `9`. But you are reading characters from a string. If you just use a `char` from `'0'` to `'9'` as an index, the corresponding `size_t` value will be between `48` and `57` (ASCII codes for `'0'` and `'9'` `char` respectively). By subtracting `c - '0'` you'll end up with an index between `size_t` `0` and `9`. More difficult to explain than to understand I guess! 2. Notice also `counts[c - '0']` returns a [reference to the element in the array](https://en.cppreference.com/w/cpp/container/array/operator_at). That's why `counts[c - '0']++` actually modifies the array contents. [[Demo]](https://godbolt.org/z/KrzW6x6od) ```cpp #include <algorithm> // all_of #include <array> #include <iostream> // cout int main() { auto is_digit = [](char c) { return c >= '0' and c <= '9'; }; const std::string n{"122333444455555"}; if (not std::all_of(std::cbegin(n), std::cend(n), is_digit)) { std::cout << "Error: input string is not a valid number.\n"; return 0; } std::array<int, 10> counts{}; for (auto c : n) { counts[c - '0']++; } for (int i{0}; i < counts.size(); ++i) { std::cout << "Number of " << i << "s in input number: " << counts[i] << "\n"; } } ```
70,423,477
I have a C++ class which I intend to call from python's mpi4py interface such that each node spawns the class. On the C++ side, I'm using the [Open MPI](https://www.open-mpi.org/) library (installed via [homebrew](https://formulae.brew.sh/formula/open-mpi)) and [pybind11](https://github.com/pybind/pybind11). The C++ class is as follows: ```cpp #include <pybind11/pybind11.h> #include <iostream> #include <chrono> #include <thread> #include <vector> #include <mpi.h> // #define PyMPI_HAVE_MPI_Message 1 // #include <mpi4py/mpi4py.h> namespace py = pybind11; class SomeComputation { float multiplier; std::vector<int> test; MPI_Comm comm_; public: void Init() { int rank; MPI_Comm_rank(comm_, &rank); test.clear(); test.resize(10, rank); } void set_comm(MPI_Comm comm){ this->comm_ = comm; } SomeComputation(float multiplier_) : multiplier(multiplier_){} ~SomeComputation() { std::cout << "Destructor Called!\n"; } float compute(float input) { std::this_thread::sleep_for(std::chrono::milliseconds((int)input * 10)); for (int i = 0; i != 10; ++i) { std::cout << test[i] << " "; } std::cout << std::endl; return multiplier * input; } }; PYBIND11_MODULE(module_name, handle) { py::class_<SomeComputation>(handle, "Cpp_computation") .def(py::init<float>()) // args of constructers are template args .def("set_comm", &SomeComputation::set_comm) .def("compute", &SomeComputation::compute) .def("cpp_init", &SomeComputation::Init); } ``` and here's the python interface spawning the same C++: ```py from build.module_name import * import time from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() m = Cpp_computation(44.0) # send communicator to cpp m.cpp_init() i = 0 while i < 5: print(m.compute(i)) time.sleep(1) i+=1 ``` I've already tried "[Sharing an MPI communicator using pybind11](https://stackoverflow.com/q/52657173/4593199)" but I'm stuck at a long unhelpful error ([full message](https://pastebin.com/raw/zfEJGh27)): ```none [...] /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22: required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]' /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7: required from here /opt/homebrew/Cellar/gcc/11.2.0_3/include/c++/11/type_traits:1372:38: error: invalid use of incomplete type 'struct ompi_communicator_t' 1372 | : public integral_constant<bool, __is_base_of(_Base, _Derived)> | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:6: /opt/homebrew/Cellar/open-mpi/4.1.2/include/mpi.h:419:16: note: forward declaration of 'struct ompi_communicator_t' 419 | typedef struct ompi_communicator_t *MPI_Comm; | ^~~~~~~~~~~~~~~~~~~ [...] /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22: required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]' /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7: required from here /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/detail/descr.h:40:19: error: invalid use of incomplete type 'struct ompi_communicator_t' 40 | return {{&typeid(Ts)..., nullptr}}; | ^~~~~~~~~~ In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:6: /opt/homebrew/Cellar/open-mpi/4.1.2/include/mpi.h:419:16: note: forward declaration of 'struct ompi_communicator_t' 419 | typedef struct ompi_communicator_t *MPI_Comm; | ^~~~~~~~~~~~~~~~~~~ [...] from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:1: /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/detail/descr.h:40:42: error: could not convert '{{<expression error>, nullptr}}' from '<brace-enclosed initializer list>' to 'std::array<const std::type_info*, 3>' 40 | return {{&typeid(Ts)..., nullptr}}; | ^ | | | <brace-enclosed initializer list> [...] In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:1: /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h: In instantiation of 'void pybind11::cpp_function::initialize(Func&&, Return (*)(Args ...), const Extra& ...) [with Func = pybind11::cpp_function::cpp_function<void, SomeComputation, ompi_communicator_t*, pybind11::name, pybind11::is_method, pybind11::sibling>(void (SomeComputation::*)(ompi_communicator_t*), const pybind11::name&, const pybind11::is_method&, const pybind11::sibling&)::<lambda(SomeComputation*, ompi_communicator_t*)>; Return = void; Args = {SomeComputation*, ompi_communicator_t*}; Extra = {pybind11::name, pybind11::is_method, pybind11::sibling}]': [..] /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22: required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]' /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7: required from here /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:266:73: in 'constexpr' expansion of 'pybind11::detail::descr<18, SomeComputation, ompi_communicator_t>::types()' /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:266:39: error: 'constexpr' call flows off the end of the function 266 | PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types(); | ^~~~~ ``` The error points to `.def("set_comm", &SomeComputation::set_comm)` What is the cause of these errors, and how should they be resolved? UPDATE: Added answer below by using custom type caster as explained in [this answer](https://stackoverflow.com/questions/49259704/pybind11-possible-to-use-mpi4py). But is it the *only* way to go about it?
2021/12/20
[ "https://Stackoverflow.com/questions/70423477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593199/" ]
I understand that you would like to have an explanation and not just a code dump or some comments. So, let me try to explain you. As you know: Numbers like 12345 in a base 10 numbering system or decimal system are build of a digit and a power of 10. Mathematically you could write 12345 also a `5*10^0 + 4*10^1 + 3*10^2 + 2*10^3 + 1*10^4`. Or, we can write: ``` number = 0; number = number + 1; number = number * 10; number = number + 2; number = number * 10; number = number + 3; number = number * 10; number = number + 4; number = number * 10; number = number + 5; ``` That is nothing new. But it is important to understand, how to get back the digits from a number. Obviously we need to make an integer division by 10 somewhen. But this alone does not give us the digits. If we perform a division o 12345 by 10, then the result is 1234.5. And for the intger devision it os 1234 with a rest of 5. And now, we can see that the rest is the digit that we are looking for. And in C++ we have a function that gives us the rest of an integer division. It is the modulo operator %. Let us look, how this works: ``` int number = 12345; int digit = number % 10; // Result will be 5 // Do something with digit number = number / 10; // Now number is 1234 (Integer division will truncate the fraction) digit = number % 10; // Result is now 4 // Do something with digit number = number / 10; // Now number is 123 (Integer division will truncate the fraction) digit = number % 10; // Result is now 3 // Do something with digit number = number / 10; // Now number is 12 (Integer division will truncate the fraction) digit = number % 10; // Result is now 2 // Do something with digit number = number / 10; // Now number is 1 (Integer division will truncate the fraction) digit = number % 10; // Result is now 1 number = number / 10; // Now number is 0, and we can stop the operation. ``` And later we can do all this in a loop. Like with ``` int number = 12345; while (number > 0) { int digit = number % 10; // Extract next digit from number // Do something with digit number /= 10; } ``` And thats it. Now we extracted all digits. --- Next is counting. We have 10 different digits. So, we could now define 10 counter variables like "int counterFor0, counterFor1, counterFor2 ..... , counterFor9" and the compare the digit with "0,1,2,...9" and then increment the related counter. But that is too much typing work. But, luckily, we have arrays in C++. So we can define an array with 10 counters like: `int counterForDigit[10]`. OK, understood. You remember that we had in the above code a comment "// Do something with digit ". And this we will do now. If we have a digit, then we use that as an index in our array and increment the related counter. So, finally. One possible solution would be: ``` #include <iostream> int main() { // Test number. Can be anything int number = 12344555; // Counter for our digits int counterForDigits[10]{}; // The {} will initialize all values in the array with 0 // Extract all digits while (number > 0) { // Get digit int digit = number % 10; // Increment related counter counterForDigits[digit]++; // Get next number number /= 10; } // Show result for (int k = 0; k < 10; ++k) std::cout << k << " : " << counterForDigits[k] << '\n'; } ``` If you do not want to show 0 outputs, then please add `if (counterForDigits[k] > 0)` after the `for` statement. If you should have further questions, then please ask
A simple approach: Assuming you want to get the number of digits of the decimal equivalent of the number, you can convert the int to a string, then count the digit characters: ``` #include <string> [...] char digit = '3'; // or any digit int num = 321523; // or any number // convert to decimal string std::string str_num = to_string(num); // count digits int digit_count = 0; for(int i=0; i<str_num.length(); i++) if(str_num[i] == digit) digit_count++; // digit_count should now be equal to 2 ```
191,621
I want to retrieve a record from SharePoint list by passing field value to CAML query using javascript,I tried below code ``` function retrieveDetails(name) { var ctx = new SP.ClientContext(appWebUrl);//Get the SharePoint Context object based upon the URL var myList = ctx.get_web().get_lists().getByTitle("PersonalDetails"); var query = new SP.CamlQuery(); query.set_viewXml('<View><Query><Where><eq><FieldRef Name=\'Name\'/><Value Type=\'Text\'>' + name + '</Value><FieldRef Name=\'email\'/><Value Type=\'Text\'></Value></eq>" + "</Where></Query><RowLimit>100</RowLimit></View>'); var items = myList.getItems(query); ctx.load(items); ctx.executeQueryAsync(onQuerySucceeded, onQueryFailed); function onQuerySucceeded() { Roomdetailstable(items); } function onQueryFailed(sender, args) { alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace()); } } function details(items) { var itemInfo = ''; var enumerator = items.getEnumerator(); while (enumerator.moveNext()) { var currentListItem = enumerator.get_current(); var rnmae = currentListItem.get_item('Name'); document.getElementById("rnme").innerHTML = rnmae ; var emailid= currentListItem.get_item('email'); document.getElementById("emailid").innerHTML = emailid; } } ``` but it is showing error like below [![enter image description here](https://i.stack.imgur.com/9ruAA.png)](https://i.stack.imgur.com/9ruAA.png)
2016/08/24
[ "https://sharepoint.stackexchange.com/questions/191621", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/52922/" ]
resolved this issue by removing `<Query></Query>` from my caml query ``` function retrieveDetails(name) { var ctx = new SP.ClientContext(appWebUrl);//Get the SharePoint Context object based upon the URL var myList = ctx.get_web().get_lists().getByTitle("PersonalDetails"); var query = new SP.CamlQuery(); query.set_viewXml('<View><Where><eq><FieldRef Name=\'Name\'/><Value Type=\'Text\'>' + name + '</Value><FieldRef Name=\'email\'/><Value Type=\'Text\'></Value></eq>" + "</Where><RowLimit>100</RowLimit></View>'); var items = myList.getItems(query); ctx.load(items); ctx.executeQueryAsync(onQuerySucceeded, onQueryFailed); function onQuerySucceeded() { Roomdetailstable(items); } function onQueryFailed(sender, args) { alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace()); } } function details(items) { var itemInfo = ''; var enumerator = items.getEnumerator(); while (enumerator.moveNext()) { var currentListItem = enumerator.get_current(); var rnmae = currentListItem.get_item('Name'); document.getElementById("rnme").innerHTML = rnmae ; var emailid= currentListItem.get_item('email'); document.getElementById("emailid").innerHTML = emailid; } } ```
Your caml query is wrong. If you want to be sure it's not the code, please try this caml query: ``` query.set_viewXml('<View><Query><Where><IsNotNull><FieldRef Name=\'ID\' /></IsNotNull></Where></Query><RowLimit>100</RowLimit></View>'); ```
191,621
I want to retrieve a record from SharePoint list by passing field value to CAML query using javascript,I tried below code ``` function retrieveDetails(name) { var ctx = new SP.ClientContext(appWebUrl);//Get the SharePoint Context object based upon the URL var myList = ctx.get_web().get_lists().getByTitle("PersonalDetails"); var query = new SP.CamlQuery(); query.set_viewXml('<View><Query><Where><eq><FieldRef Name=\'Name\'/><Value Type=\'Text\'>' + name + '</Value><FieldRef Name=\'email\'/><Value Type=\'Text\'></Value></eq>" + "</Where></Query><RowLimit>100</RowLimit></View>'); var items = myList.getItems(query); ctx.load(items); ctx.executeQueryAsync(onQuerySucceeded, onQueryFailed); function onQuerySucceeded() { Roomdetailstable(items); } function onQueryFailed(sender, args) { alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace()); } } function details(items) { var itemInfo = ''; var enumerator = items.getEnumerator(); while (enumerator.moveNext()) { var currentListItem = enumerator.get_current(); var rnmae = currentListItem.get_item('Name'); document.getElementById("rnme").innerHTML = rnmae ; var emailid= currentListItem.get_item('email'); document.getElementById("emailid").innerHTML = emailid; } } ``` but it is showing error like below [![enter image description here](https://i.stack.imgur.com/9ruAA.png)](https://i.stack.imgur.com/9ruAA.png)
2016/08/24
[ "https://sharepoint.stackexchange.com/questions/191621", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/52922/" ]
resolved this issue by removing `<Query></Query>` from my caml query ``` function retrieveDetails(name) { var ctx = new SP.ClientContext(appWebUrl);//Get the SharePoint Context object based upon the URL var myList = ctx.get_web().get_lists().getByTitle("PersonalDetails"); var query = new SP.CamlQuery(); query.set_viewXml('<View><Where><eq><FieldRef Name=\'Name\'/><Value Type=\'Text\'>' + name + '</Value><FieldRef Name=\'email\'/><Value Type=\'Text\'></Value></eq>" + "</Where><RowLimit>100</RowLimit></View>'); var items = myList.getItems(query); ctx.load(items); ctx.executeQueryAsync(onQuerySucceeded, onQueryFailed); function onQuerySucceeded() { Roomdetailstable(items); } function onQueryFailed(sender, args) { alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace()); } } function details(items) { var itemInfo = ''; var enumerator = items.getEnumerator(); while (enumerator.moveNext()) { var currentListItem = enumerator.get_current(); var rnmae = currentListItem.get_item('Name'); document.getElementById("rnme").innerHTML = rnmae ; var emailid= currentListItem.get_item('email'); document.getElementById("emailid").innerHTML = emailid; } } ```
Try below code to get the data from SharePoint list using CAML query. ``` function retrieveDetails(name) { var ctx = new SP.ClientContext(appWebUrl);//Get the SharePoint Context object based upon the URL var myList = ctx.get_web().get_lists().getByTitle("PersonalDetails"); var query = new SP.CamlQuery(); query.set_viewXml('<View><Query><Where><eq><FieldRef Name=\'Name\'/><Value Type=\'Text\'>' + name + '</Value><FieldRef Name=\'email\'/><Value Type=\'Text\'></Value></eq>" + "</Where></Query><RowLimit>100</RowLimit></View>'); var items = myList.getItems(query); ctx.load(items); ctx.executeQueryAsync( Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed) ); } function onQuerySucceeded() { var itemInfo = ''; var enumerator = items.getEnumerator(); while (enumerator.moveNext()) { var currentListItem = enumerator.get_current(); var rnmae = currentListItem.get_item('Name'); document.getElementById("rnme").innerHTML = rnmae ; var emailid= currentListItem.get_item('email'); document.getElementById("emailid").innerHTML = emailid; } function onQueryFailed(sender, args) { alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace()); } ```
21,394,573
I would like to get the value for of a hiddenfield if a checkbox is checked on my gridview my gridview: ``` <asp:GridView ID="gv_enfant" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" DataSourceID="SqlDataSource1" Width="533px"> <Columns> <asp:TemplateField HeaderText="Select"> <ItemTemplate> <asp:CheckBox ID="CheckBoxenfant" runat="server" /> <asp:HiddenField ID="codeenfant" runat="server" Value='<%# Eval("codeEnfants") %>' /> </ItemTemplate> .............. </asp:GridView> ``` and here is how I loop trhough the rows and check: ``` string myid = string.Empty; for (int i = 0; i < gv_enfant.Rows.Count; i++) { CheckBox chbox = (CheckBox)gv_enfant.Rows[i].Cells[0].FindControl("CheckBoxenfant"); if (chbox.Checked) { myid = ((HiddenField)gv_enfant.Rows[i].Cells[0].FindControl("codeenfant")).Value; } } ``` I put a breakpoint on the condition, debugger never hit that line
2014/01/28
[ "https://Stackoverflow.com/questions/21394573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Late answer, but if it still helps (or for anyone else) you should be able to do the following with SQL 2008. ``` DECLARE @point GEOMETRY = GEOMETRY::STPointFromText('POINT(0 0)', 0); DECLARE @line GEOMETRY = GEOMETRY::STLineFromText('POINT(10 10, 20 20)', 0); SELECT STIntersection(@point.STBuffer(@point.STDistance(@line))); ``` Essentially, you calculate the distance between the two geometries,use that as a buffer on the point which should result in the geometries touching, and take the intersection (point) of that.
**Note @Road is the same as geography MULTILINESTRING** **SET INITIAL ROAD SEGMENT** *SET @Road* = geography::STMLineFromText('MULTILINESTRING ((-79.907603999999992 32.851905999999985, -79.907708999999983 32.851751, -79.907879999999992 32.851555999999995, -79.907889999999981 32.851542999999992, -79.907995999999983 32.851461, -79.90813399999999 32.851373999999986, -79.90833499999998 32.851286999999992, -79.908529 32.85121, -79.909110999999982 32.850974))', 4269); **GET START/END POINTS OF ROAD SEGMENT FOR NEW MIDPOINT CALCULATION** *SET @x1* = CAST(@Road.STStartPoint().Lat AS decimal(11,6)) *SET @y1* = CAST(@Road.STStartPoint().Long AS decimal(12,6)) *SET @x2* = CAST(@Road.STEndPoint().Lat AS decimal(11,6)) *SET @y2* = CAST(@Road.STEndPoint().Long AS decimal(12,6)) **ASSIGN ROAD SEGMENT MIDPOINT LAT/LON** *SET @MidPointLat* = CAST( ((@x1 + @x2) / 2) AS nvarchar(11)) *SET @MidPointLon* = CAST( ((@y1 + @y2) / 2) AS nvarchar(12)) **SET INITIAL OFF ROAD CENTROID** *SET @RoadMidPt* = geography::STPointFromText('POINT(' + @MidPointLon + ' ' + @MidPointLat + ')', 4269) **CALCULATE BUFFER DISTANCE BACK TO ROAD FOR .STIntersection** (add .02 to ensure intersect) *SET @RoadMidPtBuffer* = @RoadMidPt.STBuffer(@RoadMidPt.STDistance(@Road) + .02) **Might intersect at multiple points! Use 1st point that intersects road as centroid** *SET @RoadCentroid* = @RoadMidPtBuffer.STIntersection(@Road).STPointN(1); **FINAL NEW LAT/LON OF CLOSEST ROAD/LINE CENTROID** SELECT @RoadCentroid.Lat, @RoadCentroid.Long
48,395,984
I have the following vuejs component. I know that it is a pretty simple example, but still it does not load correctly. Find below my code: ```js Vue.component('my-component', { template: '<div>{{ msg }}</div>', data: { msg: 'hello' } }); new Vue({ el: '#app-6' }); ``` ```html <!DOCTYPE html> <html lang="en"> <meta> <meta charset="UTF-8"> <title>Components in Vue.js</title> </meta> <body> <div id="app-6"> test <my-component></my-component> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.min.js"></script> </body> </html> ``` Any suggestions what I am doing wrong? I appreciate your replies!
2018/01/23
[ "https://Stackoverflow.com/questions/48395984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2847689/" ]
Data Must be a function always ```js var data={msg: 'hello'} Vue.component('my-component', { template: '<div>{{ msg }}</div>', data:function() { return data; } }); new Vue({ el: '#app-6' }); ``` ```html <!DOCTYPE html> <html lang="en"> <meta> <meta charset="UTF-8"> <title>Components in Vue.js</title> </meta> <body> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.min.js"></script> <div id="app-6"> test <my-component></my-component> </div> </body> </html> ```
Your data should be a function like this: ``` data () { return { msg: 'Hello' } } ``` More information here: <https://v2.vuejs.org/v2/guide/components.html#data-Must-Be-a-Function>
48,395,984
I have the following vuejs component. I know that it is a pretty simple example, but still it does not load correctly. Find below my code: ```js Vue.component('my-component', { template: '<div>{{ msg }}</div>', data: { msg: 'hello' } }); new Vue({ el: '#app-6' }); ``` ```html <!DOCTYPE html> <html lang="en"> <meta> <meta charset="UTF-8"> <title>Components in Vue.js</title> </meta> <body> <div id="app-6"> test <my-component></my-component> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.min.js"></script> </body> </html> ``` Any suggestions what I am doing wrong? I appreciate your replies!
2018/01/23
[ "https://Stackoverflow.com/questions/48395984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2847689/" ]
Your data should be a function like this: ``` data () { return { msg: 'Hello' } } ``` More information here: <https://v2.vuejs.org/v2/guide/components.html#data-Must-Be-a-Function>
you should do it like this. ``` Vue.component('my-component', { template: '<div>{{ msg }}</div>', data: function () { return { msg: 'Hello' } } }); ```
48,395,984
I have the following vuejs component. I know that it is a pretty simple example, but still it does not load correctly. Find below my code: ```js Vue.component('my-component', { template: '<div>{{ msg }}</div>', data: { msg: 'hello' } }); new Vue({ el: '#app-6' }); ``` ```html <!DOCTYPE html> <html lang="en"> <meta> <meta charset="UTF-8"> <title>Components in Vue.js</title> </meta> <body> <div id="app-6"> test <my-component></my-component> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.min.js"></script> </body> </html> ``` Any suggestions what I am doing wrong? I appreciate your replies!
2018/01/23
[ "https://Stackoverflow.com/questions/48395984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2847689/" ]
Data Must be a function always ```js var data={msg: 'hello'} Vue.component('my-component', { template: '<div>{{ msg }}</div>', data:function() { return data; } }); new Vue({ el: '#app-6' }); ``` ```html <!DOCTYPE html> <html lang="en"> <meta> <meta charset="UTF-8"> <title>Components in Vue.js</title> </meta> <body> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.min.js"></script> <div id="app-6"> test <my-component></my-component> </div> </body> </html> ```
you should do it like this. ``` Vue.component('my-component', { template: '<div>{{ msg }}</div>', data: function () { return { msg: 'Hello' } } }); ```
51,195,379
Strange issue... This is using VisualStudio Community 2017 and is a C++CLI WinForms project. **BGStatsInterface.cpp** ``` #include "BGStatsInterface.h" using namespace System; using namespace System::Windows::Forms; [STAThreadAttribute] void Main(array<String^>^ args) { Application::EnableVisualStyles(); Application::SetCompatibleTextRenderingDefault(false); BattlegroundStats::BGStatsInterface form; Application::Run(%form); } ``` **BGStatsInterface.h** ``` #pragma once #include <windows.h> #include "LuaReader.h" namespace BattlegroundStats { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; using namespace System::IO; public ref class BGStatsInterface : public System::Windows::Forms::Form { public: BGStatsInterface(void) { InitializeComponent(); this->MinimizeBox = false; this->MaximizeBox = false; } static System::Windows::Forms::TextBox^ textBoxLog; static System::Void addMsg(String^ text) { textBoxLog->AppendText(text + "\n"); } protected: ~BGStatsInterface() { if (components) { delete components; } } private: LuaReader ^ reader = gcnew LuaReader(); private: System::Windows::Forms::Button^ b1; private: System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code void InitializeComponent(void) { this->textBoxLog = (gcnew System::Windows::Forms::TextBox()); this->b1 = (gcnew System::Windows::Forms::Button()); this->SuspendLayout(); // // textBoxLog // this->textBoxLog->BackColor = System::Drawing::SystemColors::ControlLightLight; this->textBoxLog->Cursor = System::Windows::Forms::Cursors::IBeam; this->textBoxLog->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 6.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->textBoxLog->Location = System::Drawing::Point(10, 80); this->textBoxLog->Multiline = true; this->textBoxLog->Name = L"textBoxLog"; this->textBoxLog->ReadOnly = true; this->textBoxLog->ScrollBars = System::Windows::Forms::ScrollBars::Vertical; this->textBoxLog->Size = System::Drawing::Size(280, 90); this->textBoxLog->TabIndex = 6; this->textBoxLog->TabStop = false; this->textBoxLog->GotFocus += gcnew System::EventHandler(this, &BGStatsInterface::textBoxLog_HideCaret); // // b1 // this->b1->Location = System::Drawing::Point(100, 30); this->b1->Name = L"b1"; this->b1->Size = System::Drawing::Size(75, 23); this->b1->TabIndex = 7; this->b1->Text = L"DoSomething"; this->b1->UseVisualStyleBackColor = true; this->b1->Click += gcnew System::EventHandler(this, &BGStatsInterface::b1_Click); // // BGStatsInterface // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(301, 411); this->Controls->Add(this->b1); this->Controls->Add(this->textBoxLog); this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::FixedSingle; this->MaximumSize = System::Drawing::Size(317, 450); this->MinimumSize = System::Drawing::Size(317, 450); this->Name = L"BGStatsInterface"; this->Text = L"Test"; this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion System::Void textBoxLog_HideCaret(System::Object^ sender, System::EventArgs^ e) { TextBox^ focus = safe_cast<TextBox^>(sender); HideCaret((HWND)focus->Handle.ToPointer()); } System::Void b1_Click(System::Object^ sender, System::EventArgs^ e) { reader->DoSomething(); addMsg("DoingSomethingA"); System::Diagnostics::Debug::WriteLine("DoingSomethingA"); } }; } ``` **LuaReader.cpp** ``` #include "LuaReader.h" #include "BGStatsInterface.h" // PointA- This is where I'm having the issue. using namespace System; LuaReader::LuaReader(){} System::Void LuaReader::DoSomething() { BattlegroundStats::BGStatsInterface::addMsg("DoingSomethingB"); System::Diagnostics::Debug::WriteLine("DoingSomethingB"); } ``` **LuaReader.h** ``` #pragma once #include "GameCollection.h" // PointB - Another issue here. ref class LuaReader { public: LuaReader(); GameCollection^ gameData = gcnew GameCollection(); System::String^ _fileName; System::Void DoSomething(); }; #endif ``` **GameCollection.cpp** ``` #include "GameCollection.h" GameCollection::GameCollection(){} ``` **GameCollection.h** ``` #pragma once using namespace System; ref class GameCollection { public: GameCollection(); }; ``` **The Problem:** In LuaReader.cpp If I include BGStatsInterface.h (needed so it can access the addMsg method), noted by PointA, it wont compile and will generate the errors listed below. However, if I remove the GameCollection.h include from LuaReader.h (needed so I can create the GameCollection object), noted at PointB, it has no issues with BGStatsInterface.h included in the LuaReader.cpp file and everything compiles/runs without issues. I don't know what to do... Why does it only work if I don't create the GameCollection object in LuaReader.h? What have I done wrong? **Errors:** ``` Severity Code Description Project File Line Suppression State Error (active) E1986 an ordinary pointer to a C++/CLI ref class or interface class is not allowed BattlegroundStats c:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um\servprov.h 91 Error (active) E0266 "IServiceProvider" is ambiguous BattlegroundStats c:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um\servprov.h 115 Error (active) E0266 "IServiceProvider" is ambiguous BattlegroundStats c:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um\servprov.h 239 Error (active) E0266 "IServiceProvider" is ambiguous BattlegroundStats c:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um\servprov.h 249 Error (active) E0266 "IServiceProvider" is ambiguous BattlegroundStats c:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um\urlmon.h 6867 Error (active) E0266 "IServiceProvider" is ambiguous BattlegroundStats c:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um\urlmon.h 6869 Error C3699 '*': cannot use this indirection on type 'IServiceProvider' BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\servprov.h 91 Error C2371 'IServiceProvider': redefinition; different basic types BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\servprov.h 98 Error C2872 'IServiceProvider': ambiguous symbol BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\servprov.h 115 Error C2872 'IServiceProvider': ambiguous symbol BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\servprov.h 239 Error C2872 'IServiceProvider': ambiguous symbol BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\servprov.h 249 Error C2872 'IServiceProvider': ambiguous symbol BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\urlmon.h 6867 Error C2872 'IServiceProvider': ambiguous symbol BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\urlmon.h 6869 ```
2018/07/05
[ "https://Stackoverflow.com/questions/51195379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7194063/" ]
This happens when using #include Windows.h as it defines ::IServiceProvider while the framework has System::IServiceProvider, then when there's a using namespace System in scope somewhere it becomes ambiguous. Solution is to simply put the delcarations in your own namespace.
Just providing another solution in here if your project is small - remove: ``` using namespace System; ``` and use full type name in the code for System's class, e.g. `System::String^`.
51,195,379
Strange issue... This is using VisualStudio Community 2017 and is a C++CLI WinForms project. **BGStatsInterface.cpp** ``` #include "BGStatsInterface.h" using namespace System; using namespace System::Windows::Forms; [STAThreadAttribute] void Main(array<String^>^ args) { Application::EnableVisualStyles(); Application::SetCompatibleTextRenderingDefault(false); BattlegroundStats::BGStatsInterface form; Application::Run(%form); } ``` **BGStatsInterface.h** ``` #pragma once #include <windows.h> #include "LuaReader.h" namespace BattlegroundStats { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; using namespace System::IO; public ref class BGStatsInterface : public System::Windows::Forms::Form { public: BGStatsInterface(void) { InitializeComponent(); this->MinimizeBox = false; this->MaximizeBox = false; } static System::Windows::Forms::TextBox^ textBoxLog; static System::Void addMsg(String^ text) { textBoxLog->AppendText(text + "\n"); } protected: ~BGStatsInterface() { if (components) { delete components; } } private: LuaReader ^ reader = gcnew LuaReader(); private: System::Windows::Forms::Button^ b1; private: System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code void InitializeComponent(void) { this->textBoxLog = (gcnew System::Windows::Forms::TextBox()); this->b1 = (gcnew System::Windows::Forms::Button()); this->SuspendLayout(); // // textBoxLog // this->textBoxLog->BackColor = System::Drawing::SystemColors::ControlLightLight; this->textBoxLog->Cursor = System::Windows::Forms::Cursors::IBeam; this->textBoxLog->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 6.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->textBoxLog->Location = System::Drawing::Point(10, 80); this->textBoxLog->Multiline = true; this->textBoxLog->Name = L"textBoxLog"; this->textBoxLog->ReadOnly = true; this->textBoxLog->ScrollBars = System::Windows::Forms::ScrollBars::Vertical; this->textBoxLog->Size = System::Drawing::Size(280, 90); this->textBoxLog->TabIndex = 6; this->textBoxLog->TabStop = false; this->textBoxLog->GotFocus += gcnew System::EventHandler(this, &BGStatsInterface::textBoxLog_HideCaret); // // b1 // this->b1->Location = System::Drawing::Point(100, 30); this->b1->Name = L"b1"; this->b1->Size = System::Drawing::Size(75, 23); this->b1->TabIndex = 7; this->b1->Text = L"DoSomething"; this->b1->UseVisualStyleBackColor = true; this->b1->Click += gcnew System::EventHandler(this, &BGStatsInterface::b1_Click); // // BGStatsInterface // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(301, 411); this->Controls->Add(this->b1); this->Controls->Add(this->textBoxLog); this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::FixedSingle; this->MaximumSize = System::Drawing::Size(317, 450); this->MinimumSize = System::Drawing::Size(317, 450); this->Name = L"BGStatsInterface"; this->Text = L"Test"; this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion System::Void textBoxLog_HideCaret(System::Object^ sender, System::EventArgs^ e) { TextBox^ focus = safe_cast<TextBox^>(sender); HideCaret((HWND)focus->Handle.ToPointer()); } System::Void b1_Click(System::Object^ sender, System::EventArgs^ e) { reader->DoSomething(); addMsg("DoingSomethingA"); System::Diagnostics::Debug::WriteLine("DoingSomethingA"); } }; } ``` **LuaReader.cpp** ``` #include "LuaReader.h" #include "BGStatsInterface.h" // PointA- This is where I'm having the issue. using namespace System; LuaReader::LuaReader(){} System::Void LuaReader::DoSomething() { BattlegroundStats::BGStatsInterface::addMsg("DoingSomethingB"); System::Diagnostics::Debug::WriteLine("DoingSomethingB"); } ``` **LuaReader.h** ``` #pragma once #include "GameCollection.h" // PointB - Another issue here. ref class LuaReader { public: LuaReader(); GameCollection^ gameData = gcnew GameCollection(); System::String^ _fileName; System::Void DoSomething(); }; #endif ``` **GameCollection.cpp** ``` #include "GameCollection.h" GameCollection::GameCollection(){} ``` **GameCollection.h** ``` #pragma once using namespace System; ref class GameCollection { public: GameCollection(); }; ``` **The Problem:** In LuaReader.cpp If I include BGStatsInterface.h (needed so it can access the addMsg method), noted by PointA, it wont compile and will generate the errors listed below. However, if I remove the GameCollection.h include from LuaReader.h (needed so I can create the GameCollection object), noted at PointB, it has no issues with BGStatsInterface.h included in the LuaReader.cpp file and everything compiles/runs without issues. I don't know what to do... Why does it only work if I don't create the GameCollection object in LuaReader.h? What have I done wrong? **Errors:** ``` Severity Code Description Project File Line Suppression State Error (active) E1986 an ordinary pointer to a C++/CLI ref class or interface class is not allowed BattlegroundStats c:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um\servprov.h 91 Error (active) E0266 "IServiceProvider" is ambiguous BattlegroundStats c:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um\servprov.h 115 Error (active) E0266 "IServiceProvider" is ambiguous BattlegroundStats c:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um\servprov.h 239 Error (active) E0266 "IServiceProvider" is ambiguous BattlegroundStats c:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um\servprov.h 249 Error (active) E0266 "IServiceProvider" is ambiguous BattlegroundStats c:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um\urlmon.h 6867 Error (active) E0266 "IServiceProvider" is ambiguous BattlegroundStats c:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um\urlmon.h 6869 Error C3699 '*': cannot use this indirection on type 'IServiceProvider' BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\servprov.h 91 Error C2371 'IServiceProvider': redefinition; different basic types BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\servprov.h 98 Error C2872 'IServiceProvider': ambiguous symbol BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\servprov.h 115 Error C2872 'IServiceProvider': ambiguous symbol BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\servprov.h 239 Error C2872 'IServiceProvider': ambiguous symbol BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\servprov.h 249 Error C2872 'IServiceProvider': ambiguous symbol BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\urlmon.h 6867 Error C2872 'IServiceProvider': ambiguous symbol BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\urlmon.h 6869 ```
2018/07/05
[ "https://Stackoverflow.com/questions/51195379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7194063/" ]
This happens when using #include Windows.h as it defines ::IServiceProvider while the framework has System::IServiceProvider, then when there's a using namespace System in scope somewhere it becomes ambiguous. Solution is to simply put the delcarations in your own namespace.
To fix this, put your include file (that has windows.h in it) before declaring your namespaces and/or using statements: So: ``` #include "stdafx.h" using namespace System; ``` instead of ``` using namespace System; #include "stdafx.h" ``` Hat tip to <http://www.windows-tech.info/17/fbe07cd4dfcac878.php>
32,356,907
I have basic order form (4 inputs only for testing purposes), i want to count number of inputs (total items) where value is filled in and higher then 0 (basicaly how many products has been ordered, no to confuse with their quantities). When i add products is fine, problems start when I remove items( set them to 0). Could you help me to work it out. Working jsfiddle: <http://jsfiddle.net/nitadesign/97tnrepg/33/> And few lines to bring your attention into a right place: ``` function GetOrder(curId){ var order = null; for(i = 0; i< orders.length; i++){ if(orders[i].id == curId){ order = orders[i]; break; } } return order; } function CalculateTotal(){ var total = 0; for(i = 0; i< orders.length; i++){ total = total + orders[i].packTotal; } console.log(total); if(total > 0){ $("#order_total").html('Total Items:' + i + '<br>' + 'Order Subtotal: ' + total); $("#order_total").show(); $('.submitorder').show(); } if(total == 0){ $("#order_total").html('Your shopping basket is empty'); $("#order_total").show(); $('.submitorder').hide(); } } ``` Thanks a lot for your help in advance!
2015/09/02
[ "https://Stackoverflow.com/questions/32356907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1826668/" ]
Just use a jquery selector and loop through it. ``` $("input").change(function(){ var counter = 0; $("input").each(function(){ if($(this).val() != "" && $(this).val() != 0) counter++; }); $("#order_total").html('Total Items:' + counter + '<br>' + 'Order Subtotal: ' + total); }); ```
``` if(total > 0){ var counter = 0; $("input[type=text]").each(function(){ if($(this).val() != "" && $(this).val() != 0) counter++; }); $("#order_total").html('Total Items:' + counter + '<br>' + 'Order Subtotal: ' + total); $("#order_total").show(); $('.submitorder').show(); } if(total == 0){ $("#order_total").html('Your shopping basket is empty'); $("#order_total").show(); $('.submitorder').hide(); } ```
9,553,939
I'm trying to crawl FTP and pull down all the files recursively. Up until now I was trying to pull down a directory with ``` ftp.list.each do |entry| if entry.split(/\s+/)[0][0, 1] == "d" out[:dirs] << entry.split.last unless black_dirs.include? entry.split.last else out[:files] << entry.split.last unless black_files.include? entry.split.last end ``` But turns out, if you split the list up until last space, filenames and directories with spaces are fetched wrong. Need a little help on the logic here.
2012/03/04
[ "https://Stackoverflow.com/questions/9553939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/853685/" ]
You can also use a regular expression. I put one together. Please verify if it works for you as well as I don't know it your dir listing look different. You have to use Ruby 1.9 btw. ``` reg = /^(?<type>.{1})(?<mode>\S+)\s+(?<number>\d+)\s+(?<owner>\S+)\s+(?<group>\S+)\s+(?<size>\d+)\s+(?<mod_time>.{12})\s+(?<path>.+)$/ match = entry.match(reg) ``` You are able to access the elements by name then `match[:type]` contains a `'d'` if it's a directory, a space if it's a file. All the other elements are there as well. Most importantly `match[:path]`.
You can avoid recursion if you list all files at once `files = ftp.nlst('**/*.*')` Directories are not included in the list but the full ftp path is still available in the name. EDIT I'm assuming that each file name contains a dot and directory names don't. Thanks for mentioning @Niklas B.
9,553,939
I'm trying to crawl FTP and pull down all the files recursively. Up until now I was trying to pull down a directory with ``` ftp.list.each do |entry| if entry.split(/\s+/)[0][0, 1] == "d" out[:dirs] << entry.split.last unless black_dirs.include? entry.split.last else out[:files] << entry.split.last unless black_files.include? entry.split.last end ``` But turns out, if you split the list up until last space, filenames and directories with spaces are fetched wrong. Need a little help on the logic here.
2012/03/04
[ "https://Stackoverflow.com/questions/9553939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/853685/" ]
Assuming that the FTP server returns *Unix-like* file listings, the following code works. At least for me. ``` regex = /^d[r|w|x|-]+\s+[0-9]\s+\S+\s+\S+\s+\d+\s+\w+\s+\d+\s+[\d|:]+\s(.+)/ ftp.ls.each do |line| if dir = line.match(regex) puts dir[1] end end ``` `dir[1]` contains the name of the directory (given that the inspected line actually represents a directory).
As @Alex pointed out, using patterns in filenames for this is hardly reliable. Directories CAN have dots in their names (.ssh for example), and listings can be very different on different servers. His method works, but as he himself points out, takes too long. I prefer using the .size method from Net::FTP. It returns the size of a file, or throws an error if the file is a directory. ``` def item_is_file? (item) ftp = Net::FTP.new(host, username, password) begin if ftp.size(item).is_a? Numeric true end rescue Net::FTPPermError return false end end ```
9,553,939
I'm trying to crawl FTP and pull down all the files recursively. Up until now I was trying to pull down a directory with ``` ftp.list.each do |entry| if entry.split(/\s+/)[0][0, 1] == "d" out[:dirs] << entry.split.last unless black_dirs.include? entry.split.last else out[:files] << entry.split.last unless black_files.include? entry.split.last end ``` But turns out, if you split the list up until last space, filenames and directories with spaces are fetched wrong. Need a little help on the logic here.
2012/03/04
[ "https://Stackoverflow.com/questions/9553939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/853685/" ]
Assuming that the FTP server returns *Unix-like* file listings, the following code works. At least for me. ``` regex = /^d[r|w|x|-]+\s+[0-9]\s+\S+\s+\S+\s+\d+\s+\w+\s+\d+\s+[\d|:]+\s(.+)/ ftp.ls.each do |line| if dir = line.match(regex) puts dir[1] end end ``` `dir[1]` contains the name of the directory (given that the inspected line actually represents a directory).
I'll add my solution to the mix... Using `ftp.nlst('**/*.*')` did not work for me... server doesn't seem to support that \*\* syntax. The chdir trick with a `rescue` seems expensive and hackish. Assuming that all files have at least one char, a single period, and then an extension, I did a simple recursion. ``` def list_all_files(ftp, folder) entries = ftp.nlst(folder) file_regex = /.+\.{1}.*/ files = entries.select{|e| e.match(file_regex)} subfolders = entries.reject{|e| e.match(file_regex)} subfolders.each do |subfolder| files += list_all_files(ftp, subfolder) end files end ``` `nlst` seems to return the full path to whatever it finds *non-recursively*... so each time you get a listing, separate the files from the folders, and then process any folder you find recrsively. Collect all the file results. To call, you can pass a starting folder ``` files = list_all_files(ftp, "my_starting_folder/my_sub_folder") files = list_all_files(ftp, ".") files = list_all_files(ftp, "") files = list_all_files(ftp, nil) ```
9,553,939
I'm trying to crawl FTP and pull down all the files recursively. Up until now I was trying to pull down a directory with ``` ftp.list.each do |entry| if entry.split(/\s+/)[0][0, 1] == "d" out[:dirs] << entry.split.last unless black_dirs.include? entry.split.last else out[:files] << entry.split.last unless black_files.include? entry.split.last end ``` But turns out, if you split the list up until last space, filenames and directories with spaces are fetched wrong. Need a little help on the logic here.
2012/03/04
[ "https://Stackoverflow.com/questions/9553939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/853685/" ]
There are a huge variety of FTP servers around. We have clients who use some obscure proprietary, Windows-based servers and the file listing returned by them look completely different from Linux versions. So what I ended up doing is for each file/directory entry I try changing directory into it and if this doesn't work - consider it a file :) The following method is "bullet proof": ``` # Checks if the give file_name is actually a file. def is_ftp_file?(ftp, file_name) ftp.chdir(file_name) ftp.chdir('..') false rescue true end file_names = ftp.nlst.select {|fname| is_ftp_file?(ftp, fname)} ``` Works like a charm, but **please note:** if the FTP directory has tons of files in it - this method **takes a while** to traverse all of them.
I'll add my solution to the mix... Using `ftp.nlst('**/*.*')` did not work for me... server doesn't seem to support that \*\* syntax. The chdir trick with a `rescue` seems expensive and hackish. Assuming that all files have at least one char, a single period, and then an extension, I did a simple recursion. ``` def list_all_files(ftp, folder) entries = ftp.nlst(folder) file_regex = /.+\.{1}.*/ files = entries.select{|e| e.match(file_regex)} subfolders = entries.reject{|e| e.match(file_regex)} subfolders.each do |subfolder| files += list_all_files(ftp, subfolder) end files end ``` `nlst` seems to return the full path to whatever it finds *non-recursively*... so each time you get a listing, separate the files from the folders, and then process any folder you find recrsively. Collect all the file results. To call, you can pass a starting folder ``` files = list_all_files(ftp, "my_starting_folder/my_sub_folder") files = list_all_files(ftp, ".") files = list_all_files(ftp, "") files = list_all_files(ftp, nil) ```
9,553,939
I'm trying to crawl FTP and pull down all the files recursively. Up until now I was trying to pull down a directory with ``` ftp.list.each do |entry| if entry.split(/\s+/)[0][0, 1] == "d" out[:dirs] << entry.split.last unless black_dirs.include? entry.split.last else out[:files] << entry.split.last unless black_files.include? entry.split.last end ``` But turns out, if you split the list up until last space, filenames and directories with spaces are fetched wrong. Need a little help on the logic here.
2012/03/04
[ "https://Stackoverflow.com/questions/9553939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/853685/" ]
You can also use a regular expression. I put one together. Please verify if it works for you as well as I don't know it your dir listing look different. You have to use Ruby 1.9 btw. ``` reg = /^(?<type>.{1})(?<mode>\S+)\s+(?<number>\d+)\s+(?<owner>\S+)\s+(?<group>\S+)\s+(?<size>\d+)\s+(?<mod_time>.{12})\s+(?<path>.+)$/ match = entry.match(reg) ``` You are able to access the elements by name then `match[:type]` contains a `'d'` if it's a directory, a space if it's a file. All the other elements are there as well. Most importantly `match[:path]`.
There are a huge variety of FTP servers around. We have clients who use some obscure proprietary, Windows-based servers and the file listing returned by them look completely different from Linux versions. So what I ended up doing is for each file/directory entry I try changing directory into it and if this doesn't work - consider it a file :) The following method is "bullet proof": ``` # Checks if the give file_name is actually a file. def is_ftp_file?(ftp, file_name) ftp.chdir(file_name) ftp.chdir('..') false rescue true end file_names = ftp.nlst.select {|fname| is_ftp_file?(ftp, fname)} ``` Works like a charm, but **please note:** if the FTP directory has tons of files in it - this method **takes a while** to traverse all of them.
9,553,939
I'm trying to crawl FTP and pull down all the files recursively. Up until now I was trying to pull down a directory with ``` ftp.list.each do |entry| if entry.split(/\s+/)[0][0, 1] == "d" out[:dirs] << entry.split.last unless black_dirs.include? entry.split.last else out[:files] << entry.split.last unless black_files.include? entry.split.last end ``` But turns out, if you split the list up until last space, filenames and directories with spaces are fetched wrong. Need a little help on the logic here.
2012/03/04
[ "https://Stackoverflow.com/questions/9553939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/853685/" ]
You can avoid recursion if you list all files at once `files = ftp.nlst('**/*.*')` Directories are not included in the list but the full ftp path is still available in the name. EDIT I'm assuming that each file name contains a dot and directory names don't. Thanks for mentioning @Niklas B.
As @Alex pointed out, using patterns in filenames for this is hardly reliable. Directories CAN have dots in their names (.ssh for example), and listings can be very different on different servers. His method works, but as he himself points out, takes too long. I prefer using the .size method from Net::FTP. It returns the size of a file, or throws an error if the file is a directory. ``` def item_is_file? (item) ftp = Net::FTP.new(host, username, password) begin if ftp.size(item).is_a? Numeric true end rescue Net::FTPPermError return false end end ```
9,553,939
I'm trying to crawl FTP and pull down all the files recursively. Up until now I was trying to pull down a directory with ``` ftp.list.each do |entry| if entry.split(/\s+/)[0][0, 1] == "d" out[:dirs] << entry.split.last unless black_dirs.include? entry.split.last else out[:files] << entry.split.last unless black_files.include? entry.split.last end ``` But turns out, if you split the list up until last space, filenames and directories with spaces are fetched wrong. Need a little help on the logic here.
2012/03/04
[ "https://Stackoverflow.com/questions/9553939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/853685/" ]
You can also use a regular expression. I put one together. Please verify if it works for you as well as I don't know it your dir listing look different. You have to use Ruby 1.9 btw. ``` reg = /^(?<type>.{1})(?<mode>\S+)\s+(?<number>\d+)\s+(?<owner>\S+)\s+(?<group>\S+)\s+(?<size>\d+)\s+(?<mod_time>.{12})\s+(?<path>.+)$/ match = entry.match(reg) ``` You are able to access the elements by name then `match[:type]` contains a `'d'` if it's a directory, a space if it's a file. All the other elements are there as well. Most importantly `match[:path]`.
As @Alex pointed out, using patterns in filenames for this is hardly reliable. Directories CAN have dots in their names (.ssh for example), and listings can be very different on different servers. His method works, but as he himself points out, takes too long. I prefer using the .size method from Net::FTP. It returns the size of a file, or throws an error if the file is a directory. ``` def item_is_file? (item) ftp = Net::FTP.new(host, username, password) begin if ftp.size(item).is_a? Numeric true end rescue Net::FTPPermError return false end end ```
9,553,939
I'm trying to crawl FTP and pull down all the files recursively. Up until now I was trying to pull down a directory with ``` ftp.list.each do |entry| if entry.split(/\s+/)[0][0, 1] == "d" out[:dirs] << entry.split.last unless black_dirs.include? entry.split.last else out[:files] << entry.split.last unless black_files.include? entry.split.last end ``` But turns out, if you split the list up until last space, filenames and directories with spaces are fetched wrong. Need a little help on the logic here.
2012/03/04
[ "https://Stackoverflow.com/questions/9553939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/853685/" ]
You can also use a regular expression. I put one together. Please verify if it works for you as well as I don't know it your dir listing look different. You have to use Ruby 1.9 btw. ``` reg = /^(?<type>.{1})(?<mode>\S+)\s+(?<number>\d+)\s+(?<owner>\S+)\s+(?<group>\S+)\s+(?<size>\d+)\s+(?<mod_time>.{12})\s+(?<path>.+)$/ match = entry.match(reg) ``` You are able to access the elements by name then `match[:type]` contains a `'d'` if it's a directory, a space if it's a file. All the other elements are there as well. Most importantly `match[:path]`.
Assuming that the FTP server returns *Unix-like* file listings, the following code works. At least for me. ``` regex = /^d[r|w|x|-]+\s+[0-9]\s+\S+\s+\S+\s+\d+\s+\w+\s+\d+\s+[\d|:]+\s(.+)/ ftp.ls.each do |line| if dir = line.match(regex) puts dir[1] end end ``` `dir[1]` contains the name of the directory (given that the inspected line actually represents a directory).
9,553,939
I'm trying to crawl FTP and pull down all the files recursively. Up until now I was trying to pull down a directory with ``` ftp.list.each do |entry| if entry.split(/\s+/)[0][0, 1] == "d" out[:dirs] << entry.split.last unless black_dirs.include? entry.split.last else out[:files] << entry.split.last unless black_files.include? entry.split.last end ``` But turns out, if you split the list up until last space, filenames and directories with spaces are fetched wrong. Need a little help on the logic here.
2012/03/04
[ "https://Stackoverflow.com/questions/9553939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/853685/" ]
You can also use a regular expression. I put one together. Please verify if it works for you as well as I don't know it your dir listing look different. You have to use Ruby 1.9 btw. ``` reg = /^(?<type>.{1})(?<mode>\S+)\s+(?<number>\d+)\s+(?<owner>\S+)\s+(?<group>\S+)\s+(?<size>\d+)\s+(?<mod_time>.{12})\s+(?<path>.+)$/ match = entry.match(reg) ``` You are able to access the elements by name then `match[:type]` contains a `'d'` if it's a directory, a space if it's a file. All the other elements are there as well. Most importantly `match[:path]`.
I'll add my solution to the mix... Using `ftp.nlst('**/*.*')` did not work for me... server doesn't seem to support that \*\* syntax. The chdir trick with a `rescue` seems expensive and hackish. Assuming that all files have at least one char, a single period, and then an extension, I did a simple recursion. ``` def list_all_files(ftp, folder) entries = ftp.nlst(folder) file_regex = /.+\.{1}.*/ files = entries.select{|e| e.match(file_regex)} subfolders = entries.reject{|e| e.match(file_regex)} subfolders.each do |subfolder| files += list_all_files(ftp, subfolder) end files end ``` `nlst` seems to return the full path to whatever it finds *non-recursively*... so each time you get a listing, separate the files from the folders, and then process any folder you find recrsively. Collect all the file results. To call, you can pass a starting folder ``` files = list_all_files(ftp, "my_starting_folder/my_sub_folder") files = list_all_files(ftp, ".") files = list_all_files(ftp, "") files = list_all_files(ftp, nil) ```
9,553,939
I'm trying to crawl FTP and pull down all the files recursively. Up until now I was trying to pull down a directory with ``` ftp.list.each do |entry| if entry.split(/\s+/)[0][0, 1] == "d" out[:dirs] << entry.split.last unless black_dirs.include? entry.split.last else out[:files] << entry.split.last unless black_files.include? entry.split.last end ``` But turns out, if you split the list up until last space, filenames and directories with spaces are fetched wrong. Need a little help on the logic here.
2012/03/04
[ "https://Stackoverflow.com/questions/9553939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/853685/" ]
There are a huge variety of FTP servers around. We have clients who use some obscure proprietary, Windows-based servers and the file listing returned by them look completely different from Linux versions. So what I ended up doing is for each file/directory entry I try changing directory into it and if this doesn't work - consider it a file :) The following method is "bullet proof": ``` # Checks if the give file_name is actually a file. def is_ftp_file?(ftp, file_name) ftp.chdir(file_name) ftp.chdir('..') false rescue true end file_names = ftp.nlst.select {|fname| is_ftp_file?(ftp, fname)} ``` Works like a charm, but **please note:** if the FTP directory has tons of files in it - this method **takes a while** to traverse all of them.
As @Alex pointed out, using patterns in filenames for this is hardly reliable. Directories CAN have dots in their names (.ssh for example), and listings can be very different on different servers. His method works, but as he himself points out, takes too long. I prefer using the .size method from Net::FTP. It returns the size of a file, or throws an error if the file is a directory. ``` def item_is_file? (item) ftp = Net::FTP.new(host, username, password) begin if ftp.size(item).is_a? Numeric true end rescue Net::FTPPermError return false end end ```
13,539,692
Say we have the following classes: ``` class DoubleOhSeven { public static void doSomethingClassy(); public static void neverDoThisClassy(); } class Dude { public void doSomething(); public void neverDoThis(); } public class Party { public static void main(String[] args){ DoubleOhSeven.doSomething(); Dude guy = new Dude; guy.doSomething(); } } ``` Of course, all the methods will be compiled into their respective `.class`: do the unused static/instance methods occupy memory at run time? What about unused inherited or imported methods?
2012/11/24
[ "https://Stackoverflow.com/questions/13539692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/390897/" ]
The unused methods are still there occupying memory as part of the class / object, even if they're not directly called. If they were optimised away, then that would make reflective calls on these methods impossible. One could argue that an optimisation could be generated that only stored the method stub in memory, and garbage collected the method contents (which would then be re-fetched from the class file if a call was made.) However, I'm not aware of a VM which does this, and it would be hard to justify due to the likely minimal gains in memory and tradeoff in speed whenever such a method was called. Unused inherited methods would be exactly the same.
The unused methods inrease the class size, but classes are stored in a so called PermGen memory. The heap memory, where regular java objects are stored, is not affected by class size
13,539,692
Say we have the following classes: ``` class DoubleOhSeven { public static void doSomethingClassy(); public static void neverDoThisClassy(); } class Dude { public void doSomething(); public void neverDoThis(); } public class Party { public static void main(String[] args){ DoubleOhSeven.doSomething(); Dude guy = new Dude; guy.doSomething(); } } ``` Of course, all the methods will be compiled into their respective `.class`: do the unused static/instance methods occupy memory at run time? What about unused inherited or imported methods?
2012/11/24
[ "https://Stackoverflow.com/questions/13539692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/390897/" ]
The unused methods are still there occupying memory as part of the class / object, even if they're not directly called. If they were optimised away, then that would make reflective calls on these methods impossible. One could argue that an optimisation could be generated that only stored the method stub in memory, and garbage collected the method contents (which would then be re-fetched from the class file if a call was made.) However, I'm not aware of a VM which does this, and it would be hard to justify due to the likely minimal gains in memory and tradeoff in speed whenever such a method was called. Unused inherited methods would be exactly the same.
The memory used by an instance of a class `Abc` does not depend on how many methods there are in `Abc`. The generated bytecode obviously does increase in size when you add methods, whether they do something or not, but that would only affect the size of the class object `Abc.class`, which is loaded only once, regardless of how many instances are created.
13,539,692
Say we have the following classes: ``` class DoubleOhSeven { public static void doSomethingClassy(); public static void neverDoThisClassy(); } class Dude { public void doSomething(); public void neverDoThis(); } public class Party { public static void main(String[] args){ DoubleOhSeven.doSomething(); Dude guy = new Dude; guy.doSomething(); } } ``` Of course, all the methods will be compiled into their respective `.class`: do the unused static/instance methods occupy memory at run time? What about unused inherited or imported methods?
2012/11/24
[ "https://Stackoverflow.com/questions/13539692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/390897/" ]
The unused methods are still there occupying memory as part of the class / object, even if they're not directly called. If they were optimised away, then that would make reflective calls on these methods impossible. One could argue that an optimisation could be generated that only stored the method stub in memory, and garbage collected the method contents (which would then be re-fetched from the class file if a call was made.) However, I'm not aware of a VM which does this, and it would be hard to justify due to the likely minimal gains in memory and tradeoff in speed whenever such a method was called. Unused inherited methods would be exactly the same.
Since classes are safed in ther PermGen for Sun Hotspot JVMs (that will change for Java 8), you can do something like this, first run: ``` MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); long before = memoryMXBean.getNonHeapMemoryUsage().getUsed(); new Dude(); // class must not be loaded before System.out.println("Usage of dude is " + (memoryMXBean.getNonHeapMemoryUsage().getUsed() - before) + " bytes"); ``` And you will see something like this: *Usage of dude is 6432 bytes* And then create a Dude class without the unused method and run the test: ``` MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); long before = memoryMXBean.getNonHeapMemoryUsage().getUsed(); new DudeWithoutNeverDoThis(); // must not be loaded before System.out.println("Usage of dude without 'nerverDoThis' is " + (memoryMXBean.getNonHeapMemoryUsage().getUsed() - before) + " bytes"); ``` and you see the difference (*Usage of dude without 'nerverDoThis' is 6176 bytes*)
13,539,692
Say we have the following classes: ``` class DoubleOhSeven { public static void doSomethingClassy(); public static void neverDoThisClassy(); } class Dude { public void doSomething(); public void neverDoThis(); } public class Party { public static void main(String[] args){ DoubleOhSeven.doSomething(); Dude guy = new Dude; guy.doSomething(); } } ``` Of course, all the methods will be compiled into their respective `.class`: do the unused static/instance methods occupy memory at run time? What about unused inherited or imported methods?
2012/11/24
[ "https://Stackoverflow.com/questions/13539692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/390897/" ]
The unused methods are still there occupying memory as part of the class / object, even if they're not directly called. If they were optimised away, then that would make reflective calls on these methods impossible. One could argue that an optimisation could be generated that only stored the method stub in memory, and garbage collected the method contents (which would then be re-fetched from the class file if a call was made.) However, I'm not aware of a VM which does this, and it would be hard to justify due to the likely minimal gains in memory and tradeoff in speed whenever such a method was called. Unused inherited methods would be exactly the same.
The method can be compiled and loaded to PerGen. But JVM maybe `optimize` method using `method inlining`. Eg: ``` public class Test { public void foo(){ System.out.println("foo"); bar(); } public void bar(){ System.out.println("bar"); } } ``` The method will be compiled like this by JIT compiler: ``` public void foo(){ System.out.println("foo"); System.out.println("bar"); } ``` So, the empty method will never be invoked.
13,539,692
Say we have the following classes: ``` class DoubleOhSeven { public static void doSomethingClassy(); public static void neverDoThisClassy(); } class Dude { public void doSomething(); public void neverDoThis(); } public class Party { public static void main(String[] args){ DoubleOhSeven.doSomething(); Dude guy = new Dude; guy.doSomething(); } } ``` Of course, all the methods will be compiled into their respective `.class`: do the unused static/instance methods occupy memory at run time? What about unused inherited or imported methods?
2012/11/24
[ "https://Stackoverflow.com/questions/13539692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/390897/" ]
The memory used by an instance of a class `Abc` does not depend on how many methods there are in `Abc`. The generated bytecode obviously does increase in size when you add methods, whether they do something or not, but that would only affect the size of the class object `Abc.class`, which is loaded only once, regardless of how many instances are created.
The unused methods inrease the class size, but classes are stored in a so called PermGen memory. The heap memory, where regular java objects are stored, is not affected by class size
13,539,692
Say we have the following classes: ``` class DoubleOhSeven { public static void doSomethingClassy(); public static void neverDoThisClassy(); } class Dude { public void doSomething(); public void neverDoThis(); } public class Party { public static void main(String[] args){ DoubleOhSeven.doSomething(); Dude guy = new Dude; guy.doSomething(); } } ``` Of course, all the methods will be compiled into their respective `.class`: do the unused static/instance methods occupy memory at run time? What about unused inherited or imported methods?
2012/11/24
[ "https://Stackoverflow.com/questions/13539692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/390897/" ]
Since classes are safed in ther PermGen for Sun Hotspot JVMs (that will change for Java 8), you can do something like this, first run: ``` MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); long before = memoryMXBean.getNonHeapMemoryUsage().getUsed(); new Dude(); // class must not be loaded before System.out.println("Usage of dude is " + (memoryMXBean.getNonHeapMemoryUsage().getUsed() - before) + " bytes"); ``` And you will see something like this: *Usage of dude is 6432 bytes* And then create a Dude class without the unused method and run the test: ``` MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); long before = memoryMXBean.getNonHeapMemoryUsage().getUsed(); new DudeWithoutNeverDoThis(); // must not be loaded before System.out.println("Usage of dude without 'nerverDoThis' is " + (memoryMXBean.getNonHeapMemoryUsage().getUsed() - before) + " bytes"); ``` and you see the difference (*Usage of dude without 'nerverDoThis' is 6176 bytes*)
The unused methods inrease the class size, but classes are stored in a so called PermGen memory. The heap memory, where regular java objects are stored, is not affected by class size
13,539,692
Say we have the following classes: ``` class DoubleOhSeven { public static void doSomethingClassy(); public static void neverDoThisClassy(); } class Dude { public void doSomething(); public void neverDoThis(); } public class Party { public static void main(String[] args){ DoubleOhSeven.doSomething(); Dude guy = new Dude; guy.doSomething(); } } ``` Of course, all the methods will be compiled into their respective `.class`: do the unused static/instance methods occupy memory at run time? What about unused inherited or imported methods?
2012/11/24
[ "https://Stackoverflow.com/questions/13539692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/390897/" ]
The unused methods inrease the class size, but classes are stored in a so called PermGen memory. The heap memory, where regular java objects are stored, is not affected by class size
The method can be compiled and loaded to PerGen. But JVM maybe `optimize` method using `method inlining`. Eg: ``` public class Test { public void foo(){ System.out.println("foo"); bar(); } public void bar(){ System.out.println("bar"); } } ``` The method will be compiled like this by JIT compiler: ``` public void foo(){ System.out.println("foo"); System.out.println("bar"); } ``` So, the empty method will never be invoked.
13,539,692
Say we have the following classes: ``` class DoubleOhSeven { public static void doSomethingClassy(); public static void neverDoThisClassy(); } class Dude { public void doSomething(); public void neverDoThis(); } public class Party { public static void main(String[] args){ DoubleOhSeven.doSomething(); Dude guy = new Dude; guy.doSomething(); } } ``` Of course, all the methods will be compiled into their respective `.class`: do the unused static/instance methods occupy memory at run time? What about unused inherited or imported methods?
2012/11/24
[ "https://Stackoverflow.com/questions/13539692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/390897/" ]
The memory used by an instance of a class `Abc` does not depend on how many methods there are in `Abc`. The generated bytecode obviously does increase in size when you add methods, whether they do something or not, but that would only affect the size of the class object `Abc.class`, which is loaded only once, regardless of how many instances are created.
The method can be compiled and loaded to PerGen. But JVM maybe `optimize` method using `method inlining`. Eg: ``` public class Test { public void foo(){ System.out.println("foo"); bar(); } public void bar(){ System.out.println("bar"); } } ``` The method will be compiled like this by JIT compiler: ``` public void foo(){ System.out.println("foo"); System.out.println("bar"); } ``` So, the empty method will never be invoked.
13,539,692
Say we have the following classes: ``` class DoubleOhSeven { public static void doSomethingClassy(); public static void neverDoThisClassy(); } class Dude { public void doSomething(); public void neverDoThis(); } public class Party { public static void main(String[] args){ DoubleOhSeven.doSomething(); Dude guy = new Dude; guy.doSomething(); } } ``` Of course, all the methods will be compiled into their respective `.class`: do the unused static/instance methods occupy memory at run time? What about unused inherited or imported methods?
2012/11/24
[ "https://Stackoverflow.com/questions/13539692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/390897/" ]
Since classes are safed in ther PermGen for Sun Hotspot JVMs (that will change for Java 8), you can do something like this, first run: ``` MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); long before = memoryMXBean.getNonHeapMemoryUsage().getUsed(); new Dude(); // class must not be loaded before System.out.println("Usage of dude is " + (memoryMXBean.getNonHeapMemoryUsage().getUsed() - before) + " bytes"); ``` And you will see something like this: *Usage of dude is 6432 bytes* And then create a Dude class without the unused method and run the test: ``` MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); long before = memoryMXBean.getNonHeapMemoryUsage().getUsed(); new DudeWithoutNeverDoThis(); // must not be loaded before System.out.println("Usage of dude without 'nerverDoThis' is " + (memoryMXBean.getNonHeapMemoryUsage().getUsed() - before) + " bytes"); ``` and you see the difference (*Usage of dude without 'nerverDoThis' is 6176 bytes*)
The method can be compiled and loaded to PerGen. But JVM maybe `optimize` method using `method inlining`. Eg: ``` public class Test { public void foo(){ System.out.println("foo"); bar(); } public void bar(){ System.out.println("bar"); } } ``` The method will be compiled like this by JIT compiler: ``` public void foo(){ System.out.println("foo"); System.out.println("bar"); } ``` So, the empty method will never be invoked.
26,404
In our web-application(built on Bootstrap and Angular), certain tabs in the navbar are displayed only to particular users. Certain input boxes/ buttons are enabled only to certain users. I want to write test scripts using Selenium/ Sikuli to test this functionality and I want your suggestions in this approach. One of the ideas is to navigate to different pages in the UI, and use Selenium's `isDisplayed()` and `isEnabled()` functions and make assertions. And capture screenshots accordingly? The other idea is to use Sikuli and match certain submenus being present on hover, capture screenshots and compare with the expected. Which approach do you guys think is the better one to use? Also, please suggest if there's another way to do it. Would also be so glad if you guys can provide me a generic method to test this.
2017/03/26
[ "https://sqa.stackexchange.com/questions/26404", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/24825/" ]
I think the name comes from the resulting graph over-time, which is called a stairstep graph. I don't think it is official, but more some terms added together which seemed logical. The step load pattern increases the user load periodically during the load test. Creating a stairstep graph where you show number of users vs time: [![enter image description here](https://i.stack.imgur.com/shNoy.png)](https://i.stack.imgur.com/shNoy.png) This instead of a continuous increase over time. Let say you increase the number of users by 60 each minute. This would generate a stairstep. You could also add a user each second increasing it linear. Other reads: * How to: Change the Load Pattern: <https://msdn.microsoft.com/en-us/library/ms182586(v=vs.80).aspx>
"Stair-Step" is also know as "Ramp up". In this type of Performance Testing, load is increased in a schedule intervals to check the server performance.
26,404
In our web-application(built on Bootstrap and Angular), certain tabs in the navbar are displayed only to particular users. Certain input boxes/ buttons are enabled only to certain users. I want to write test scripts using Selenium/ Sikuli to test this functionality and I want your suggestions in this approach. One of the ideas is to navigate to different pages in the UI, and use Selenium's `isDisplayed()` and `isEnabled()` functions and make assertions. And capture screenshots accordingly? The other idea is to use Sikuli and match certain submenus being present on hover, capture screenshots and compare with the expected. Which approach do you guys think is the better one to use? Also, please suggest if there's another way to do it. Would also be so glad if you guys can provide me a generic method to test this.
2017/03/26
[ "https://sqa.stackexchange.com/questions/26404", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/24825/" ]
I think the name comes from the resulting graph over-time, which is called a stairstep graph. I don't think it is official, but more some terms added together which seemed logical. The step load pattern increases the user load periodically during the load test. Creating a stairstep graph where you show number of users vs time: [![enter image description here](https://i.stack.imgur.com/shNoy.png)](https://i.stack.imgur.com/shNoy.png) This instead of a continuous increase over time. Let say you increase the number of users by 60 each minute. This would generate a stairstep. You could also add a user each second increasing it linear. Other reads: * How to: Change the Load Pattern: <https://msdn.microsoft.com/en-us/library/ms182586(v=vs.80).aspx>
Load is increased over time and by set increments. Users observe whether the server load on memory, cpu, etc. and response time remain constant, increase proportionally or start to increase disproportionately. It is done in steps or increments for efficiency. Instead of 5000 different tests with 1,2,3,4,5,6,7,8... 5000 users you will get most of what you want to know from 'steps' such as 1,2,3,10,20,50,100,1000,5000 user loads i.e. 9 tests instead of 5000 tests. Sometimes the process is repeated if a certain point is found where individual performance start to suffer with more small steps around that point to pin-point it, e.g. if 100 was ok but 1000 was not you might try again with 150,200,400,800 Use with caution. Don't do premature optimization is a strong concept to repect. In a few weeks the database or server may become more powerful. Try to remain implementation independent as long as possible.
26,404
In our web-application(built on Bootstrap and Angular), certain tabs in the navbar are displayed only to particular users. Certain input boxes/ buttons are enabled only to certain users. I want to write test scripts using Selenium/ Sikuli to test this functionality and I want your suggestions in this approach. One of the ideas is to navigate to different pages in the UI, and use Selenium's `isDisplayed()` and `isEnabled()` functions and make assertions. And capture screenshots accordingly? The other idea is to use Sikuli and match certain submenus being present on hover, capture screenshots and compare with the expected. Which approach do you guys think is the better one to use? Also, please suggest if there's another way to do it. Would also be so glad if you guys can provide me a generic method to test this.
2017/03/26
[ "https://sqa.stackexchange.com/questions/26404", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/24825/" ]
I think the name comes from the resulting graph over-time, which is called a stairstep graph. I don't think it is official, but more some terms added together which seemed logical. The step load pattern increases the user load periodically during the load test. Creating a stairstep graph where you show number of users vs time: [![enter image description here](https://i.stack.imgur.com/shNoy.png)](https://i.stack.imgur.com/shNoy.png) This instead of a continuous increase over time. Let say you increase the number of users by 60 each minute. This would generate a stairstep. You could also add a user each second increasing it linear. Other reads: * How to: Change the Load Pattern: <https://msdn.microsoft.com/en-us/library/ms182586(v=vs.80).aspx>
Here is an explanation for the term you are looking for. Though I believe that the adliteram term you are after does not exist, but it refers to the different approaches to **load patterns**. The **step** load pattern is used to specify a user load that increases with time up to a defined maximum user load. For stepping loads, you specify the Initial User Count, Maximum User Count, Step Duration (seconds), and Step User Count. For example a **Step load** with an Initial User count of one, **Maximum User Count of 100**, **Step Duration** (seconds) of 10, and a Step User Count of 1 creates a user load pattern that starts at 1, increases by 1 every 10 seconds until it reaches 100 Users.
64,872,442
I deployed a Rails application in Digital Ocean Ubuntu Server using Capistrano. For some reason the puma server suddenly stops. I'm not sure what's the reason. That's why I created a script **/home/deploy/startup-script.sh** the script contains the commands to startup the Rails application in daemon ``` #!/bin/bash echo "Running Puma Server" touch hello.txt cd /srv/www/apps/app/current bundle exec puma -C /srv/www/apps/app/shared/puma.rb --daemon ``` then I run this script every minute using Cron. My **crontab -e** contains ``` * * * * * ./startup-script.sh ``` After 1 minute I noticed that it created a hello.txt file but my puma server is not running. But when I run it manually using `./startup-script.sh` it will run the server. **puma\_error.log** ``` Puma starting in single mode... * Version 4.3.1 (ruby 2.6.0-p0), codename: Mysterious Traveller * Min threads: 0, max threads: 8 * Environment: production * Daemonizing... === puma startup: 2020-09-21 05:16:28 +0000 === === puma startup: 2020-09-21 05:17:39 +0000 === * Listening on tcp://0.0.0.0:9292 === puma startup: 2020-09-21 06:11:35 +0000 === - Gracefully stopping, waiting for requests to finish === puma shutdown: 2020-09-21 06:11:35 +0000 === ``` **production.log** ``` Item Load (0.3ms) SELECT "items".* FROM "items" WHERE "items"."id" = $1 LIMIT $2 [["id", 208], ["LIMIT", 1]] CACHE Unit Load (0.0ms) SELECT "units".* FROM "units" WHERE "units"."id" = $1 LIMIT $2 [["id", 4], ["LIMIT", 1]] Item Load (0.3ms) SELECT "items".* FROM "items" WHERE "items"."id" = $1 LIMIT $2 [["id", 215], ["LIMIT", 1]] CACHE Unit Load (0.0ms) SELECT "units".* FROM "units" WHERE "units"."id" = $1 LIMIT $2 [["id", 4], ["LIMIT", 1]] Item Load (0.2ms) SELECT "items".* FROM "items" WHERE "items"."id" = $1 LIMIT $2 [["id", 198], ["LIMIT", 1]] CACHE Unit Load (0.0ms) SELECT "units".* FROM "units" WHERE "units"."id" = $1 LIMIT $2 [["id", 10], ["LIMIT", 1]] Rendering text template Rendered text template (0.0ms) Sent data Delivery Receipt 12-2020-001.pdf (0.5ms) Completed 200 OK in 4326ms (Views: 0.3ms | ActiveRecord: 37.4ms) ``` **puma\_access.log** ``` === puma startup: 2020-12-01 01:07:13 +0000 === ``` When starting the `startup-script.sh` script I'm getting this ``` Running Puma Server Puma starting in single mode... * Version 4.3.1 (ruby 2.6.0-p0), codename: Mysterious Traveller * Min threads: 0, max threads: 8 * Environment: production * Daemonizing... ``` My droplet is still running but the puma running on port 9292 disappears when crashes, so I suspect this is puma error.
2020/11/17
[ "https://Stackoverflow.com/questions/64872442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1077711/" ]
I agree with OP that, the simple predicate of the O(N) algo might not work on the stack-based solution when looking for the first element > 2x in the remaining array. I found a O(NlogN) solution for this btw. It uses a **Min-heap** to maintain the frontier elements we are interested in. ### Pseudo-code: ``` def get_2x_elements(input_list, multipler = 2): H = [] #min-heap with node-values as tuples (index, value) R = [-1 for _ in range(len(input_list))] # results-list for index, value in enumerate(input_list): while multiplier*H[0][1] < value: minval = extractMinFromHeap(H) R[minval[0]] = value insertToMinHeap(H, (index, value)) return R ``` ### Complexity-analysis: ``` 1. Insertion/Extraction from min-heap = O(logN) 2. Number of such operations = N Total-complexity = O(NlogN) ``` PS: This assumes we need the `first >2x element` from the remaining part of the list. Re: I made a Java verion implementation of your idea. Thanks @Serial Lazer ```java private static class ValueAndIndexPair implements Comparable<ValueAndIndexPair>{ public final double value; public final int index; public ValueAndIndexPair(double value, int index) { this.value = value; this.index = index; } @Override public int compareTo(ValueAndIndexPair other) { return Double.compare(value, other.value); } } public static double[] returnNextNTimeLargerElementIndex(final List<Double> valueList, double multiplier) { double[] result = new double[valueList.size()]; PriorityQueue<ValueAndIndexPair> minHeap = new PriorityQueue<>(); // Initialize O(n) for (int i = 0; i < valueList.size(); i++) { result[i] = -1.0; } if (valueList.size() <= 1) return result; minHeap.add(new ValueAndIndexPair(valueList.get(0) * multiplier, 0)); for (int i = 1; i <valueList.size(); i++) { double currentElement = valueList.get(i); while (!minHeap.isEmpty() && minHeap.peek().value < currentElement) { result[minHeap.poll().index] = currentElement; } minHeap.add(new ValueAndIndexPair(currentElement * multiplier, i)); } return result; } ```
Sure, easily. We just need a sorted version of the array (sorted elements plus their original index) and then we can do an efficient search (a modified binary search) that points us to the start of the elements that are larger than the current number (or a multiple of it, it doesn't matter). Those elements we can then search sequentially for the one with the smallest index (that is greater than the one of the current number, if so required). Edit: It was pointed out that the algorithm may not be better than O(n²) because of the sequential search of the elements that satisfy the condition of being greater. This may be so, I'm not sure. But note that we may build a more complex search structure that involves the index already, somehow. This is left as homework. :)
64,872,442
I deployed a Rails application in Digital Ocean Ubuntu Server using Capistrano. For some reason the puma server suddenly stops. I'm not sure what's the reason. That's why I created a script **/home/deploy/startup-script.sh** the script contains the commands to startup the Rails application in daemon ``` #!/bin/bash echo "Running Puma Server" touch hello.txt cd /srv/www/apps/app/current bundle exec puma -C /srv/www/apps/app/shared/puma.rb --daemon ``` then I run this script every minute using Cron. My **crontab -e** contains ``` * * * * * ./startup-script.sh ``` After 1 minute I noticed that it created a hello.txt file but my puma server is not running. But when I run it manually using `./startup-script.sh` it will run the server. **puma\_error.log** ``` Puma starting in single mode... * Version 4.3.1 (ruby 2.6.0-p0), codename: Mysterious Traveller * Min threads: 0, max threads: 8 * Environment: production * Daemonizing... === puma startup: 2020-09-21 05:16:28 +0000 === === puma startup: 2020-09-21 05:17:39 +0000 === * Listening on tcp://0.0.0.0:9292 === puma startup: 2020-09-21 06:11:35 +0000 === - Gracefully stopping, waiting for requests to finish === puma shutdown: 2020-09-21 06:11:35 +0000 === ``` **production.log** ``` Item Load (0.3ms) SELECT "items".* FROM "items" WHERE "items"."id" = $1 LIMIT $2 [["id", 208], ["LIMIT", 1]] CACHE Unit Load (0.0ms) SELECT "units".* FROM "units" WHERE "units"."id" = $1 LIMIT $2 [["id", 4], ["LIMIT", 1]] Item Load (0.3ms) SELECT "items".* FROM "items" WHERE "items"."id" = $1 LIMIT $2 [["id", 215], ["LIMIT", 1]] CACHE Unit Load (0.0ms) SELECT "units".* FROM "units" WHERE "units"."id" = $1 LIMIT $2 [["id", 4], ["LIMIT", 1]] Item Load (0.2ms) SELECT "items".* FROM "items" WHERE "items"."id" = $1 LIMIT $2 [["id", 198], ["LIMIT", 1]] CACHE Unit Load (0.0ms) SELECT "units".* FROM "units" WHERE "units"."id" = $1 LIMIT $2 [["id", 10], ["LIMIT", 1]] Rendering text template Rendered text template (0.0ms) Sent data Delivery Receipt 12-2020-001.pdf (0.5ms) Completed 200 OK in 4326ms (Views: 0.3ms | ActiveRecord: 37.4ms) ``` **puma\_access.log** ``` === puma startup: 2020-12-01 01:07:13 +0000 === ``` When starting the `startup-script.sh` script I'm getting this ``` Running Puma Server Puma starting in single mode... * Version 4.3.1 (ruby 2.6.0-p0), codename: Mysterious Traveller * Min threads: 0, max threads: 8 * Environment: production * Daemonizing... ``` My droplet is still running but the puma running on port 9292 disappears when crashes, so I suspect this is puma error.
2020/11/17
[ "https://Stackoverflow.com/questions/64872442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1077711/" ]
I agree with OP that, the simple predicate of the O(N) algo might not work on the stack-based solution when looking for the first element > 2x in the remaining array. I found a O(NlogN) solution for this btw. It uses a **Min-heap** to maintain the frontier elements we are interested in. ### Pseudo-code: ``` def get_2x_elements(input_list, multipler = 2): H = [] #min-heap with node-values as tuples (index, value) R = [-1 for _ in range(len(input_list))] # results-list for index, value in enumerate(input_list): while multiplier*H[0][1] < value: minval = extractMinFromHeap(H) R[minval[0]] = value insertToMinHeap(H, (index, value)) return R ``` ### Complexity-analysis: ``` 1. Insertion/Extraction from min-heap = O(logN) 2. Number of such operations = N Total-complexity = O(NlogN) ``` PS: This assumes we need the `first >2x element` from the remaining part of the list. Re: I made a Java verion implementation of your idea. Thanks @Serial Lazer ```java private static class ValueAndIndexPair implements Comparable<ValueAndIndexPair>{ public final double value; public final int index; public ValueAndIndexPair(double value, int index) { this.value = value; this.index = index; } @Override public int compareTo(ValueAndIndexPair other) { return Double.compare(value, other.value); } } public static double[] returnNextNTimeLargerElementIndex(final List<Double> valueList, double multiplier) { double[] result = new double[valueList.size()]; PriorityQueue<ValueAndIndexPair> minHeap = new PriorityQueue<>(); // Initialize O(n) for (int i = 0; i < valueList.size(); i++) { result[i] = -1.0; } if (valueList.size() <= 1) return result; minHeap.add(new ValueAndIndexPair(valueList.get(0) * multiplier, 0)); for (int i = 1; i <valueList.size(); i++) { double currentElement = valueList.get(i); while (!minHeap.isEmpty() && minHeap.peek().value < currentElement) { result[minHeap.poll().index] = currentElement; } minHeap.add(new ValueAndIndexPair(currentElement * multiplier, i)); } return result; } ```
The stack-based solution [offered at geeksforgeeks](https://www.geeksforgeeks.org/next-greater-element/) does not seem to maintain the order of the elements in the result even in its output: ``` input: int arr[] = { 11, 13, 21, 3 }; output: 11 -- 13 13 -- 21 3 -- -1 21 -- -1 ``` After minor modification to find the first element which is greater N times than a current, this algorithm fails to detect 9 for the element 4 from the given example. [Online demo](https://ideone.com/SXM7j4) ``` input: int arr[] = { 2, 5, 4, 7, 3, 8, 9, 6 }; // as in this question output: 2 * 2 --> 5 2 * 3 --> 8 6 -- -1 9 -- -1 8 -- -1 7 -- -1 4 -- -1 5 -- -1 ``` Thus, initial assumption about existing solution with complexity O(N) is not quite applicable to the expected result.
29,578,436
I am new to Swift I am using MPMovieviewcontroller when i click next or previous button then no event occurs here is code ``` import UIKit import MediaPlayer class ViewController: UIViewController { var i : Int = 0 var movieplayer : MPMoviePlayerController! var arr = ["Akbar","Serial","ak"] override func viewDidLoad() { super.viewDidLoad() UIApplication.sharedApplication().beginReceivingRemoteControlEvents() self.becomeFirstResponder() startplaying() } override func canBecomeFirstResponder() -> Bool { return true } override func remoteControlReceivedWithEvent(event: UIEvent) { if event.subtype == UIEventSubtype.RemoteControlNextTrack { i++ startplaying() println(event.subtype) } } func startplaying() { if i <= 2 { let path = NSBundle.mainBundle().pathForResource(arr[i], ofType: "mov") let url = NSURL.fileURLWithPath(path!) movieplayer = MPMoviePlayerController(contentURL: url) } movieplayer.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height) movieplayer.view.sizeToFit() movieplayer.scalingMode = MPMovieScalingMode.AspectFill movieplayer.fullscreen = true movieplayer.controlStyle = MPMovieControlStyle.Fullscreen movieplayer.movieSourceType = MPMovieSourceType.File movieplayer.prepareToPlay() self.view.addSubview(movieplayer.view) } ``` When i debug this code then remoteControlReceivedWithEvent function did not execute I get donm help from [here](https://stackoverflow.com/questions/3593683/how-can-i-know-users-click-fast-forward-and-fast-rewind-buttons-on-the-playback)
2015/04/11
[ "https://Stackoverflow.com/questions/29578436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4741194/" ]
Try this ``` func startplaying() { if i <= 2 { let path = NSBundle.mainBundle().pathForResource(arr[i], ofType: "mov") let url = NSURL.fileURLWithPath(path!) movieplayer.contentURL = NSURL.fileURLWithPath(url) } ``` Read more: [Play MP4 using MPMoviePlayerController() in Swift](https://stackoverflow.com/questions/24350482/play-mp4-using-mpmovieplayercontroller-in-swift)
Here I do next/Previous Manully using button I hope it is proper way to next/previous operation ``` import UIKit import MediaPlayer class ViewController: UIViewController { var movieplayer : MPMoviePlayerController! var arr = ["ak","Serial","Akbar"] var i = 0 override func viewDidLoad() { super.viewDidLoad() startplaying() } @IBOutlet var views: UIView! var flag = 0 @IBOutlet var next: UIButton! @IBOutlet var pre: UIButton! @IBOutlet var play: UIButton! func startplaying() { if i >= 0 && i <= 2 { let path = NSBundle.mainBundle().pathForResource(arr[i], ofType: "mov") let url = NSURL.fileURLWithPath(path!) movieplayer = MPMoviePlayerController(contentURL: url) movieplayer.view.frame = CGRect(x: 0, y: 0, width: 320, height: 450) movieplayer.view.sizeToFit() movieplayer.scalingMode = MPMovieScalingMode.AspectFill movieplayer.fullscreen = true movieplayer.controlStyle = MPMovieControlStyle.Embedded movieplayer.movieSourceType = MPMovieSourceType.File movieplayer.repeatMode = MPMovieRepeatMode.One movieplayer.prepareToPlay() // self.view.addSubview(movieplayer.view) self.views.addSubview(movieplayer.view) } else { println("No Video Avaliable") movieplayer.stop() } } @IBAction func Previous(sender: AnyObject) { if i >= 0 { i-- startplaying() } else { println("No Video Avaliable") movieplayer.stop() } } @IBAction func Pause(sender: AnyObject) { if flag == 0 { play.setTitle("Pause", forState: UIControlState.Normal) movieplayer.pause() flag = 1 } else { play.setTitle("Play", forState: UIControlState.Normal) movieplayer.play() flag = 0 } } @IBAction func next(sender: AnyObject) { if i <= 2 { i++ startplaying() } else { println("No Video Avaliable") movieplayer.stop() } } ```
15,700,850
I am having some trouble finding a solution in mySQL, I have 2 tables where in the one I have my images and in the other I have my votes and image\_id that I bind together using this line: ``` $sql = "SELECT `image` FROM `sh_images`, `sh_votes` WHERE `sh_images`.`id`=`sh_votes`.`image_id` ORDER BY `vote` DESC"; ``` Everything works fine except that the images that aren't voted yet aren't showing. So do you have a solution for me?
2013/03/29
[ "https://Stackoverflow.com/questions/15700850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2223874/" ]
You should be using `LEFT JOIN` on this. `LEFT JOIN` is different from `INNER JOIN` (*which is what you are doing right now*). `LEFT JOIN` displays all the records define on the *LeftHand side* whether it has a matching record or none on the *RightHand side* table on the result. ``` SELECT image, vote FROM sh_images LEFT JOIN sh_votes ON sh_images.id = sh_votes.image_id ORDER BY vote DESC ``` * [SQLFiddle Demo](http://www.sqlfiddle.com/#!2/747ce/3) To further gain more knowledge about joins, kindly visit the link below: * [Visual Representation of SQL Joins](http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html)
Sure, just use a LEFT JOIN: ``` SELECT image FROM sh_images LEFT JOIN sh_votes ON sh_images.id=sh_votes.image_id ORDER BY vote DESC; ``` Btw, consider using `INNER JOIN` syntax for your straight joins, it's easier to prevent a missing join condition that way.
31,470,858
I have two variables `@date` of type `datetime` and `@time` of type `time`. I want to add both to get another `datetime` variable. And I want to perform further calculations on it. Ex: ``` Declare @date datetime Declare @time time ``` I want something like this ``` @date = @date + @time (but not concatenation) SELECT @Startdate = DATEADD(DAY, -1, @date ) ``` Is there any way?
2015/07/17
[ "https://Stackoverflow.com/questions/31470858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2045931/" ]
You can tranform your time to seconds and add them to your datetime value: ``` DECLARE @datetime DATETIME = GETDATE(), @time TIME = '01:16:24', @timeinseconds INT PRINT 'we add ' + CAST(@time AS VARCHAR(8)) + ' to ' + CONVERT(VARCHAR,@datetime,120)+ ':' SELECT @timeinseconds = DATEPART(SECOND, @time) + DATEPART(MINUTE, @time) * 60 + DATEPART(HOUR, @time) * 3600 SET @datetime = DATEADD(SECOND,@timeinseconds,@datetime) PRINT 'The result is: ' + CONVERT(VARCHAR,@datetime,120) ``` Output: ``` we add 01:16:24 to 2015-07-17 09:58:45: The result is: 2015-07-17 11:15:09 ```
Your code is correct. ``` DECLARE @date DATETIME = '1/1/2020' DECLARE @time TIME = '1:00 pm' DECLARE @Startdate DATETIME SET @date = @date + @time SELECT @Startdate = DATEADD(DAY, -1, @date) @date = 2020-01-01 13:00:00.000 @Startdate = 2019-12-31 13:00:00.000 ``` It isn't concatenating, it is adding them together. The time on @date is 0:00:00.000, so it might appear to be concatenating them. But change @date to '1/1/2020 1:00 am' and then: ``` @date = 2020-01-01 14:00:00.000 @Startdate = 2019-12-31 14:00:00.000 ```
31,470,858
I have two variables `@date` of type `datetime` and `@time` of type `time`. I want to add both to get another `datetime` variable. And I want to perform further calculations on it. Ex: ``` Declare @date datetime Declare @time time ``` I want something like this ``` @date = @date + @time (but not concatenation) SELECT @Startdate = DATEADD(DAY, -1, @date ) ``` Is there any way?
2015/07/17
[ "https://Stackoverflow.com/questions/31470858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2045931/" ]
The only thing you are missing is that @time needs to be cast back to a datetime before adding to @date. ``` declare @date datetime = '2022-05-26' declare @time time = '09:52:14' declare @Startdate datetime set @date = @date + convert(datetime,@time) SELECT @Startdate = DATEADD(DAY, -1, @date) ``` Produces: [![enter image description here](https://i.stack.imgur.com/gp3eh.png)](https://i.stack.imgur.com/gp3eh.png)
I'm not sure what's going on here, but if your variables are datetime and time types, this should work just fine: ``` declare @date datetime declare @time time set @date = '20150717' set @time = '12:34:56' set @date = @date + @time select @date, DATEADD(DAY,-1,@date) ``` See [SQL Fiddle](http://sqlfiddle.com/#!3/9eecb7/1978) If the problem is that @date contains also time part, you can use: ``` set @date = convert(datetime, convert(date, @date)) + @time ```
31,470,858
I have two variables `@date` of type `datetime` and `@time` of type `time`. I want to add both to get another `datetime` variable. And I want to perform further calculations on it. Ex: ``` Declare @date datetime Declare @time time ``` I want something like this ``` @date = @date + @time (but not concatenation) SELECT @Startdate = DATEADD(DAY, -1, @date ) ``` Is there any way?
2015/07/17
[ "https://Stackoverflow.com/questions/31470858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2045931/" ]
If you need to take only date part from `@date` and time part from `@time` - can convert your `@date` and `@time` to strings, concatenate the values and convert back to datetime: ``` select cast(convert(nvarchar(20), @date, 104) + ' ' + convert(nvarchar(20), @time, 108) as datetime2) ``` Or, alternatively, if you need to add time to datetime value, you can do something like: ``` select dateadd(ms, datepart(ms, @time), dateadd(ss, datepart(ss, @time), dateadd(mi, datepart(mi, @time), dateadd(hh, datepart(hh, @time), @date)))) ```
I'm not sure what's going on here, but if your variables are datetime and time types, this should work just fine: ``` declare @date datetime declare @time time set @date = '20150717' set @time = '12:34:56' set @date = @date + @time select @date, DATEADD(DAY,-1,@date) ``` See [SQL Fiddle](http://sqlfiddle.com/#!3/9eecb7/1978) If the problem is that @date contains also time part, you can use: ``` set @date = convert(datetime, convert(date, @date)) + @time ```
31,470,858
I have two variables `@date` of type `datetime` and `@time` of type `time`. I want to add both to get another `datetime` variable. And I want to perform further calculations on it. Ex: ``` Declare @date datetime Declare @time time ``` I want something like this ``` @date = @date + @time (but not concatenation) SELECT @Startdate = DATEADD(DAY, -1, @date ) ``` Is there any way?
2015/07/17
[ "https://Stackoverflow.com/questions/31470858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2045931/" ]
First of all convert `@date` and `@time` variables to `NVARCHAR()`, then concat them and after It convert It to `DATETIME` datatype. After It you can use `DATEADD` function on It. Try in following: ``` DECLARE @date DATETIME DECLARE @time TIME SET @date = GETDATE() SET @time = '10:12:13' SELECT DATEADD(DAY, -1, CAST(CONVERT(NVARCHAR(20), @date, 110) + ' ' + CONVERT(NVARCHAR(20), @time, 108) AS DATETIME)) ``` **OUTPUT** (*Today day -1 + time '10:12:13'*): ``` 2015-07-16 10:12:13.000 ```
Your code is correct. ``` DECLARE @date DATETIME = '1/1/2020' DECLARE @time TIME = '1:00 pm' DECLARE @Startdate DATETIME SET @date = @date + @time SELECT @Startdate = DATEADD(DAY, -1, @date) @date = 2020-01-01 13:00:00.000 @Startdate = 2019-12-31 13:00:00.000 ``` It isn't concatenating, it is adding them together. The time on @date is 0:00:00.000, so it might appear to be concatenating them. But change @date to '1/1/2020 1:00 am' and then: ``` @date = 2020-01-01 14:00:00.000 @Startdate = 2019-12-31 14:00:00.000 ```
31,470,858
I have two variables `@date` of type `datetime` and `@time` of type `time`. I want to add both to get another `datetime` variable. And I want to perform further calculations on it. Ex: ``` Declare @date datetime Declare @time time ``` I want something like this ``` @date = @date + @time (but not concatenation) SELECT @Startdate = DATEADD(DAY, -1, @date ) ``` Is there any way?
2015/07/17
[ "https://Stackoverflow.com/questions/31470858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2045931/" ]
You can tranform your time to seconds and add them to your datetime value: ``` DECLARE @datetime DATETIME = GETDATE(), @time TIME = '01:16:24', @timeinseconds INT PRINT 'we add ' + CAST(@time AS VARCHAR(8)) + ' to ' + CONVERT(VARCHAR,@datetime,120)+ ':' SELECT @timeinseconds = DATEPART(SECOND, @time) + DATEPART(MINUTE, @time) * 60 + DATEPART(HOUR, @time) * 3600 SET @datetime = DATEADD(SECOND,@timeinseconds,@datetime) PRINT 'The result is: ' + CONVERT(VARCHAR,@datetime,120) ``` Output: ``` we add 01:16:24 to 2015-07-17 09:58:45: The result is: 2015-07-17 11:15:09 ```
First of all convert `@date` and `@time` variables to `NVARCHAR()`, then concat them and after It convert It to `DATETIME` datatype. After It you can use `DATEADD` function on It. Try in following: ``` DECLARE @date DATETIME DECLARE @time TIME SET @date = GETDATE() SET @time = '10:12:13' SELECT DATEADD(DAY, -1, CAST(CONVERT(NVARCHAR(20), @date, 110) + ' ' + CONVERT(NVARCHAR(20), @time, 108) AS DATETIME)) ``` **OUTPUT** (*Today day -1 + time '10:12:13'*): ``` 2015-07-16 10:12:13.000 ```
31,470,858
I have two variables `@date` of type `datetime` and `@time` of type `time`. I want to add both to get another `datetime` variable. And I want to perform further calculations on it. Ex: ``` Declare @date datetime Declare @time time ``` I want something like this ``` @date = @date + @time (but not concatenation) SELECT @Startdate = DATEADD(DAY, -1, @date ) ``` Is there any way?
2015/07/17
[ "https://Stackoverflow.com/questions/31470858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2045931/" ]
You can tranform your time to seconds and add them to your datetime value: ``` DECLARE @datetime DATETIME = GETDATE(), @time TIME = '01:16:24', @timeinseconds INT PRINT 'we add ' + CAST(@time AS VARCHAR(8)) + ' to ' + CONVERT(VARCHAR,@datetime,120)+ ':' SELECT @timeinseconds = DATEPART(SECOND, @time) + DATEPART(MINUTE, @time) * 60 + DATEPART(HOUR, @time) * 3600 SET @datetime = DATEADD(SECOND,@timeinseconds,@datetime) PRINT 'The result is: ' + CONVERT(VARCHAR,@datetime,120) ``` Output: ``` we add 01:16:24 to 2015-07-17 09:58:45: The result is: 2015-07-17 11:15:09 ```
If you need to take only date part from `@date` and time part from `@time` - can convert your `@date` and `@time` to strings, concatenate the values and convert back to datetime: ``` select cast(convert(nvarchar(20), @date, 104) + ' ' + convert(nvarchar(20), @time, 108) as datetime2) ``` Or, alternatively, if you need to add time to datetime value, you can do something like: ``` select dateadd(ms, datepart(ms, @time), dateadd(ss, datepart(ss, @time), dateadd(mi, datepart(mi, @time), dateadd(hh, datepart(hh, @time), @date)))) ```
31,470,858
I have two variables `@date` of type `datetime` and `@time` of type `time`. I want to add both to get another `datetime` variable. And I want to perform further calculations on it. Ex: ``` Declare @date datetime Declare @time time ``` I want something like this ``` @date = @date + @time (but not concatenation) SELECT @Startdate = DATEADD(DAY, -1, @date ) ``` Is there any way?
2015/07/17
[ "https://Stackoverflow.com/questions/31470858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2045931/" ]
If you need to take only date part from `@date` and time part from `@time` - can convert your `@date` and `@time` to strings, concatenate the values and convert back to datetime: ``` select cast(convert(nvarchar(20), @date, 104) + ' ' + convert(nvarchar(20), @time, 108) as datetime2) ``` Or, alternatively, if you need to add time to datetime value, you can do something like: ``` select dateadd(ms, datepart(ms, @time), dateadd(ss, datepart(ss, @time), dateadd(mi, datepart(mi, @time), dateadd(hh, datepart(hh, @time), @date)))) ```
Your code is correct. ``` DECLARE @date DATETIME = '1/1/2020' DECLARE @time TIME = '1:00 pm' DECLARE @Startdate DATETIME SET @date = @date + @time SELECT @Startdate = DATEADD(DAY, -1, @date) @date = 2020-01-01 13:00:00.000 @Startdate = 2019-12-31 13:00:00.000 ``` It isn't concatenating, it is adding them together. The time on @date is 0:00:00.000, so it might appear to be concatenating them. But change @date to '1/1/2020 1:00 am' and then: ``` @date = 2020-01-01 14:00:00.000 @Startdate = 2019-12-31 14:00:00.000 ```
31,470,858
I have two variables `@date` of type `datetime` and `@time` of type `time`. I want to add both to get another `datetime` variable. And I want to perform further calculations on it. Ex: ``` Declare @date datetime Declare @time time ``` I want something like this ``` @date = @date + @time (but not concatenation) SELECT @Startdate = DATEADD(DAY, -1, @date ) ``` Is there any way?
2015/07/17
[ "https://Stackoverflow.com/questions/31470858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2045931/" ]
The only thing you are missing is that @time needs to be cast back to a datetime before adding to @date. ``` declare @date datetime = '2022-05-26' declare @time time = '09:52:14' declare @Startdate datetime set @date = @date + convert(datetime,@time) SELECT @Startdate = DATEADD(DAY, -1, @date) ``` Produces: [![enter image description here](https://i.stack.imgur.com/gp3eh.png)](https://i.stack.imgur.com/gp3eh.png)
Your code is correct. ``` DECLARE @date DATETIME = '1/1/2020' DECLARE @time TIME = '1:00 pm' DECLARE @Startdate DATETIME SET @date = @date + @time SELECT @Startdate = DATEADD(DAY, -1, @date) @date = 2020-01-01 13:00:00.000 @Startdate = 2019-12-31 13:00:00.000 ``` It isn't concatenating, it is adding them together. The time on @date is 0:00:00.000, so it might appear to be concatenating them. But change @date to '1/1/2020 1:00 am' and then: ``` @date = 2020-01-01 14:00:00.000 @Startdate = 2019-12-31 14:00:00.000 ```
31,470,858
I have two variables `@date` of type `datetime` and `@time` of type `time`. I want to add both to get another `datetime` variable. And I want to perform further calculations on it. Ex: ``` Declare @date datetime Declare @time time ``` I want something like this ``` @date = @date + @time (but not concatenation) SELECT @Startdate = DATEADD(DAY, -1, @date ) ``` Is there any way?
2015/07/17
[ "https://Stackoverflow.com/questions/31470858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2045931/" ]
First of all convert `@date` and `@time` variables to `NVARCHAR()`, then concat them and after It convert It to `DATETIME` datatype. After It you can use `DATEADD` function on It. Try in following: ``` DECLARE @date DATETIME DECLARE @time TIME SET @date = GETDATE() SET @time = '10:12:13' SELECT DATEADD(DAY, -1, CAST(CONVERT(NVARCHAR(20), @date, 110) + ' ' + CONVERT(NVARCHAR(20), @time, 108) AS DATETIME)) ``` **OUTPUT** (*Today day -1 + time '10:12:13'*): ``` 2015-07-16 10:12:13.000 ```
I'm not sure what's going on here, but if your variables are datetime and time types, this should work just fine: ``` declare @date datetime declare @time time set @date = '20150717' set @time = '12:34:56' set @date = @date + @time select @date, DATEADD(DAY,-1,@date) ``` See [SQL Fiddle](http://sqlfiddle.com/#!3/9eecb7/1978) If the problem is that @date contains also time part, you can use: ``` set @date = convert(datetime, convert(date, @date)) + @time ```
31,470,858
I have two variables `@date` of type `datetime` and `@time` of type `time`. I want to add both to get another `datetime` variable. And I want to perform further calculations on it. Ex: ``` Declare @date datetime Declare @time time ``` I want something like this ``` @date = @date + @time (but not concatenation) SELECT @Startdate = DATEADD(DAY, -1, @date ) ``` Is there any way?
2015/07/17
[ "https://Stackoverflow.com/questions/31470858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2045931/" ]
The only thing you are missing is that @time needs to be cast back to a datetime before adding to @date. ``` declare @date datetime = '2022-05-26' declare @time time = '09:52:14' declare @Startdate datetime set @date = @date + convert(datetime,@time) SELECT @Startdate = DATEADD(DAY, -1, @date) ``` Produces: [![enter image description here](https://i.stack.imgur.com/gp3eh.png)](https://i.stack.imgur.com/gp3eh.png)
First of all convert `@date` and `@time` variables to `NVARCHAR()`, then concat them and after It convert It to `DATETIME` datatype. After It you can use `DATEADD` function on It. Try in following: ``` DECLARE @date DATETIME DECLARE @time TIME SET @date = GETDATE() SET @time = '10:12:13' SELECT DATEADD(DAY, -1, CAST(CONVERT(NVARCHAR(20), @date, 110) + ' ' + CONVERT(NVARCHAR(20), @time, 108) AS DATETIME)) ``` **OUTPUT** (*Today day -1 + time '10:12:13'*): ``` 2015-07-16 10:12:13.000 ```
210,792
I don't know if it's heartless,but when I'm in a situation that is really sad(like a funeral) I always have this urge to laugh.Of course I try not to burst out in laughter but I guess it's how I cope with these things. Is there a word that can describe this?I don't mind if it would be used for the urge,the behaviour,the feeling.I'm just really interested how to express this kind of thing without having to say that I really,really have to laugh.
2014/11/28
[ "https://english.stackexchange.com/questions/210792", "https://english.stackexchange.com", "https://english.stackexchange.com/users/99370/" ]
**Nervous-laughter** should be a appropriate word. And in a novel I read a word **painful-dimples**, It sounds compatible too. But `painful-dimples` kind of word is not heard or seen usually.
I'd describe that as a fit of [hysterical](http://dictionary.reference.com/browse/hysterical) laughter : Hysterical: > > * uncontrollably emotional. > * irrational from fear, emotion, or an emotional shock. > > > ( from dictionary.reference.com)
210,792
I don't know if it's heartless,but when I'm in a situation that is really sad(like a funeral) I always have this urge to laugh.Of course I try not to burst out in laughter but I guess it's how I cope with these things. Is there a word that can describe this?I don't mind if it would be used for the urge,the behaviour,the feeling.I'm just really interested how to express this kind of thing without having to say that I really,really have to laugh.
2014/11/28
[ "https://english.stackexchange.com/questions/210792", "https://english.stackexchange.com", "https://english.stackexchange.com/users/99370/" ]
**Nervous-laughter** should be a appropriate word. And in a novel I read a word **painful-dimples**, It sounds compatible too. But `painful-dimples` kind of word is not heard or seen usually.
The psychological term is "inappropriate affect". Not to make you nervous... but, it can be an indicator of pathology.
210,792
I don't know if it's heartless,but when I'm in a situation that is really sad(like a funeral) I always have this urge to laugh.Of course I try not to burst out in laughter but I guess it's how I cope with these things. Is there a word that can describe this?I don't mind if it would be used for the urge,the behaviour,the feeling.I'm just really interested how to express this kind of thing without having to say that I really,really have to laugh.
2014/11/28
[ "https://english.stackexchange.com/questions/210792", "https://english.stackexchange.com", "https://english.stackexchange.com/users/99370/" ]
**Nervous-laughter** should be a appropriate word. And in a novel I read a word **painful-dimples**, It sounds compatible too. But `painful-dimples` kind of word is not heard or seen usually.
Titter to laugh nervously, often at something that you feel you should not be laughing at.
210,792
I don't know if it's heartless,but when I'm in a situation that is really sad(like a funeral) I always have this urge to laugh.Of course I try not to burst out in laughter but I guess it's how I cope with these things. Is there a word that can describe this?I don't mind if it would be used for the urge,the behaviour,the feeling.I'm just really interested how to express this kind of thing without having to say that I really,really have to laugh.
2014/11/28
[ "https://english.stackexchange.com/questions/210792", "https://english.stackexchange.com", "https://english.stackexchange.com/users/99370/" ]
**Nervous-laughter** should be a appropriate word. And in a novel I read a word **painful-dimples**, It sounds compatible too. But `painful-dimples` kind of word is not heard or seen usually.
Laughter is a highly complex behavior. One term for what you describe might be *nervous laughter* (if you actually laughed instead of just felt the urge to laugh). But that term is used in various ways, so as far as I know, the best way to describe it is similar to what you did in the question.
210,792
I don't know if it's heartless,but when I'm in a situation that is really sad(like a funeral) I always have this urge to laugh.Of course I try not to burst out in laughter but I guess it's how I cope with these things. Is there a word that can describe this?I don't mind if it would be used for the urge,the behaviour,the feeling.I'm just really interested how to express this kind of thing without having to say that I really,really have to laugh.
2014/11/28
[ "https://english.stackexchange.com/questions/210792", "https://english.stackexchange.com", "https://english.stackexchange.com/users/99370/" ]
The psychological term is "inappropriate affect". Not to make you nervous... but, it can be an indicator of pathology.
I'd describe that as a fit of [hysterical](http://dictionary.reference.com/browse/hysterical) laughter : Hysterical: > > * uncontrollably emotional. > * irrational from fear, emotion, or an emotional shock. > > > ( from dictionary.reference.com)
210,792
I don't know if it's heartless,but when I'm in a situation that is really sad(like a funeral) I always have this urge to laugh.Of course I try not to burst out in laughter but I guess it's how I cope with these things. Is there a word that can describe this?I don't mind if it would be used for the urge,the behaviour,the feeling.I'm just really interested how to express this kind of thing without having to say that I really,really have to laugh.
2014/11/28
[ "https://english.stackexchange.com/questions/210792", "https://english.stackexchange.com", "https://english.stackexchange.com/users/99370/" ]
I'd describe that as a fit of [hysterical](http://dictionary.reference.com/browse/hysterical) laughter : Hysterical: > > * uncontrollably emotional. > * irrational from fear, emotion, or an emotional shock. > > > ( from dictionary.reference.com)
Titter to laugh nervously, often at something that you feel you should not be laughing at.
210,792
I don't know if it's heartless,but when I'm in a situation that is really sad(like a funeral) I always have this urge to laugh.Of course I try not to burst out in laughter but I guess it's how I cope with these things. Is there a word that can describe this?I don't mind if it would be used for the urge,the behaviour,the feeling.I'm just really interested how to express this kind of thing without having to say that I really,really have to laugh.
2014/11/28
[ "https://english.stackexchange.com/questions/210792", "https://english.stackexchange.com", "https://english.stackexchange.com/users/99370/" ]
I'd describe that as a fit of [hysterical](http://dictionary.reference.com/browse/hysterical) laughter : Hysterical: > > * uncontrollably emotional. > * irrational from fear, emotion, or an emotional shock. > > > ( from dictionary.reference.com)
Laughter is a highly complex behavior. One term for what you describe might be *nervous laughter* (if you actually laughed instead of just felt the urge to laugh). But that term is used in various ways, so as far as I know, the best way to describe it is similar to what you did in the question.
210,792
I don't know if it's heartless,but when I'm in a situation that is really sad(like a funeral) I always have this urge to laugh.Of course I try not to burst out in laughter but I guess it's how I cope with these things. Is there a word that can describe this?I don't mind if it would be used for the urge,the behaviour,the feeling.I'm just really interested how to express this kind of thing without having to say that I really,really have to laugh.
2014/11/28
[ "https://english.stackexchange.com/questions/210792", "https://english.stackexchange.com", "https://english.stackexchange.com/users/99370/" ]
The psychological term is "inappropriate affect". Not to make you nervous... but, it can be an indicator of pathology.
Titter to laugh nervously, often at something that you feel you should not be laughing at.
210,792
I don't know if it's heartless,but when I'm in a situation that is really sad(like a funeral) I always have this urge to laugh.Of course I try not to burst out in laughter but I guess it's how I cope with these things. Is there a word that can describe this?I don't mind if it would be used for the urge,the behaviour,the feeling.I'm just really interested how to express this kind of thing without having to say that I really,really have to laugh.
2014/11/28
[ "https://english.stackexchange.com/questions/210792", "https://english.stackexchange.com", "https://english.stackexchange.com/users/99370/" ]
The psychological term is "inappropriate affect". Not to make you nervous... but, it can be an indicator of pathology.
Laughter is a highly complex behavior. One term for what you describe might be *nervous laughter* (if you actually laughed instead of just felt the urge to laugh). But that term is used in various ways, so as far as I know, the best way to describe it is similar to what you did in the question.
4,587,392
Is it possible to create an instance of an interface in Java? Somewhere I have read that using inner anonymous class we can do it as shown below: ```java interface Test { public void wish(); } class Main { public static void main(String[] args) { Test t = new Test() { public void wish() { System.out.println("output: hello how r u"); } }; t.wish(); } } ``` ```none cmd> javac Main.java cmd> java Main output: hello how r u ``` Is it correct here?
2011/01/03
[ "https://Stackoverflow.com/questions/4587392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547709/" ]
No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.
Yes it is correct. you can do it with an inner class.
4,587,392
Is it possible to create an instance of an interface in Java? Somewhere I have read that using inner anonymous class we can do it as shown below: ```java interface Test { public void wish(); } class Main { public static void main(String[] args) { Test t = new Test() { public void wish() { System.out.println("output: hello how r u"); } }; t.wish(); } } ``` ```none cmd> javac Main.java cmd> java Main output: hello how r u ``` Is it correct here?
2011/01/03
[ "https://Stackoverflow.com/questions/4587392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547709/" ]
Normaly, you can create a reference for an interface. But you cant create an instance for interface.
Yes it is correct. you can do it with an inner class.
4,587,392
Is it possible to create an instance of an interface in Java? Somewhere I have read that using inner anonymous class we can do it as shown below: ```java interface Test { public void wish(); } class Main { public static void main(String[] args) { Test t = new Test() { public void wish() { System.out.println("output: hello how r u"); } }; t.wish(); } } ``` ```none cmd> javac Main.java cmd> java Main output: hello how r u ``` Is it correct here?
2011/01/03
[ "https://Stackoverflow.com/questions/4587392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547709/" ]
Normaly, you can create a reference for an interface. But you cant create an instance for interface.
Short answer...yes. You can use an anonymous class when you initialize a variable. Take a look at this question: [Anonymous vs named inner classes? - best practices?](https://stackoverflow.com/q/714602)
4,587,392
Is it possible to create an instance of an interface in Java? Somewhere I have read that using inner anonymous class we can do it as shown below: ```java interface Test { public void wish(); } class Main { public static void main(String[] args) { Test t = new Test() { public void wish() { System.out.println("output: hello how r u"); } }; t.wish(); } } ``` ```none cmd> javac Main.java cmd> java Main output: hello how r u ``` Is it correct here?
2011/01/03
[ "https://Stackoverflow.com/questions/4587392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547709/" ]
Yes, your example is correct. Anonymous classes can implement interfaces, and that's the only time I can think of that you'll see a class implementing an interface without the "implements" keyword. Check out another code sample right here: ```java interface ProgrammerInterview { public void read(); } class Website { ProgrammerInterview p = new ProgrammerInterview() { public void read() { System.out.println("interface ProgrammerInterview class implementer"); } }; } ``` This works fine. Was taken from this page: <http://www.programmerinterview.com/index.php/java-questions/anonymous-class-interface/>
No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.
4,587,392
Is it possible to create an instance of an interface in Java? Somewhere I have read that using inner anonymous class we can do it as shown below: ```java interface Test { public void wish(); } class Main { public static void main(String[] args) { Test t = new Test() { public void wish() { System.out.println("output: hello how r u"); } }; t.wish(); } } ``` ```none cmd> javac Main.java cmd> java Main output: hello how r u ``` Is it correct here?
2011/01/03
[ "https://Stackoverflow.com/questions/4587392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547709/" ]
You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example, ``` public interface A { } public class B implements A { } public static void main(String[] args) { A test = new B(); //A test = new A(); // wont compile } ``` What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type `interface Test`.
Yes it is correct. you can do it with an inner class.
4,587,392
Is it possible to create an instance of an interface in Java? Somewhere I have read that using inner anonymous class we can do it as shown below: ```java interface Test { public void wish(); } class Main { public static void main(String[] args) { Test t = new Test() { public void wish() { System.out.println("output: hello how r u"); } }; t.wish(); } } ``` ```none cmd> javac Main.java cmd> java Main output: hello how r u ``` Is it correct here?
2011/01/03
[ "https://Stackoverflow.com/questions/4587392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547709/" ]
Short answer...yes. You can use an anonymous class when you initialize a variable. Take a look at this question: [Anonymous vs named inner classes? - best practices?](https://stackoverflow.com/q/714602)
Yes we can, "Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name"-[>>Java Doc](http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html)
4,587,392
Is it possible to create an instance of an interface in Java? Somewhere I have read that using inner anonymous class we can do it as shown below: ```java interface Test { public void wish(); } class Main { public static void main(String[] args) { Test t = new Test() { public void wish() { System.out.println("output: hello how r u"); } }; t.wish(); } } ``` ```none cmd> javac Main.java cmd> java Main output: hello how r u ``` Is it correct here?
2011/01/03
[ "https://Stackoverflow.com/questions/4587392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547709/" ]
You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example, ``` public interface A { } public class B implements A { } public static void main(String[] args) { A test = new B(); //A test = new A(); // wont compile } ``` What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type `interface Test`.
Yes we can, "Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name"-[>>Java Doc](http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html)
4,587,392
Is it possible to create an instance of an interface in Java? Somewhere I have read that using inner anonymous class we can do it as shown below: ```java interface Test { public void wish(); } class Main { public static void main(String[] args) { Test t = new Test() { public void wish() { System.out.println("output: hello how r u"); } }; t.wish(); } } ``` ```none cmd> javac Main.java cmd> java Main output: hello how r u ``` Is it correct here?
2011/01/03
[ "https://Stackoverflow.com/questions/4587392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547709/" ]
No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.
Yes we can, "Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name"-[>>Java Doc](http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html)
4,587,392
Is it possible to create an instance of an interface in Java? Somewhere I have read that using inner anonymous class we can do it as shown below: ```java interface Test { public void wish(); } class Main { public static void main(String[] args) { Test t = new Test() { public void wish() { System.out.println("output: hello how r u"); } }; t.wish(); } } ``` ```none cmd> javac Main.java cmd> java Main output: hello how r u ``` Is it correct here?
2011/01/03
[ "https://Stackoverflow.com/questions/4587392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547709/" ]
You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example, ``` public interface A { } public class B implements A { } public static void main(String[] args) { A test = new B(); //A test = new A(); // wont compile } ``` What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type `interface Test`.
Normaly, you can create a reference for an interface. But you cant create an instance for interface.
4,587,392
Is it possible to create an instance of an interface in Java? Somewhere I have read that using inner anonymous class we can do it as shown below: ```java interface Test { public void wish(); } class Main { public static void main(String[] args) { Test t = new Test() { public void wish() { System.out.println("output: hello how r u"); } }; t.wish(); } } ``` ```none cmd> javac Main.java cmd> java Main output: hello how r u ``` Is it correct here?
2011/01/03
[ "https://Stackoverflow.com/questions/4587392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547709/" ]
Normaly, you can create a reference for an interface. But you cant create an instance for interface.
Yes we can, "Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name"-[>>Java Doc](http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html)
1,053,217
Hey I would like to know the correct approach to this problem. I think I'm close but I'm confusing myself. How many sets of size five are there from the natural numbers 1-100 that contain exactly two odd numbers? First we would select 2 odd numbers (50 choose 2) Then sum it with (50 choose 3)? For the even #s?
2014/12/05
[ "https://math.stackexchange.com/questions/1053217", "https://math.stackexchange.com", "https://math.stackexchange.com/users/197861/" ]
Not sum it, multiply it. This is because for **every way** of choosing the odds, there are $\binom{50}{3}$ ways to choose the evens.
Rule of product, not rule of sum. We choose our even numbers independently of the odd numbers. So $\binom{50}{2} \binom{50}{3}$. Note the rule of sum is for disjoint cases (ie., partitioning the elements you are counting). Consider a smaller example- one even number and one odd number from $\{1, ..., 6\}$. So we can have: $(1, 2), (1, 4), (1, 6)$. We then apply the same pairs for $3, 5$. This gives us $9$ pairs, which is: $\binom{3}{1} \binom{3}{1}$, not $\binom{3}{1} + \binom{3}{1}$.
1,053,217
Hey I would like to know the correct approach to this problem. I think I'm close but I'm confusing myself. How many sets of size five are there from the natural numbers 1-100 that contain exactly two odd numbers? First we would select 2 odd numbers (50 choose 2) Then sum it with (50 choose 3)? For the even #s?
2014/12/05
[ "https://math.stackexchange.com/questions/1053217", "https://math.stackexchange.com", "https://math.stackexchange.com/users/197861/" ]
Not sum it, multiply it. This is because for **every way** of choosing the odds, there are $\binom{50}{3}$ ways to choose the evens.
We want a set of size $5$, with $2$ odd numbers *and* $3$ even numbers. Converting this into math lingo, we get $\binom{50}{2} \cdot \binom{50}{3}$, and not their sum because we want both and not one or the other.
1,053,217
Hey I would like to know the correct approach to this problem. I think I'm close but I'm confusing myself. How many sets of size five are there from the natural numbers 1-100 that contain exactly two odd numbers? First we would select 2 odd numbers (50 choose 2) Then sum it with (50 choose 3)? For the even #s?
2014/12/05
[ "https://math.stackexchange.com/questions/1053217", "https://math.stackexchange.com", "https://math.stackexchange.com/users/197861/" ]
Not sum it, multiply it. This is because for **every way** of choosing the odds, there are $\binom{50}{3}$ ways to choose the evens.
Choose 2 odd numbers from 50 : $\binom{50}{2}$ For each of these choices, you can choose 3 even numbers from the 50 even numbers : $\binom{50}{3}$ Thus it should be $\binom{50}{2}.\binom{50}{3}$
1,053,217
Hey I would like to know the correct approach to this problem. I think I'm close but I'm confusing myself. How many sets of size five are there from the natural numbers 1-100 that contain exactly two odd numbers? First we would select 2 odd numbers (50 choose 2) Then sum it with (50 choose 3)? For the even #s?
2014/12/05
[ "https://math.stackexchange.com/questions/1053217", "https://math.stackexchange.com", "https://math.stackexchange.com/users/197861/" ]
Rule of product, not rule of sum. We choose our even numbers independently of the odd numbers. So $\binom{50}{2} \binom{50}{3}$. Note the rule of sum is for disjoint cases (ie., partitioning the elements you are counting). Consider a smaller example- one even number and one odd number from $\{1, ..., 6\}$. So we can have: $(1, 2), (1, 4), (1, 6)$. We then apply the same pairs for $3, 5$. This gives us $9$ pairs, which is: $\binom{3}{1} \binom{3}{1}$, not $\binom{3}{1} + \binom{3}{1}$.
We want a set of size $5$, with $2$ odd numbers *and* $3$ even numbers. Converting this into math lingo, we get $\binom{50}{2} \cdot \binom{50}{3}$, and not their sum because we want both and not one or the other.
1,053,217
Hey I would like to know the correct approach to this problem. I think I'm close but I'm confusing myself. How many sets of size five are there from the natural numbers 1-100 that contain exactly two odd numbers? First we would select 2 odd numbers (50 choose 2) Then sum it with (50 choose 3)? For the even #s?
2014/12/05
[ "https://math.stackexchange.com/questions/1053217", "https://math.stackexchange.com", "https://math.stackexchange.com/users/197861/" ]
Choose 2 odd numbers from 50 : $\binom{50}{2}$ For each of these choices, you can choose 3 even numbers from the 50 even numbers : $\binom{50}{3}$ Thus it should be $\binom{50}{2}.\binom{50}{3}$
We want a set of size $5$, with $2$ odd numbers *and* $3$ even numbers. Converting this into math lingo, we get $\binom{50}{2} \cdot \binom{50}{3}$, and not their sum because we want both and not one or the other.
54,913,904
I'm trying to select the number of free beds per floor and the number of rooms in which those beds exist. I think I'm having trouble because I first have to calculate how many beds are free in each room, which I'm doing by subtracting the number of beds in the room minus the people that are assigned to that room. Can I `GROUP BY` the current query in a way that achieves the desired result? The tables used are these: ``` CREATE TABLE IF NOT EXISTS planta( codigo int PRIMARY KEY NOT NULL AUTO_INCREMENT, especialidad varchar(25) NOT NULL ) ENGINE=InnoDB; CREATE TABLE IF NOT EXISTS habitacion( id int PRIMARY KEY NOT NULL AUTO_INCREMENT, numero_camas int NOT NULL, planta_id int NOT NULL, FOREIGN KEY (planta_id) REFERENCES planta(codigo) )ENGINE=InnoDB; CREATE TABLE IF NOT EXISTS paciente( dni varchar(9) PRIMARY KEY NOT NULL, num_ss varchar(10) NOT NULL, nombre varchar(20) NOT NULL, direccion varchar(50) NOT NULL, tratamiento mediumtext NOT NULL, diagnostico mediumtext NOT NULL, habitacion_id int NOT NULL, medico_id int NOT NULL, FOREIGN KEY (habitacion_id) REFERENCES habitacion(id), FOREIGN KEY (medico_id) REFERENCES medico(num_colegiado) )ENGINE=InnoDB; ``` The query is this: ``` SELECT planta.codigo AS Floor_id, habitacion.id AS Room_id, numero_camas - count(dni) AS Free_beds FROM habitacion, paciente, planta WHERE planta_id = planta.codigo AND habitacion_id = habitacion.id GROUP BY planta.codigo, habitacion.id; ``` It returns this result: ``` Floor id | Room id | Free beds 1 1 1 1 2 1 2 3 3 ``` But I want this: ``` Floor id | Rooms | Free beds 1 2 2 2 1 3 ```
2019/02/27
[ "https://Stackoverflow.com/questions/54913904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11127217/" ]
*Never* use commas in the `FROM` clause. *Always* use proper, explicit, **standard** `JOIN` syntax. You just need the correct `GROUP BY` logic. I think it is like this ``` SELECT pl.codigo AS Floor_id, count(count distinct h.id) as num_rooms, MAX(numero_camas) - count(distinct h.id) AS Free_beds FROM habitacion h join paciente p on p.habitacion_id = h.id -- just a guess that this is the right join condition planta pl on h.planta_id = pl.codigo GROUP BY pl.codigo ```
Based on the answer of Gordon Linoff and yor statement I guess with this minor changes you should get the correct result (I guess the distinct rooms need to be counted and the amount of beds minus the people that are assigned needs to be summed up): ``` SELECT pl.codigo AS Floor_id, count(distinct habitacion_id) as num_rooms, SUM(numero_camas - count(dni)) AS Free_beds FROM habitacion h join paciente p on p.habitacion_id = h.id join condition planta pl on h.planta_id = pl.codigo GROUP BY pl.codigo ```
54,913,904
I'm trying to select the number of free beds per floor and the number of rooms in which those beds exist. I think I'm having trouble because I first have to calculate how many beds are free in each room, which I'm doing by subtracting the number of beds in the room minus the people that are assigned to that room. Can I `GROUP BY` the current query in a way that achieves the desired result? The tables used are these: ``` CREATE TABLE IF NOT EXISTS planta( codigo int PRIMARY KEY NOT NULL AUTO_INCREMENT, especialidad varchar(25) NOT NULL ) ENGINE=InnoDB; CREATE TABLE IF NOT EXISTS habitacion( id int PRIMARY KEY NOT NULL AUTO_INCREMENT, numero_camas int NOT NULL, planta_id int NOT NULL, FOREIGN KEY (planta_id) REFERENCES planta(codigo) )ENGINE=InnoDB; CREATE TABLE IF NOT EXISTS paciente( dni varchar(9) PRIMARY KEY NOT NULL, num_ss varchar(10) NOT NULL, nombre varchar(20) NOT NULL, direccion varchar(50) NOT NULL, tratamiento mediumtext NOT NULL, diagnostico mediumtext NOT NULL, habitacion_id int NOT NULL, medico_id int NOT NULL, FOREIGN KEY (habitacion_id) REFERENCES habitacion(id), FOREIGN KEY (medico_id) REFERENCES medico(num_colegiado) )ENGINE=InnoDB; ``` The query is this: ``` SELECT planta.codigo AS Floor_id, habitacion.id AS Room_id, numero_camas - count(dni) AS Free_beds FROM habitacion, paciente, planta WHERE planta_id = planta.codigo AND habitacion_id = habitacion.id GROUP BY planta.codigo, habitacion.id; ``` It returns this result: ``` Floor id | Room id | Free beds 1 1 1 1 2 1 2 3 3 ``` But I want this: ``` Floor id | Rooms | Free beds 1 2 2 2 1 3 ```
2019/02/27
[ "https://Stackoverflow.com/questions/54913904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11127217/" ]
*Never* use commas in the `FROM` clause. *Always* use proper, explicit, **standard** `JOIN` syntax. You just need the correct `GROUP BY` logic. I think it is like this ``` SELECT pl.codigo AS Floor_id, count(count distinct h.id) as num_rooms, MAX(numero_camas) - count(distinct h.id) AS Free_beds FROM habitacion h join paciente p on p.habitacion_id = h.id -- just a guess that this is the right join condition planta pl on h.planta_id = pl.codigo GROUP BY pl.codigo ```
You need two aggregations: The number of beds per habitation, then the sum of available beds per floor. One way to do this is: ``` select planta_id, count(*) as rooms, sum(available - occupied) as free_beds from ( select planta_id, h.id as habitacion_id, numero_camas as available, (select count(*) from paciente p where p.habitacion_id = h.id) as occupied from habitacion h ) habitation_aggregated group by planta_id order by planta_id; ``` You see that I have a subquery in the `FROM` clause that represents an aggregation. This is a very good and save way to deal with multiple aggregations.
46,502,470
I have made an image gallery, made up by two rows each with tree images. I've made my site responsive, but for some reason, the images does not resize/adjust according to the screen. I've attached the picture, and as is visible the images does not adjust to the screen. [Screen shot of site](https://i.stack.imgur.com/GjWXb.png) ```css .image3 { height: 300px; width: 370px; border: 5px solid; color: grey; } ``` ```html <div class="wrapper"> <div class="row"> <img src="img/gallery1.jpg" alt="Iphone" class="image3"> <img src="img/static1.squarespace2.jpg" alt="Iphone" class="image3"> <img src="img/apple-iphone-8.jpg" alt="Iphone" class="image3"> </div> <div class="row"> <img src="img/iphone-8-concept.jpg" alt="Iphone" class="image3"> <img src="img/gallery1.jpg" alt="Iphone" class="image3"> <img src="img/gallery1.jpg" alt="Iphone" class="image3"> </div> </div> ```
2017/09/30
[ "https://Stackoverflow.com/questions/46502470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6669176/" ]
The image does not resize because you gave them a absolute width. If you give the element a `max-width` and `max-height` of 100% it should be responsive. So like this: ```css .image3 { max-height: 100%; max-width: 100%; border-style: solid; border-width: 5px; color: grey; } ``` ```html <div class="row"> <div class="wrapper"> <img src="img/gallery1.jpg" alt="Iphone" class="image3" /> <img src="img/static1.squarespace2.jpg" alt="Iphone" class="image3" /> <img src="img/apple-iphone-8.jpg" alt="Iphone" class="image3" /> </div> <div class="row"> <img src="img/iphone-8-concept.jpg" alt="Iphone" class="image3" /> <img src="img/gallery1.jpg" alt="Iphone" class="image3" /> <img src="img/gallery1.jpg" alt="Iphone" class="image3" /> </div> ``` Pixels are not responsive to the screen's size **Note: See response from MarioZ below**
Why would they? You can use ``` max-width: 100%; /* or 33% or whatever you need */ ``` to let it shrink when the screen has less width, but right now it will always be the size you specified. --- Also "responsiveness" mainly refers to having different layouts for different screen widths, which results in optimized layouts for both mobile and desktop. Having three images next to each other doesn't seem very responsive. Rather I would decrease the number of images in each row. Like this: ```css .image3 { height: 300px; width: 370px; border-style: solid; border-width: 5px; color: grey; } ``` ```html <div class="row"> <div class="wrapper"> <img src="http://www.placecage.com/200/200" alt="Iphone" class="image3" /> <img src="http://www.placecage.com/200/200" alt="Iphone" class="image3" /> <img src="http://www.placecage.com/200/200" alt="Iphone" class="image3" /> <img src="http://www.placecage.com/200/200" alt="Iphone" class="image3" /> <img src="http://www.placecage.com/200/200" alt="Iphone" class="image3" /> <img src="http://www.placecage.com/200/200" alt="Iphone" class="image3" /> </div> </div> ```
46,502,470
I have made an image gallery, made up by two rows each with tree images. I've made my site responsive, but for some reason, the images does not resize/adjust according to the screen. I've attached the picture, and as is visible the images does not adjust to the screen. [Screen shot of site](https://i.stack.imgur.com/GjWXb.png) ```css .image3 { height: 300px; width: 370px; border: 5px solid; color: grey; } ``` ```html <div class="wrapper"> <div class="row"> <img src="img/gallery1.jpg" alt="Iphone" class="image3"> <img src="img/static1.squarespace2.jpg" alt="Iphone" class="image3"> <img src="img/apple-iphone-8.jpg" alt="Iphone" class="image3"> </div> <div class="row"> <img src="img/iphone-8-concept.jpg" alt="Iphone" class="image3"> <img src="img/gallery1.jpg" alt="Iphone" class="image3"> <img src="img/gallery1.jpg" alt="Iphone" class="image3"> </div> </div> ```
2017/09/30
[ "https://Stackoverflow.com/questions/46502470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6669176/" ]
The image does not resize because you gave them a absolute width. If you give the element a `max-width` and `max-height` of 100% it should be responsive. So like this: ```css .image3 { max-height: 100%; max-width: 100%; border-style: solid; border-width: 5px; color: grey; } ``` ```html <div class="row"> <div class="wrapper"> <img src="img/gallery1.jpg" alt="Iphone" class="image3" /> <img src="img/static1.squarespace2.jpg" alt="Iphone" class="image3" /> <img src="img/apple-iphone-8.jpg" alt="Iphone" class="image3" /> </div> <div class="row"> <img src="img/iphone-8-concept.jpg" alt="Iphone" class="image3" /> <img src="img/gallery1.jpg" alt="Iphone" class="image3" /> <img src="img/gallery1.jpg" alt="Iphone" class="image3" /> </div> ``` Pixels are not responsive to the screen's size **Note: See response from MarioZ below**
It seems you're giving a fixed size to your images using `px` units. If you want your images to be responsive, to adapt their size, you need to use relative units. Being the most common: * Relative to the container: percentaje **%** * Relative to the container font-size: **em** * Relative to the root element font-size: **rem** * Relative to the viewport size: **vw** and **vh** (equivalent to 1% of the viewport measure) You should wrap each image in an individual div `class:wrapper` and give the div a relative width. ```css html,body { width:100%; height:100%; margin:0; padding:0; } .image3 { display:block; max-height: 100%; max-width: 100%; width:100%; border-style: solid; border-width: 5px; color: grey; } .row { width:100%; } .wrapper { width: 33.33%; float:left; } ``` ```html <div class="row"> <div class="wrapper"> <img src="https://placeimg.com/80/80/any" alt="Iphone" class="image3" /> </div> <div class="wrapper"> <img src="https://placeimg.com/120/120/any" alt="Iphone" class="image3" /> </div> <div class="wrapper"> <img src="https://placeimg.com/100/100/any" alt="Iphone" class="image3" /> </div> </div> <div class="row"> <div class="wrapper"> <img src="https://placeimg.com/80/80/any" alt="Iphone" class="image3" /> </div> <div class="wrapper"> <img src="https://placeimg.com/120/120/any" alt="Iphone" class="image3" /> </div> <div class="wrapper"> <img src="https://placeimg.com/100/100/any" alt="Iphone" class="image3" /> </div> </div> ``` Maybe it's a good idea to use css **flexbox** or **grid** too.
46,502,470
I have made an image gallery, made up by two rows each with tree images. I've made my site responsive, but for some reason, the images does not resize/adjust according to the screen. I've attached the picture, and as is visible the images does not adjust to the screen. [Screen shot of site](https://i.stack.imgur.com/GjWXb.png) ```css .image3 { height: 300px; width: 370px; border: 5px solid; color: grey; } ``` ```html <div class="wrapper"> <div class="row"> <img src="img/gallery1.jpg" alt="Iphone" class="image3"> <img src="img/static1.squarespace2.jpg" alt="Iphone" class="image3"> <img src="img/apple-iphone-8.jpg" alt="Iphone" class="image3"> </div> <div class="row"> <img src="img/iphone-8-concept.jpg" alt="Iphone" class="image3"> <img src="img/gallery1.jpg" alt="Iphone" class="image3"> <img src="img/gallery1.jpg" alt="Iphone" class="image3"> </div> </div> ```
2017/09/30
[ "https://Stackoverflow.com/questions/46502470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6669176/" ]
The image does not resize because you gave them a absolute width. If you give the element a `max-width` and `max-height` of 100% it should be responsive. So like this: ```css .image3 { max-height: 100%; max-width: 100%; border-style: solid; border-width: 5px; color: grey; } ``` ```html <div class="row"> <div class="wrapper"> <img src="img/gallery1.jpg" alt="Iphone" class="image3" /> <img src="img/static1.squarespace2.jpg" alt="Iphone" class="image3" /> <img src="img/apple-iphone-8.jpg" alt="Iphone" class="image3" /> </div> <div class="row"> <img src="img/iphone-8-concept.jpg" alt="Iphone" class="image3" /> <img src="img/gallery1.jpg" alt="Iphone" class="image3" /> <img src="img/gallery1.jpg" alt="Iphone" class="image3" /> </div> ``` Pixels are not responsive to the screen's size **Note: See response from MarioZ below**
use this code. here i used bootstrap... copy whole code.. and save as page.html then check. ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-lg-4 col-sm-4 col-md-4 col-xs-4"> <img src="http://lorempixel.com/400/200/sports/" alt="" class="img-responsive"> </div> <div class="col-lg-4 col-sm-4 col-md-4 col-xs-4"> <img src="http://lorempixel.com/400/200/sports/" alt="" class="img-responsive"> </div> <div class="col-lg-4 col-sm-4 col-md-4 col-xs-4"> <img src="http://lorempixel.com/400/200/sports/" alt="" class="img-responsive"> </div> </div> <div class="row"> <div class="col-lg-4 col-sm-4 col-md-4 col-xs-4"> <img src="http://lorempixel.com/400/200/sports/" alt="" class="img-responsive"> </div> <div class="col-lg-4 col-sm-4 col-md-4 col-xs-4"> <img src="http://lorempixel.com/400/200/sports/" alt="" class="img-responsive"> </div> <div class="col-lg-4 col-sm-4 col-md-4 col-xs-4"> <img src="http://lorempixel.com/400/200/sports/" alt="" class="img-responsive"> </div> </div> </div> </body> </html> ```
46,502,470
I have made an image gallery, made up by two rows each with tree images. I've made my site responsive, but for some reason, the images does not resize/adjust according to the screen. I've attached the picture, and as is visible the images does not adjust to the screen. [Screen shot of site](https://i.stack.imgur.com/GjWXb.png) ```css .image3 { height: 300px; width: 370px; border: 5px solid; color: grey; } ``` ```html <div class="wrapper"> <div class="row"> <img src="img/gallery1.jpg" alt="Iphone" class="image3"> <img src="img/static1.squarespace2.jpg" alt="Iphone" class="image3"> <img src="img/apple-iphone-8.jpg" alt="Iphone" class="image3"> </div> <div class="row"> <img src="img/iphone-8-concept.jpg" alt="Iphone" class="image3"> <img src="img/gallery1.jpg" alt="Iphone" class="image3"> <img src="img/gallery1.jpg" alt="Iphone" class="image3"> </div> </div> ```
2017/09/30
[ "https://Stackoverflow.com/questions/46502470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6669176/" ]
The image does not resize because you gave them a absolute width. If you give the element a `max-width` and `max-height` of 100% it should be responsive. So like this: ```css .image3 { max-height: 100%; max-width: 100%; border-style: solid; border-width: 5px; color: grey; } ``` ```html <div class="row"> <div class="wrapper"> <img src="img/gallery1.jpg" alt="Iphone" class="image3" /> <img src="img/static1.squarespace2.jpg" alt="Iphone" class="image3" /> <img src="img/apple-iphone-8.jpg" alt="Iphone" class="image3" /> </div> <div class="row"> <img src="img/iphone-8-concept.jpg" alt="Iphone" class="image3" /> <img src="img/gallery1.jpg" alt="Iphone" class="image3" /> <img src="img/gallery1.jpg" alt="Iphone" class="image3" /> </div> ``` Pixels are not responsive to the screen's size **Note: See response from MarioZ below**
If you want an image to be responsive there are 2 main things you need to do: 1. never set both width and height, just set width. 2. don't use pixels to set the width use percentages In your case you have 3 images so divide 100% in 3 which is about 33%, so give the images the size of 33% (or a little less if the container doesn't have box-sizing: border-box;) and they will adjust nicely.
185,586
The basic search capabilities of MediaWiki (at least, the version we're running - 1.7.1) are pretty poor. I'd like to improve them with an extension, but there are a lot of options and I'd like to have a good starting point. For what it's worth, the wiki is an internal one; we don't have the option, for example, of using the Google search extension, because it's not going to be able to crawl the wiki's contents. I need a solution that will run entirely on the wiki server. Here are the wiki version details: ``` MediaWiki: 1.7.1 PHP: 5.2.8 (apache2handler) MySQL: 4.1.21-log ``` What are my options?
2010/09/28
[ "https://serverfault.com/questions/185586", "https://serverfault.com", "https://serverfault.com/users/2741/" ]
1. Dont do email marketing. Don't. Streamsend, Mailchimp or Constant Contact are spammers by any other name. A pig with lipstick is still a pig. 2. If you must, just customize an existing solution. Very customizable: [sendmail](http://www.sendmail.org)
Lyris, LSoft, Constant Contact and if you like programmable interfaces Mailgun
1,115,775
I have installed VirtualBox 5.0.14 on an Lubuntu 15.10 host, and created a virtual machine with Lubuntu 14.04.5 LTS as the guest OS. I would like to set up a host-only network adapter in VirtualBox so that I can access an Apache webserver running inside the guest OS from a webbrowser running on the host system. So far I have created a host-only adapter `vboxnet0` which I can ping successfully from the host OS. However, I cannot access port 80 using a webbrowser or any other means. What can I do to get to the cause of the problem and configure things properly? VM network settings ------------------- [![enter image description here](https://i.stack.imgur.com/FfbPh.png)](https://i.stack.imgur.com/FfbPh.png) VirtualBox `vboxnet0` settings ------------------------------ [![enter image description here](https://i.stack.imgur.com/OPqpj.png)](https://i.stack.imgur.com/OPqpj.png) [![enter image description here](https://i.stack.imgur.com/sNQu2.png)](https://i.stack.imgur.com/sNQu2.png) Test results inside guest ------------------------- After booting the VM and starting Apache (using `sudo service apache2 start`) I can access a test page on `http://localhost/` using Firefox inside the guest OS without problems. The corresponding Apache VirtualHost is defined as `<VirtualHost *:80>` in `/etc/apache2/sites-enabled/000-default.conf`, so I don't see why it wouldn't be accessible from any host. Also, sshd and MySQL server are running on the guest. I can ssh to localhost and nmap shows all relevant ports open (22, 80, 3306). Test results on host -------------------- On the host OS, `vboxnet0` appears as follows and is pingable: ``` % ifconfig vboxnet0 vboxnet0 Link encap:Ethernet HWaddr 0a:00:27:00:00:00 inet addr:192.168.10.10 Bcast:192.168.10.255 Mask:255.255.255.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:192 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:0 (0.0 B) TX bytes:16176 (16.1 KB) % ping 192.168.10.10 PING 192.168.10.10 (192.168.10.10) 56(84) bytes of data. 64 bytes from 192.168.10.10: icmp_seq=1 ttl=64 time=0.023 ms ``` However, none of the ports are accessible: ``` % nmap 192.168.10.10 -p 22,80,3306 Starting Nmap 6.47 ( http://nmap.org ) at 2016-08-20 21:29 CEST Nmap scan report for 192.168.10.10 Host is up (0.000027s latency). PORT STATE SERVICE 22/tcp closed ssh 80/tcp closed http 3306/tcp closed mysql Nmap done: 1 IP address (1 host up) scanned in 0.07 seconds ``` Trying to match IP address -------------------------- As per comment by @MarkoPolo: Even though `192.168.10.10` is pingable from the host OS, I cannot access this IP address from the guest OS. In fact, the guest OS has an IP address from the DHCP range specified in for `vboxnet0`: ``` eth1 Link encap:Ethernet HWaddr 08:00:27:0d:b4:6a inet addr:192.168.56.101 Bcast:192.168.56.255 Mask:255.255.255.0 inet6 addr: fe80::a00:27ff:fe0d:b46a/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:2 errors:0 dropped:0 overruns:0 frame:0 TX packets:11 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:1180 (1.1 KB) TX bytes:1422 (1.4 KB) ``` The IP address `192.168.56.101` is not reachable from the host OS, i.e. not pingable, no access using webbrowser. I tried updating the IP address of `eth1` to `192.168.10.10` using `ifconfig`. Then, Apache is reachable on `http://192.168.10.10` from the guest OS, however, still no access (aside from ping) is possible from the host OS.
2016/08/20
[ "https://superuser.com/questions/1115775", "https://superuser.com", "https://superuser.com/users/526082/" ]
### Shorter answer. Based on what I know about default VirtualBox network settings, your host only connection that uses `192.168.10.10` is on the incorrect subnet and that adjustment is being done in the wrong area to get this thing working. When setting up a host only adapter on the host OS, the IPv4 address should be `192.168.56.1`. And then—after that is setup—on the guest OS set the `eth1` interface to use an IP address like `192.168.56.10`. ### Longer answer. When using VirtualBox the internal pseudo-software router is set to work on the `192.168.56.x` range of IP addresses. The DHCP server range—which you should not set static IP addresses on would be in the range of `192.168.56.101` to `192.168.56.254` and to set a static IP address, you would need to set an IP address between `192.168.56.2` to `192.168.56.100`. So I would recommend that your guest OS config use (Lubuntu 14.04.5 LTS) use an IP address such as `192.168.56.10`. But don’t set that `192.168.56.10` value in the “Adapter” area as you have it set up. Instead, adjust your adapter settings to be as follows; see Mac OS X screenshot below for reference: * IPv4 Address: `192.168.56.1` * IPv4 Network Mask: `255.255.255.0` * IPv6 Address: [Leave Blank] * IPv6 Network Mask Length: `0` [![Screenshot of the network settings for a host only interface in the Mac OS X version of VirtualBox.](https://i.stack.imgur.com/5ThnN.png)](https://i.stack.imgur.com/5ThnN.png) And then on your guest OS (Lubuntu 14.04.5 LTS), it seems odd to me that your `eth1` setting would be the DHCP setting and have the address of `192.168.56.101`. I use Ubuntu 14.04.5 with a very similar host only connection for Apache development on the second adapter as well, and my setup is broken down like this: * `eth0` with an IP address of `10.0.2.15`. * `eth1` with an IP address of `192.168.56.10`. And my settings in `/etc/network/interfaces` are as follows: ``` auto eth1 iface eth1 inet static address 192.168.56.10 netmask 255.255.255.0 ``` So double-check that IP address on the host only connection and double-check your network interfaces config as well.
**The purpose of Host-only networking using VirtualBox** In your example, you're attempting to set up a host-only network in VirtualBox that consists of one guest machine only, and of course the host machine. Keep in mind, however, that *Host-only networking* is designed so that it can accommodate multiple guest machines. All guest machines inside the *host-only-network* can communicate with eath other *and* the host machine *but not* with the outside world: ``` Outside world <--> NIC <--> Host <--> vboxnet0 <--> virtual NIC <--> Guest OS --- -------- ----------- (virtual NIC <--> Guest OS #2) ... (virtual NIC <--> Guest OS #n) ``` **Distinguishing between host and guest IP address** Your assumption is that `192.168.10.10` would be the IP address of the guest OS because it appears as `vboxnet0` on the host machine. This assumption is incorrect -- in fact, `192.168.10.10` is the IP address of the *host* machine! Assume that you have multiple guest machines inside your *host-only network*, then all of them could access the host OS using that IP address. `vboxnet0` acts as the gateway between host and guest(s). You can easily verify this: If you open any port on your host machine (for instance using `nc`), you should be able to access that port from the guest OS on `192.168.10.10`. The actual IP address of the guest is -- as you noted above -- `192.168.56.101` which is taken from the DHCP configuration in VirtualBox' `vboxnet0` settings. This is what is to be expected. You should be able to access your guest OS on `192.168.56.101` from the host. (Note that this is where the multiple guest machines would come into play: If you would assign more guest machines to `vboxnet0`, the would also get IP addresses from the DHCP range specified. You can also choose to assign static IP addresses, however, keep in mind then that they must be in the same subnet as the host's IP address, i.e. the address of `vboxnet0`.) **Possible cause of trouble and solution** Your guest machine should be reachable as `192.168.56.101`, which you describe does not work. The VirtualBox configuration looks good. You're more likely facing a routing/subnet problem (that may have to do with other network interfaces on your host machine). Try putting the host machine in the same subnet as the guest machine(s), by changing VirtualBox' settings as follows: [![enter image description here](https://i.stack.imgur.com/CErr2.png)](https://i.stack.imgur.com/CErr2.png) Check the routing table on your host machine using `route`. A route to `192.168.56.0` / `255.255.255.0` via `vboxnet0` should now exist, created by VirtualBox. You should now be able to access the guest's Apache from the host via `http://192.168.56.101` and -- if neccessary -- access the host machine from the guest via `192.168.56.1`.
8,638,109
I saw a class "AttributeSelectedClassifier" was once created in the following ways: ``` AttributeSelectedClassifier classifier = new AttributeSelectedClassifier(); classifier.setClassifier(base); classifier.setEvaluator(eval); ``` This above one looks natural to me. But how about the following one. ``` classifier = new AttributeSelectedClassifier(); ((AttributeSelectedClassifier)classifier).setClassifier(base); ((AttributeSelectedClassifier)classifier).setEvaluator(eval); ``` I think it should be right, but I am not quite sure about the way of of defining classifier as ((AttributeSelectedClassifier)classifier), how to understand this usage?
2011/12/26
[ "https://Stackoverflow.com/questions/8638109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/288609/" ]
This means that the classifier variable is declared as a superclass or superinterface of `AttributeSelectedClassifier`, and that you need to call a method which is not defined in the class or interface, but only on `AttributeSelectedClassifier`. This notation *casts* the variable to `AttributeSelectedClassifier`: ``` Object classifier = new AttributeSelectedClassifier(); // classifier is a AttributeSelectedClassifier, but references as Object // to call the following method, we need to cast it to AttributeSelectedClassifier ((AttributeSelectedClassifier)classifier).setClassifier(base); ((AttributeSelectedClassifier)classifier).setEvaluator(eval); ``` This is usually the sign of a design problem. Either the methods should be in the superclass or interface, or the variable should be declared as `AttributeSelectedClassifier`.
This: ``` ((AttributeSelectedClassifier)classifier) ``` isn't "defining" or "declaring" classifier - it's *casting* it. Presumably in this case `classifier` is declared as some superclass of `AttributeSelectedClassifier`. The code isn't particularly clear though. I'd rewrite the second bit of code (assuming you can't change the declaration of `classifier`) to: ``` AttributeSelectedClassifier temp = new AttributeSelectedClassifier(); temp.setClassifier(base); temp.setEvaluator(eval); classifier = temp; ``` That way you get to use all the methods of `AttributeSelectedClassifier` before assigning a value to the less-strongly-typed `classifier` variable. (I'd probably use a clearer name than `temp`, but we don't have enough context to work out what such a name would be.)
8,638,109
I saw a class "AttributeSelectedClassifier" was once created in the following ways: ``` AttributeSelectedClassifier classifier = new AttributeSelectedClassifier(); classifier.setClassifier(base); classifier.setEvaluator(eval); ``` This above one looks natural to me. But how about the following one. ``` classifier = new AttributeSelectedClassifier(); ((AttributeSelectedClassifier)classifier).setClassifier(base); ((AttributeSelectedClassifier)classifier).setEvaluator(eval); ``` I think it should be right, but I am not quite sure about the way of of defining classifier as ((AttributeSelectedClassifier)classifier), how to understand this usage?
2011/12/26
[ "https://Stackoverflow.com/questions/8638109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/288609/" ]
Look at the below code. Person implements the `CanWalk` interface. If you assign a `Person` to `CanWalk` interface as shown in the main method, which is a common practice, you can only invoke the methods that are specified in the `CanWalk` interface i.e. `walk()`. If you want to invoke `f()`, that **isn't** declared in the `CanWalk` interface, then you would use the 2nd mechanism you have specified in your post. i.e. **cast** it to `Person` class and then invoke the method. It is a good practice for the user's of the API (main method here) to use the correct abstraction while working with an object. For e.g. if the client is mainly focused on moving Person's then it should use CanWalk. This way client is not effected by changes to the Person class that are not related to movement. Read [this article](http://www.markhneedham.com/blog/2009/10/18/coding-role-based-interfaces/) for more details. ``` interface CanWalk { void walk(); } class Person implements CanWalk { void walk() { System.out.println("I am walking"); } void f() { ///some arbitrary method } } public stativ void main(String a[]) { CanWalk cw=new Person(); ((Person)cw).f(); } ```
This: ``` ((AttributeSelectedClassifier)classifier) ``` isn't "defining" or "declaring" classifier - it's *casting* it. Presumably in this case `classifier` is declared as some superclass of `AttributeSelectedClassifier`. The code isn't particularly clear though. I'd rewrite the second bit of code (assuming you can't change the declaration of `classifier`) to: ``` AttributeSelectedClassifier temp = new AttributeSelectedClassifier(); temp.setClassifier(base); temp.setEvaluator(eval); classifier = temp; ``` That way you get to use all the methods of `AttributeSelectedClassifier` before assigning a value to the less-strongly-typed `classifier` variable. (I'd probably use a clearer name than `temp`, but we don't have enough context to work out what such a name would be.)