anchor
stringlengths
0
150
positive
stringlengths
0
96k
source
dict
Connect MoveIt! with real robot (hardware)
Question: Hi, I am on Ubuntu 16.04 LTS and ROS Kinetic. I am trying to control a Robotis Manipulator-H with MoveIt! and I have been able to do it in Gazebo (using this links: https://github.com/AS4SR/general_info/wiki/ROS-MoveIt!-and-Gazebo-Integration-(WIP) and https://github.com/eYSIP-2017/eYSIP-2017_Robotic_Arm/wiki/Interfacing-MoveIt%21-with-Gazebo), so now I am trying to do that in the real robot. I have searched a lot on how to do this but I can't really find anything... I have tried the package "dynamixel_controllers" and the tutorial in this link: https://github.com/eYSIP-2017/eYSIP-2017_Robotic_Arm/wiki/Interfacing-Real-Robot-with-MoveIt%21 To connect the manipulator with MoveIt! but I wasn't able to do it since this tutorials uses the package "dynamixel_controllers" and it only works with Dynamixel motors and not Dynamixel PRO motors (which are the ones used bu the Manipulator-H). I also found out that I need an action server and a client server (or something like that) but since I am a newbie, I don't know how this properly works... can you guys give me any advices on how to connect the manipulator? I think this topic is a lot under documented... Other packages that I tried but with no success: "dynamixel_workcbench" and "open_manipulator". Thanks!, José Brito Originally posted by znbrito on ROS Answers with karma: 95 on 2018-04-17 Post score: 0 Original comments Comment by idrobot on 2018-06-14: Hi Jose, Are you able to solve this issue to connect MoveIt to real Manipulator-H arm? Now, I have same problem here, but don't know how to solve. I would like to know your current situation. Thanks. Comment by Ravi_Kanth on 2018-06-18: Hi Jose, did u solved the problem. I'm also facing same problem but i'm using hubby HS422 servo motor, can i use dynamixel_controllers pkg for move it interface? I tried that but it is not working. Please help me.. Comment by znbrito on 2018-06-18: Hello @idrobot and @Ravi_Kanth, yes I kinda solved the problem by adapting myself the packages from the implemented Robotis Open Manipulator. I did this by commenting the parts of the code where grips where mentioned and by adding the joints of the Robotis Manipulator-H to the following packages: Comment by znbrito on 2018-06-18: All in kinetic devel: open_manipulator_description open_manipulator_dynamixel_ctrl open_manipulator_moveit open_manipulator_msgs open_manipulator_position_ctrl Keep in mind that there are functions for Gazebo with parts that I didn't know hot to erase or change Comment by znbrito on 2018-06-18: I simply ignored them since I didn't need to used them! :) Comment by znbrito on 2018-06-18: To use, simply connect the manipulator to the PC via USB and type the following: FIRST TERMINAL: $ sudo chmod a+rw /dev/ttyUSB0 $ roslaunch open_manipulator_dynamixel_ctrl dynamixel_controller.launch SECOND TERMINAL: $ roslaunch open_manipulator_moveit open_manipulator_demo.launch Comment by znbrito on 2018-06-18: I had a problem still. Open manipulator has 4 joints, while the Manipulator-H has 6. The 5th and 6th joints were being read with a small offset error and I don't know why... luckily, I had another package (confidential) previously developed to read the joint values, so I used it and I now I am good! Comment by znbrito on 2018-06-18: Still I don't know how you would solve this problem, if you'd ever face it... one more thing, with this program you can only "plan and execute" and not "plan" and then "execute". This is because of the way the packages is developed, please see the link in me following comment Comment by znbrito on 2018-06-18: https://github.com/ROBOTIS-GIT/dynamixel-workbench/issues/141#issuecomment-383752996. Best of lucks! José Brito Answer: Hi :) Nice to see you again. ROBOTIS has provided github repository for Manipulator-H (https://github.com/ROBOTIS-GIT/ROBOTIS-MANIPULATOR-H) I recommend to use this package to control it in Gazebo. Furthermore, dynamixel_controllers are not supported by ROBOTIS. This package doesn't support to Dynamixel PRO as i know. In order to control Dynamixel PRO, you should use one of ROBOTIS official packages such as DynamiselSDK(https://github.com/ROBOTIS-GIT/DynamixelSDK), Dynamixel-Workbench(https://github.com/ROBOTIS-GIT/dynamixel-workbench) or ROBOTIS-Framework(https://github.com/ROBOTIS-GIT/ROBOTIS-Framework). Most of all, ROBOTIS-Framework is used to control Thormang3 which is assembled by Dynamixel PRO. So this package would be help you. If you have any question or issue, please visit there issue page. Your main goal is to connect the manipulator to MoveIt!. Below steps would be help you. Make MoveIt! Package to use setup assistant (http://docs.ros.org/kinetic/api/moveit_tutorials/html/doc/setup_assistant/setup_assistant_tutorial.html) Control your Dynamixel by ROS package (https://github.com/ROBOTIS-GIT/ROBOTIS-Framework) Check which topic is to send joint position or planned path (For example "/move_group/display_planned_path") Connect path topic to joint control topic (https://github.com/ROBOTIS-GIT/open_manipulator/blob/master/open_manipulator_position_ctrl/src/position_controller.cpp#L414) Good luck! Originally posted by Darby Lim with karma: 811 on 2018-04-17 This answer was ACCEPTED on the original site Post score: 1 Original comments Comment by znbrito on 2018-04-18: Hi, Darby, thanks for your response. Step one 1 I already did when controlling the manipulator in Gazebo. In step 2, I don't understand hat do you mean by controlling my Dynamixel by ROS package. Is this the package that should allow me to subscribe and publish joint states? Comment by znbrito on 2018-04-18: In step 3 and 4, the link that you sent me has a lot of gripper configurations and is not properly set to my manipulator... how can I properly configure it? And what launch files should I use? Your answer was a bit vague in that sense... Comment by znbrito on 2018-04-18: To make my manipulator work with Gazebo, I had to configure a lot of files and you didn't point my almost no one Comment by Darby Lim on 2018-04-18: Yes, you can control Dynamixel by topic to use that packages. When you pressed plan and execute button in Rviz, you can get a planned path through "/move_group/display_planned_path" topic. Subscribe it and publish to another topic related to control Dynamixel. Comment by znbrito on 2018-04-18: Hmm could you send me an example please? I am still very confused... In rviz gui for moveit the bluetooth sphere doesn't appear in the end effector, and that's why I know that something os wrong
{ "domain": "robotics.stackexchange", "id": 30674, "tags": "ros, moveit, hardware, ros-kinetic" }
Most general Lagrangian in Conformal Quantum Mechanics
Question: This question has already been asked and answered in Most general Lagrangian in CFT in 0+1D. However I am just partially convinced with the answer. The idea is to construct the most general Lagrangian that is scale and time invariant in 0+1D (so quantum mechanics). The proposed one is $$L=\frac{1}{2}\dot{Q}^2-\frac{g}{2Q^2} \, ,\tag{1.11}$$ but why couldn’t we add terms that have $d$ derivatives and $n$ fields with $n = 2(d-1)$ such as $\dot{Q}^3Q$, $\dot{Q}^4Q^2$ and so on $[a]$, because these terms in principle would respect both time and scaling invariance? In the answer given in the link above it says something that because we don’t want to modify the kinetic term we propose terms of the form $g_nO^n$ but I don’t see why the terms I have mentioned would modify the kinetic term. $[a]$: with 3 derivatives and 4 fields, obviously I am counting the derivatives and fields separately since each carry dimensions, I could have also said 3 field derivatives and 1 field. Answer: A first-order time-translation-invariant Lagrangian $L(Q,\dot{Q},t)$ cannot have any explicit time-dependence. The claim in Ref. 1 that scale-invariance implies the Lagrangian (1.11) is strictly speaking wrong as written. Scale-invariance (that is assumed compatible with the free kinetic term) only implies that the Lagrangian is of the form $$L(Q,\dot{Q})~=~\frac{f(Q\dot{Q})}{Q^2}\tag{A}$$ for some function $f$, cf. OP's observation. However, Ref. 1 presumably implicitly assumes that the Lagrangian is of the form kinetic term minus potential term: $$L(Q,\dot{Q})~=~\frac{1}{2}\dot{Q}^2-V(Q).\tag{B}$$ This indeed leads to the Lagrangian (1.11). Alternatively, one may appeal to the following proposition. Proposition. In order for special conformal transformations (1.12) to be quasi-symmetries of the action $$S~=~\int\! \! \mathrm{d}t~L,\tag{C}$$ [with the Lagrangian (A)], then the function $f$ should be (at most) a 2nd-order polynomial. The proposition reproduces the Lagrangian (1.11) up to normalization and total derivative terms. Sketched proof of proposition: Using the notation of this related Phys.SE post, the quasi-symmetry implies that $$ \frac{f\left(Q\dot{Q}-\frac{cQ^2}{ct+d}\right)-f(Q\dot{Q})}{Q^2} \tag{D}$$ should be a total time derivative, which is only possible if it is a 1st-order polynomial in $\dot{Q}$. This in turn implies that $f$ is a 2nd-order polynomial. $\Box$ References: J.D. Qualls, Lectures on CFT, arXiv:1511.04074; eq. (1.11).
{ "domain": "physics.stackexchange", "id": 62804, "tags": "lagrangian-formalism, conformal-field-theory, scale-invariance" }
What is the difference between LeakyReLU and PReLU?
Question: I thought both, PReLU and Leaky ReLU are $$f(x) = \max(x, \alpha x) \qquad \text{ with } \alpha \in (0, 1)$$ Keras, however, has both functions in the docs. Leaky ReLU Source of LeakyReLU: return K.relu(inputs, alpha=self.alpha) Hence (see relu code) $$f_1(x) = \max(0, x) - \alpha \max(0, -x)$$ PReLU Source of PReLU: def call(self, inputs, mask=None): pos = K.relu(inputs) if K.backend() == 'theano': neg = (K.pattern_broadcast(self.alpha, self.param_broadcast) * (inputs - K.abs(inputs)) * 0.5) else: neg = -self.alpha * K.relu(-inputs) return pos + neg Hence $$f_2(x) = \max(0, x) - \alpha \max(0, -x)$$ Question Did I get something wrong? Aren't $f_1$ and $f_2$ equivalent to $f$ (assuming $\alpha \in (0, 1)$?) Answer: Straight from wikipedia: Leaky ReLUs allow a small, non-zero gradient when the unit is not active. Parametric ReLUs take this idea further by making the coefficient of leakage into a parameter that is learned along with the other neural network parameters.
{ "domain": "datascience.stackexchange", "id": 8151, "tags": "neural-network" }
Does the CPT theorem hold for all spacetime dimensions?
Question: I can't find any reference which mentions the dependence of the theorem on spacetime dimension, but it would be very interesting to know what if any it has! Answer: With one minor qualification, the answer is yes: the CPT theorem holds for all spacetime dimensions. The qualification is that the P in CPT should be interpreted as a reflection of an odd number of spatial dimensions. (The simplest choice is to reflect just one spatial dimension.) If the total number of spatial dimensions is odd, then this is the same as reflecting all of them; but if the total number of spatial dimensions is even, the distinction is important. That's because a reflection of an even number of spatial dimensions can be un-done by ordinary rotations that are continuously connected to the identity. The P in CPT should not be continuously connected to the identity. To address this, Witten suggests using a new symbol $R$ for a reflection of a single spatial dimension, so the CPT theorem would be called the CRT theorem. Here's an excerpt from page 5 in "Fermion Path Integrals And Topological Phases", http://arxiv.org/abs/1508.04715, where $D$ denotes the number of spacetime dimensions: ...symmetry that in $D = 4$ is usually called CPT (where C is charge conjugation and P is parity or spatial inversion). However, this formulation is not valid for odd $D$ (even spatial dimension $d$), since in that case P is contained in the connected part of the spatial rotation group and should be replaced by an operation that reverses the orientation of space. To use a language that is equivalent to the usual CPT statement for even $D$ but is uniformly valid for all $D$, we will refer instead to CRT symmetry, where R is a reflection of one spatial coordinate. CRT symmetry is always valid in a relativistic theory of any dimension... Some differences between the effect of CPT in $4k$ and $4k+2$ spacetime dimensions are mentioned in section 4 of Alvarez-Gaumé and Witten (1983), "Gravitational anomalies," Nuclear Physics B 234: 269-330.
{ "domain": "physics.stackexchange", "id": 59486, "tags": "quantum-field-theory, special-relativity, spacetime-dimensions, cpt-symmetry" }
Why is baryon number conservation an accidental symmetry
Question: I have to write a report surrounding the subject of baryogenesis and I wanted to start this report off with explaining how the first Sakharov condition: Baryon number violation is possible within the Standard Model. I, however, can't seem to find a good explanation as to why in the classical sense the baryon number is conserved and why this is a so-called accidental symmetry. Most papers I read about baryogenesis state that due to a general Lagrangian being invariant under the gauge group: SU(3) x SU(2) x U(1) that it automatically has an global symmetry around U(1) with which lepton and baryon numbers can be identified. But how? Answer: I think your misunderstanding is precisely that you think that $U(1)$ gauge symmetry in SM can be associated to any quantum number such as baryon or lepton number. No, it can not. The $U(1)$ coming from $SU(3)_C\otimes SU(2)_L\otimes U(1)_Y$ is related to a quantum number called hypercharge, $Y$ We say that baryon and lepton numbers are symmetries in a 'classical' sense since they are preserved at Lagrangian level. This is, the Lagrangian is invariante under the change $$ \phi \rightarrow e^{-i\epsilon N}\phi $$ Where $\phi$ is any field, $N$ can be either baryon ($B$) or lepton ($L$) numbers and $\epsilon$ the group parameter. Nevertheless, as in QFT books is proven via triangle diagrams you can see that at quantum level (not Lagrangian level) baryon and lepton numbers are not preserved, i.e., $$ \partial_\mu j^\mu_{N} = n_{CS} \Rightarrow \Delta N \neq 0 \tag1 $$ with $j^\mu_{N}$ the Noether current related to $N = B, L$ and $n_{CS}$ the Chern-Simmons index. But since this index is the same for $B$ and $L$, from Eq. (1) you can deduce that $$ \partial_\mu (j^\mu_{B} - j^\mu_{L}) = 0 \Rightarrow \Delta(B - L) = 0 $$ The accidental (which means not pre-impossed in Lagrangian) quantum symmetry is not for $B$ or $L$ but for $B - L$.
{ "domain": "physics.stackexchange", "id": 58516, "tags": "particle-physics, symmetry, baryons, baryogenesis" }
Free electron gas in magnetic field
Question: I have a question regarding the calculation of "spin up" number of particles in a free electron gas, when placed in a uniform magnetic field $\textbf B$. In my lecture notes it's said that the spin up number of particles equals: $N_\uparrow=\int g(\epsilon-\textbf B\mu_m)f(\epsilon)\space d\epsilon $, where $g$ is the states density function $g=\frac{dN}{d\epsilon}$ and $f$ is the Fermi-Dirac distribution function $f(\epsilon)=\frac{1}{e^{(\epsilon-\mu)/k T}+1}$. My question: If the density of states function changes: $g(\epsilon)\rightarrow g(\epsilon-\textbf B \mu_m)$, why doesn't the F-D function change as well, so that $f(\epsilon)\rightarrow f(\epsilon-\textbf B \mu_m)$ ? This is connected to the calculation of the Pauli paramagnetism. Answer: Let $\varepsilon$ be the total energy of an electron. Then you can divide it into the energy of the spatial part and the energy of the spin part as follows $$\varepsilon=\varepsilon_{\boldsymbol{k}}\pm\mu_{\rm B}\cdot\boldsymbol{B}$$ Now comes the key part: the Fermi-Dirac distribution is related to the total energy of the state $\varepsilon$, and so you should use $f\left(\varepsilon\right)$. On the other hand, the density of states is related to the $\boldsymbol{k}$ number of states, so this time the correct expression you need to use is $g\left(\varepsilon_{\boldsymbol{k}}\right)=g\left(\varepsilon\mp\mu_{\rm B}\cdot\boldsymbol{B}\right)$.
{ "domain": "physics.stackexchange", "id": 45676, "tags": "condensed-matter, solid-state-physics" }
VBA code to underline numbers in the header takes significant time and sometimes crashes excel
Question: Background: For several of my workbooks I run Overview sheets with charts in them. When printing the Overview sheet, I put my workbook name as header, where the workbook name includes the criteria for the generating the source data (e.g., date range and time stamp plus non-numeric strings). To draw attention to these numbers/dates/times, I can manually highlight on the print out, but when others print (using a button on the Overview sheet) they don't seem to remember to do that. I am looking to add some "flare" to my header by underlining the numeric values. Issue: The workbook name character length varies, so I assess character by character. In some cases the code executes after a delay (time varies, but will say that I had a 60 character length name take ~30 seconds), and other times Excel simply doesn't complete execution after several minutes (i will press escape and get the "code execution has been interupted" msgbox; this recently happened for a 48 character name). Question: As this is working code (sometimes), would you please help critique and possibly help resolve the time delay? If my approach is inferior, I am open to suggestions, though I understand that, from my time on StackOverflow, subjective questions tend to be closed. Code in question: Option Explicit Sub underline_numbers_in_header() Dim i As Long, n As String, z As String n = ActiveWorkbook.Name 'Debug.Print Len(n) For i = 1 To Len(n) If IsNumeric(Mid(n, i, 1)) Then z = z & "&U" & Mid(n, i, 1) & "&U" Else z = z & Mid(n, i, 1) End If ActiveSheet.PageSetup.CenterHeader = "" & z & "" Next i End Sub Answer: ActiveSheet.PageSetup.CenterHeader = "" & z & "" There's no reason to run this instruction at every single iteration as z is still in the process of being concatenated, is there? Move it out of the loop and assign PageSetup.CenterHeader once, only when you've figured out the entire final string value - this could have a dramatically positive impact on performance :) The name of the procedure/macro should not have underscores in it; convention is to use PascalCase for procedure/member names. The procedure is implicitly Public and could use an explicit access modifier. Reading the name of the procedure I was expecting it to go through page headers and underline whatever numeric values are in there... but that's not what's happening, and the variable names aren't helping much. Take the time to spell them out, and thank yourself later! That said I'd suggest taking in a Workbook parameter and removing the ActiveWorkbook and ActiveSheet dependencies, which force any VBA code calling this procedure to Select and Activate things, which as you know isn't ideal. Actually, the procedure has too many responsibilities, that's why its name feels wrong. It should be a function that takes a String argument and returns the formatted string: that's what I would expect a "make numbers underline" procedure to do. Then another procedure can be responsible for knowing what worksheet to interact with, and for setting its PageSetup.CenterHeader: Dim headerText As String headerText = UnderlineNumbers(ActiveWorkbook.Name) ActiveSheet.PageSetup.CenterHeader = headerText The string-valued Mid$ function should work slightly better than the similar but variant-valued Mid function, and when the current character is being pulled from the string in 3 places, it's time to introduce a local variable ;-) This should be pretty much instant: Private Function UnderlineNumbers(ByVal value As String) As String Dim result As String Dim i As Long For i = 1 To Len(value) Dim current As String current = Mid$(value, i, 1) If IsNumeric(current) Then result = result & "&U" & current & "&U" Else result = result & current End If Next UnderlineNumbers = result End Function
{ "domain": "codereview.stackexchange", "id": 34765, "tags": "vba, excel" }
Rostopic on Mac
Question: I am continuing my quest to get ROS working on my Mac. I deleted my old ros_catkin_ws fully, and then redid the installation script (I know, it's not complete or supported, but I have to try.) For a change I thought I should try kinetic-ors-com-wet-install. All went well ,without errors. And roscore started up fine. Then this: bash-3.2$ rostopic -h Fatal Python error: PyThreadState_Get: no current thread Abort trap: 6 Anyone have a pointer for me on that one/ Thanks! Originally posted by pitosalas on ROS Answers with karma: 628 on 2017-07-21 Post score: 1 Answer: Hi, I encountered the same problem. I finally solved it by referring to https://qiita.com/furushchev/items/bc0d2b9d6c84741645f0 This problem is caused by the wrong reference to System standard Python in roslz4. $ otool -L $CATKIN_WS/install_isolated/lib/python2.7/site-packages/roslz4/_roslz4.so You can find: _roslz4.so: _roslz4.so (compatibility version 0.0.0, current version 0.0.0) libroslz4.dylib (compatibility version 0.0.0, current version 0.0.0) /System/Library/Frameworks/Python.framework/Versions/2.7/Python (compatibility version 2.7.0, current version 2.7.10) /usr/local/opt/lz4/lib/liblz4.1.dylib (compatibility version 1.0.0, current version 1.8.1) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1238.0.0) so, we should change it to the Python we currently use: $ install_name_tool -change /System/Library/Frameworks/Python.framework/Versions/2.7/Python /usr/local/bin/python _roslz4.so then rostopic turns out to be OK for me. Hope I could help. Originally posted by heretic1993 with karma: 16 on 2018-03-16 This answer was ACCEPTED on the original site Post score: 0
{ "domain": "robotics.stackexchange", "id": 28407, "tags": "ros, mac, rostopic" }
What are some examples of the projection operator being used in quantum mechanics?
Question: In Quantum Mechanics, the projection operator is defined as $\hat{P}_\psi = |\psi\rangle\langle\psi|$, so it acts on quantum states $|\Psi\rangle$ as $$\hat{P}_\psi|\Psi\rangle = |\psi\rangle\langle\psi|\Psi\rangle = \langle\psi|\Psi\rangle|\psi\rangle=c|\psi\rangle$$ I see that it behaves in a similar way of the projection operation between euclidean vectors: it returns a new ket in the $|\psi\rangle$ direction whose lenght $c$ is that of the projection of $|\Psi\rangle $ onto the $|\psi\rangle$ direction. However, what is the importance of this operator in Quantum Mechanics? What are some examples of the cases in which it is necessary to make use of it? Answer: There are lots of places you can find this object to be acted on. The best way would be to open a Quantum Mechanics book on pc and search for the word Projection and see the section and use of the Operator. These are few or two examples. The projection operator look like $$\mathcal{P}=|n\rangle \langle n|$$ A very nice property of the operator is rather obvious from the interpretation of it. The operator project a part of the vector along a specific basis vector. So If I project a vector along with all the bases, I should get the vector back. $$\sum_n\mathcal{P}_n|\psi\rangle=\sum_n |n\rangle \langle n|\psi\rangle =|\psi\rangle $$ $$\sum_n|n\rangle \langle n|=I$$ That's the crucial property and use the time to when changing basis. Whenever we need to write a vector on some basis, We insert a complete set. It's also used in a change of basis. A nice example of optics can be found on Principle of Quantum Mechanics R. Shankar: Section 1.6 Matrix element of a linear operator. In the context of the density matrix, A pure ensemble given by $$\rho=|\alpha^{(n)}\rangle \langle \alpha^{(n)}|$$ You can represent complete polarization beam with $S_z+$ as $$\rho=|+\rangle \langle +|$$ It's also used in the context of perturbation theory. Look for section 5.1 Modern Quantum Mechanics Sakurai : Formal development of perturbation expansion.
{ "domain": "physics.stackexchange", "id": 78859, "tags": "quantum-mechanics, hilbert-space, operators, quantum-information" }
Is spin 1 described by $SO(3)$ or $SU(2)$
Question: What spin is described by which rotation group? I always only find information about spin-1/2 Answer: Quantum spin in nonrelativistic Quantum Mechanics is generally associated either with the projective unitary representations of the rotation group SO(3) or with the vector unitary representations of the special unitary group SU(2). To be more precise, spin comes naturally from the projective unitary representations of the full 3D-Galilei group, but only for angular momentum/rotation symmetry purposes, it is enough for one to restrict only to a subgroup of it isomorphic to SO(3). Therefore, spin 1 we can describe in a proper (rigged) Hilbert space environment by the linear unitary representations of the SU(2) group which are in 1-1 correspondence with the representations of the su(2) Lie algebra by (essentially) self-adjoint operators.
{ "domain": "physics.stackexchange", "id": 54195, "tags": "quantum-mechanics, angular-momentum, quantum-spin, group-theory, representation-theory" }
rosserial communication between bluetooth and arduino
Question: Hi, I am trying to communicate wirelessly between an Arduino with a bluetooth shield and my computer using rosserial. When I use rosserial through the USB cable, everything works fine, but nothing works wirelessly. Also, I can send regular serial messages sometimes to Putty using the Arduino serial functions, Serial.begin(), Serial.Write(), etc. I just can't seem to make the Arduino a ROS node through bluetooth (though, as mentioned before it does work with a USB serial connection). I setup my bluetooth connection using: sudo rfcomm bind 0 00:00:01:08:01:65 1 There is an LED on the shield that indicates when the bluetooth is connected, however the messages that I get from the terminal are: rosrun rosserial_python serial_node.py /dev/rfcomm0 _baud:=9600 [INFO] [WallTime: 1342369406.985011] ROS Serial Python Node [INFO] [WallTime: 1342369406.987303] Connected on /dev/rfcomm0 at 9600 baud [ERROR] [WallTime: 1342369421.988484] Lost sync with device, restarting... I have tried playing around with the baud rates to no avail. Does anyone know how I can make this work? Originally posted by sgwhack on ROS Answers with karma: 73 on 2012-07-15 Post score: 0 Answer: rosserial_arduino sets the baud rate to 57600 on the arudino. You'll have to configure your bluetooth shield to run at 57600 on both ends, and use 57600 on rosserial_python. Alternatively, you can get rosserial_arduino to run at 9600 baud by editing ArduinoHardware.h in \libraries\ros_lib and changing the baud rate defaults in the constructors. Remember to restart the Arduino IDE after changing libraries. Originally posted by PaulBouchier with karma: 300 on 2012-08-09 This answer was ACCEPTED on the original site Post score: 2 Original comments Comment by Tones on 2014-03-27: If you want to change the baudrate of your Arduino's UART, you do not necessarily have to edit ArduinoHardware.h. Instead, call e.g. nh.getHardware()->setBaud(115200); in the setup() function of your sketch before nh.initNode(). In my example, nh is the NodeHandle.
{ "domain": "robotics.stackexchange", "id": 10199, "tags": "arduino, serial, bluetooth, nodes, rosserial" }
Is there a relationship between Free Radicals and Beta Particles?
Question: This question is contingent on my understanding of the two terms in the title. As I was taught, a Free Radical is a reactive (high energy?) valence electron released for stability's sake because it is unpaired. I was taught that a Beta Particle is a high energy and fast moving radioactive positron or electron released to stabilize an atom. If both of these premises are true, is there a relation between the two terms, and if so, what is it? Answer: There is high-energy in the sense of chemical reactivity, and then there is high energy in the sense of nuclear reactivity. The energy associated with the latter is many orders of magnitude greater than the energy associated with the former, so that there is generally no direct interaction between the two (where the free radical is chemically reactive, and the beta particle arises from nuclear reactivity). A free radical is a chemical species, whose electron configuration is such that it is highly reactive towards other chemical species. However, this energy is far too low to affect any nuclear reactivity. A beta particle is a high-energy electron or positron emitted by the radioactive decay of an atomic nucleus. As these particles are emitted from the nucleus of the atom, the electron configuration (i.e. a free radical) is irrelevant; only the stability/reactivity of the nucleus determines whether an atom will emit a beta particle, not the chemical species. If any of this seems incorrect or unclear, please do not hesitate to ask for clarifications in the comments.
{ "domain": "chemistry.stackexchange", "id": 8331, "tags": "physical-chemistry, electrons, stability, radioactivity" }
Speed of gravitational wave in strong gravity
Question: I have a question about gravitational waves which I can't really find an answer to. My current understanding is that one assumes there is some frame in which the metric has the form $g_{\mu\nu} = \eta_{\mu\nu}+h_{\mu\nu}$ where $h$ is a small perturbation. One then expands everything to first order in the perturbation and ends up with the wave equation $\Box \bar h_{\mu\nu} = 0$ where $\bar h$ is the trace inverse of $h$ (assuming zero stress-energy tensor everywhere). This clearly describes a wave that travels at the speed of light. What I can't seem to understand is what happens when the gravitational field is strong and the first order approximation fails. Is there any other way to argue that the gravitational wave travels at the speed of light which does not involve perturbation theory? Actually, how would one even define a gravitational wave without this linear approximation? I also heard that the LIGO collaboration detection of last year showed that GW should travel at the speed of light because we received a gamma burst exactly at the same time as the GW from the same source. But here I'm interested more in a theoretical explanation rather than a "it was measured so it's true" explanation. Thank you! Answer: In general it is either false or undefined that gravitational waves propagate at $c$. As a counterexample, GR predicts that a gravitational-wave pulse propagating on a background of curved spacetime develops a trailing edge that propagates at less than $c$. See Misner, Thorne, and Wheeler, p. 957. This effect is weak when the amplitude is small or the wavelength is short compared to the scale of the background curvature. For a general spacetime that includes high-amplitude gravitational waves, there need not be any meaningful definition of the speed of propagation of such waves. It's only in the low-amplitude limit that we can meaningfully talk about splitting a metric into a background term and a wave term. In general such a split is not uniquely defined, because there is in general no notion of adding metrics the way we add fields in SR. To add metrics you have to add them point by point, but there is in general no way to decide which point to add to which point. So for a high-amplitude gravitational wave, we don't necessarily have a background metric, and without a background metric we don't have any way to define what we mean by the speed at which a wave propagates. Andrew Steane wrote in a comment: Rindler considers an extract treatment of a plane wave, and I expect it's in MTW and other well known books. Owing to the subtlety of non-static metrics it's fairly zany stuff but basically, yes, it travels at c. I think the example you're talking about is in Rindler, Relativity: Special, General, and Cosmological, 2nd ed., ch. 13. Rindler shows that the wave propagates with coordinate velocity $dx/dt=c$, where the $x$ and $t$ coordinates are defined such that, in the flat region of spacetime that has not yet been visited by the wave, they are the standard Minkowski coordinates. He doesn't seem to explicitly justify the assumption that this coordinate velocity is correctly interpreted as the velocity of propagation, but given the setup, it's pretty plausible: observers in the region that hasn't yet been visited can synchronize clocks, etc. But this is just one example, and you can't prove a general rule from one example. MTW's example is a counterexample. It would be interesting to know whether there are counterexamples where the velocity is equally unambiguous and is greater than $c$, rather than less than $c$ as in the MTW example. I would be surprised (and disturbed) if there were. Maybe there are general theorems that rule this out, but it's not obvious to me what is even the best formulation of such a conjecture.
{ "domain": "physics.stackexchange", "id": 55995, "tags": "general-relativity, gravitational-waves" }
Algorithm to return all possible ways to divide n unique elements into groups of size k
Question: If I have as set N of n unique elements, is there a known algorithm that can return every possible way in which they can form groups of size k? Eg: If N = { A, B, C, D} and k = 2, then the algorithm should return [[(A, B), (C, D)], [(A, C), (B, D)], [(A, D), (B, C)]] Here it's safe for me to assume that n is always divisible by k! :D Sorry if this has already been asked, I couldn't find it. Bonus: Is there a library to do this in Python? Answer: The algorithm is straight-forward once you decide on the order of the subsets in the partitions. A simple algorithm produces partitions where: each subset in the partition is generated in order the subsets themselves are in order by their first element These partitions can be produced recursively, adding each element of the set in turn to a partition of the initial elements where the partition components have at most $k$ elements. Such a partition can be extended with a new element by: adding the new element to one of the existing components, if that component has fewer than $k$ elements, or adding a new component at the end of the partition, if the partition doesn't already have $n/k$ components. The same algorithm, without the check for the size of the partition element, could be used to generate all partitions. You're unlikely to find this in a standard Python library, but I'm sure other implementations exist. In any event, this is not the right place to ask about software libraries in existing languages. Here's the above algorithm written in Python. Unlike a functional version, this uses a state variable containing a mutable partial partition; each modification is undone after the recursive call, and the partitions finally produced are copied in order to avoid surprises. def part(s, k): """Yields each partition of s into subsets of size k, which must be a divisor of len(s). """ def step(i): if i == len(s): # Deep copy the current partition yield list(list(p) for p in part) else: for p in part: if len(p) < k: p.append(s[i]) yield from step(i + 1) p.pop() if len(part) * k < len(s): part.append(list(s[i])) yield from step(i + 1) part.pop() part = [] yield from step(0) In theory you could do this using a combinations generator, such as the one in the itertools: (Pseudocode) partitions(Seq, K) is if length(Seq) == K: return a single partition with Seq as its only component. otherwise: # Length must be > K; otherwise it wasn't a multiple of K to start with for each combination C of Seq of length K which includes Seq[0]: for each Partition in partitions(Seq - C, K): (***) prepend C to Partition and add it to the list to result Note the line (***) which requires both a combination C and the list of other elements of Seq, ideally in order. There's no particularly easy way to get that out of itertools.combinations,
{ "domain": "cs.stackexchange", "id": 20392, "tags": "algorithms, combinatorics, python" }
Condition for rolling uphill
Question: In the follow setup a cylinder of radius R and mass M is given an initial angular velocity (while initial linear velocity is 0). Coeffs of friction (both static and kinetic) are given. The question is under which condition will the cylinder roll uphill? I'm not really sure how to approach this problem, especially since I am not told whether the rolling is pure or not. My only idea is to simply use Newton's 2nd law to find a condition over μ while assuming the rolling is not perfect and thus f=Nμ. Is this the way to go? Answer: Since the initial linear velocity is 0 but the cylinder is rotating, the initial motion is not pure rolling: the cylinder is slipping. Examining the free body diagram, there are three forces acting on the center of mass: gravity (down), the normal force (perpendicular to the surface), and kinetic friction uphill. (The friction is kinetic because the cylinder is slipping--again, $v=0$ but $\omega\ne0$. The direction of friction is up the slope because friction always opposes motion, in this case the rotation.) We can split the forces into components. The component of gravity perpendicular to the surface of the incline will be exactly cancelled by the normal force. If the friction force is larger than the gravitational weight of the cylinder along the direction parallel to the incline, then the cylinder will go uphill; otherwise, the cylinder will go downhill.
{ "domain": "physics.stackexchange", "id": 41094, "tags": "homework-and-exercises, newtonian-mechanics, rotational-dynamics" }
Number of sentences and sentential forms generated by a grammar
Question: In this question, I'm considering only "finite grammars". A finite grammar can only produce a finite number of distinct sentences. The following grammar is finite in my definition: S → AB A → B | a B → a | b It can only generate the following finite number of sentences: aa, ab, ba, bb On the other hand, the following grammar is not finite: S → AB A → AA | B | a B → a | b Because it can create an infinite number of sentences: aa, aaa, aaaa, aaaaa, ... Now to the actual question. Suppose the following finite grammar: S → variable = math_expr variable → a | b | c math_expr → INT | function function → func_1() | func_2(INT, INT, INT, INT) INT → 1 | 2 | 3 | 4 | 5 I want to know if there is some kind of formula that calculate the number of sentences and sentential forms that can be generated by a finite grammar. Example of sentences: b = func_2(2,4,3,3), a = func_1() Example of sentential forms: b = func_2(2,2,INT,INT), c = math_expr, S At the moment, I am able to know the number of sentences and sentential forms by applying a Breadth-First Search (BFS) starting from the S node. However, because I'm working with search in program synthesis, it would be great to know the size of the domain without the need of applying an exhaustive search on it. Question: How can I find the number of sentences and sentential forms given only an arbitrary finite grammar? For the first finite grammar I showed here, the answer is easy to calculate by hand: Sentences: aa, ab, ba, bb Sentential forms: S, AB, BB, aB, bB, Aa, Ab So the final answer would be 4 + 7 = 11 However, for the second finite grammar I showed, it is not that easy to calculate it. PS.: In my original problem, I am working with program synthesis with a Domain Specific Language (DSL). I tagged CFG with the hope that the same applies, granted I'm not 100% sure. Answer: If the context-free grammar is unambiguous, you can count the number of sentences it generates in a linear scan with a carefully chosen order. I'll assume we have removed all useless symbols and cycles from the grammar. If it is finite and free of useless symbols and cycles, then it should not contain any recursion. Let $N(A)$ denote the number of sentences that can be constructed starting from nonterminal $A$, i.e., $N(A) = |L(A)|$. If the grammar is unambiguous and has no recursion, you can compute $N(A)$ for each nonterminal as follows. Construct a dependency graph with one vertex per nonterminal, and an edge $A \to B$ whenever the grammar contains a rule $B ::= \cdots A \cdots$, i.e., a rule with $B$ on the left-hand side and $A$ on the right-hand side. If the grammar has no recursion, then this is a dag. Visit the vertices of this graph in topologically sorted order. Then it is easy to compute the number of sentences: for example, if we have the rule $A ::= BaC | DE$, then we have $$N(A) = N(BaC) + N(DE) = N(B) N(a) N(C) + N(D) N(E).$$ That's an example, but you can do the same for any number of alternatives on the right-hand side and any string of symbols in each alternative. Note that we have the base case $N(a) = 1$, for any terminal $a$. I expect this can be adjusted to count the number of sentential forms as well, but I haven't tried to work out the details. This relies crucially on the grammar to be unambiguous. If the grammar is ambiguous, I'm not sure whether there is any efficient algorithm -- I just don't know. For unambiguous grammars, see also https://en.wikipedia.org/wiki/Chomsky%E2%80%93Sch%C3%BCtzenberger_enumeration_theorem, which shows how to count the number of sentences of a particular length, even if the grammar is not finite.
{ "domain": "cs.stackexchange", "id": 17467, "tags": "formal-languages, context-free, search-problem, breadth-first-search, program-synthesis" }
Why does all the voltage has to be dropped in a circuit?
Question: In a simple circuit with a single resistor the entire voltage provided by the cell drops. It is independent of the resistance. Why does this happen? What is the mechanism behind this? I mean why does not it vary with varying resistances. Answer: It might be helpful to think about what would happen if the voltage drop in the resistor was not equal to the voltage gained in the battery. In this case, each time an electron traveled around the circuit, it would gain kinetic energy, since it would gain more energy from the battery than it lost passing through the resistor. Thus, the current would increase. But the increase in current would cause the voltage across the resistor to increase. Eventually, the current would increase to the point that the voltage across the resistor would equal the voltage of the battery. When people say that the voltage around a circuit has to add up to zero, they're talking about circuits in equilibrium. You can see that if the voltages didn't add to zero, that would make the current change so that they do add up to zero. That's why we can assume an equilibrium state exists.
{ "domain": "physics.stackexchange", "id": 43082, "tags": "electric-circuits, electric-current, electrical-resistance, voltage, batteries" }
Quantitative Comparisons of Phylogenetic trees
Question: I am working on a broad phylogenomic analysis of proteins involved in one particular cellular process. I have constructed a phylogenetic tree for each protein. I am now working on comparing those trees in order to extract categories (i. e., allele a of protein a occurs most frequently with allele b of protein b, etc.). I have attempted to construct a super tree using clann, but the tree is extremely difficult to interpret. I would therefore like to carryout a quantitative comparison (and subsequent categorisation) of each each tree, but it is unclear to me how to even begin this analysis. Is there a standardised method for comparison of phylogenetic trees? Answer: I don't know whether it's exactly what you need, but there are formal algorithms for tree comparison. There are basically two approaches: one utilizing tree lengths (branch score distance) and the other one dealing with topologies only (symmetric-difference metric): details and references can be found in the manual to treedist from the phylip-package, which implements both. PAUP* has a command under the same name (treedist), which calculates the symmetric-difference metric only. This metric is very intuitive: it describes the total number of partitions (= splits) present only on one of the two trees.
{ "domain": "biology.stackexchange", "id": 2397, "tags": "bioinformatics" }
Relation between rotation vector derivative and angular velocity when the rotation angle is constant
Question: $\def\va{\vec{\alpha}} \def\vw{\vec{\omega}} \def\vn{\vec{n}}$Let $\va(t)$ be a rotation vector such that its direction is the rotational axis and its length $\alpha=|\va|$ is the angle describing the rotation. In Is there a formula for the rotation vector in terms of the angular velocity vector? the formula $$ \vec{\omega}= \dot{\vec{\alpha}} + \frac{1 - \cos \alpha}{\alpha^2} \left(\vec{\alpha} \times \dot{\vec{\alpha}}\right) + \frac{\alpha - \sin \alpha}{\alpha^3} \left(\vec{\alpha} \times \left(\vec{\alpha} \times \dot{\vec{\alpha}}\right)\right)\, $$ is given which relates angular velocity $\vw$ to the rotation vector $\va$ and its time derivative. If I multiply the formula with $\va$, the two elaborate terms on the right disappear, because both contain a cross product of $\va$ such that their dot product with $\va$ is zero. I get: $$\vw\cdot\va = \dot\va\cdot\va \tag{1}$$ Because $\vw$ and $\va$ are parallel, we also have $$\omega \alpha = \dot\va\cdot\va \tag{1}$$ Now let $\va(t) = \alpha(t)\cdot \vn(t)$ for unit vector $\vn(t)$. Then we get $$ \dot\va(t) = \dot\alpha(t) \cdot\vn(t) + \alpha(t)\cdot\dot\vn(t)\,.$$ In the case $\alpha(t)=const$, and leaving out the $(t)$ for better readability, this simplifies to $\dot\va = \alpha\cdot\dot\vn$ and inserting into (1) results in \begin{align} \omega\alpha = \vw\cdot\va &= \alpha \va \cdot\dot\vn\\ &= \alpha^2 \vn\cdot\dot\vn \end{align} Dividing by $\alpha$ we get $$ \omega = \alpha\vn\cdot\dot\vn\,.$$ Since $\vn(t)$ is a unit vector for every $t$, any change of $\vn(t)$ must always only change its direction, never its length, which means that $\vn\cdot\dot\vn=0$ and therefore $$ \omega = 0$$ in the case $\dot\alpha=0$, even for $\dot\vn\neq0$. Question: How can this be that the axis of rotation changes its direction but $\omega$ and thereby angular momentum is zero? One of my assumptions of how $\va$ works is probably wrong. Yet all I have assumed is that $\va$ is just three numbers that change over time and that it can be decomposed into $\alpha\vn$. OK and that this is in line with the formula cited for $\omega$. Where is the mistake? Or can I have a change in rotation axis without having angular momentum? Answer: Early on you make the assumption that $\vec{\omega}$ and $\vec{\alpha}$ are parallel. This is not in general true. This may have arisen from a basic misconception about the meaning of $\vec{\alpha}(t)$. The direction of $\vec{\alpha}(t)$ is not the instantaneous axis of rotation. The axis-angle variables give you the rotation necessary to obtain the current orientation of a body (for example, at time $t$) relative to a reference orientation (for example, at $t=0$). It is true that any orientation can be expressed in this way: a rotation $\alpha(t)$ about a unit vector $\vec{n}(t)$, which we can put together as a combined vector $\vec{\alpha}(t)\equiv \alpha(t)\vec{n}(t)$. But this rotation depends on the entire history of the trajectory up to time $t$, and as was made clear in the page you referenced, Is there a formula for the rotation vector in terms of the angular velocity vector?, the relation is quite complicated. There is no particular reason why the axis $\vec{n}(t)$ describing the current orientation should have any relation to the direction of the current angular velocity $\vec{\omega}(t)$. One can conceive of a special case where this is true: it is the simple one where $\vec{n}$ has been constant throughout the trajectory, and both $\vec{\omega}$ and $\vec{\alpha}$ have been parallel to $\vec{n}$ for the whole time. So $$ \vec{\omega}(t)=\omega(t)\vec{n} \qquad\text{and}\qquad \vec{\alpha}(t)=\alpha(t)\vec{n} $$ Then the angle of rotation $\alpha(t)$ is just the time integral of the magnitude of the angular velocity $\omega(t)$. In this case, though, things are less interesting. The second and third terms of your first equation vanish identically, so $$\vec{\omega}=\dot{\vec{\alpha}}\qquad\text{and}\qquad \omega=\dot{\alpha} $$ Your derivation is correct until we get to the special case $\alpha(t)=$ constant, which of course correctly implies $\omega(t)=0$. But that is as one would expect, for this special case, it doesn't illustrate anything awry.
{ "domain": "physics.stackexchange", "id": 52521, "tags": "rotational-dynamics, rotational-kinematics, rotation, rigid-body-dynamics, angular-velocity" }
shared_ptr code implementation
Question: I have never used std::shared_ptr before and I don't really know how this smart pointer actually works but I decided to create one to verify my knowledge. Here is my code : namespace myStd { template<class T> class shared_ptr { public : shared_ptr() : refCount(nullptr), t(nullptr) {} shared_ptr(T *p) : refCount(new int(1)), t(p) {} ~shared_ptr() { this->destroy(); } shared_ptr(const shared_ptr &p) : refCount(nullptr), t(nullptr) { if(p.isvalid()) { refCount = p.refCount; t = p.t; if(isvalid()) (*this->refCount)++; } } void destroy() { if(isvalid()) { --(*refCount); if((*refCount) <= 0) { delete refCount; delete t; } refCount = nullptr; t = nullptr; } } shared_ptr& operator =(const shared_ptr &p) { if(this != &p) { if(!p.isvalid()) { this->destroy(); this->refCount = p.refCount; this->t = p.t; if(isvalid()) (*this->refCount)++; return (*this); } if(!isvalid()) { this->refCount = p.refCount; this->t = p.t; if(isvalid()) (*this->refCount)++; return (*this); } else { this->destroy(); this->refCount = p.refCount; this->t = p.t; if(isvalid()) (*this->refCount)++; } } return (*this); } bool isvalid() const {return (t != nullptr && refCount != nullptr);} int getCount() const {if(refCount != nullptr) return (*refCount); else return 0;} T* operator ->() {return t;} T& operator *() {return *t;} private : int *refCount; T *t; }; } What am I missing? Did I implement this smart pointer right? Your suggestions would be appreciated. Answer: What am I missing? Several things. constructor that takes object of type std::nullptr_t constructor that takes object of type shared_ptr<U> where U is derived from T boolean conversion operator. swap operator move semantics Sure there is more. In Smart pointers you always forget something. Did I implement this smart pointer right? YOu implemented the rule of three. So barring any bugs it should be good. Your suggestions would be appreciated. I go into a lot of detail in my articles: Unique Pointer Smart Pointer Constructors Don't use this. It is not very normal to see this-> in C++ code (unlike Java). I actually consider the use of this-> as bad practice. You only need to use this->member if there is some ambiguity between local/parameters and member names. If you have some ambiguity then you have done a bad job at naming and you are using this-> to cover up the problem. Prefer to fix the problem as some poor maintainer is going to come along later and use the wrong variable because of your laziness. I normally turn on the compiler warning that tells my if a local variable is shadowing another thus forcing me to have unique (and meaningful names). One Line One Statement shared_ptr(const shared_ptr &p) : refCount(nullptr), t(nullptr) To me this looks exactly like multiple assignments packed onto the same line. varOne = 5; varTwo = 6; theOtherOne = doStuff(5); I think it is well accepted that one line should have one statement. Why not apply this to your parameter list. It will make reading the code much easier and also validating order of initialization problems. shared_ptr(const shared_ptr &p) : refCount(nullptr) , t(nullptr) { /* Stuff */ } Construct with a null ptr shared_ptr(T *p) : refCount(new int(1)), t(p) {} What happens if you I build with a nullptr? X* ptr = nullptr; shared_ptr<X> data1(ptr); shared_ptr<X> data2(nullptr); // should have its own constructor. Double Check of isvalid() is wastefull If p.isvalid() is true then isvalid() will be true after the copy. shared_ptr(const shared_ptr &p) : refCount(nullptr), t(nullptr) { if(p.isvalid()) { refCount = p.refCount; t = p.t; if(isvalid()) (*this->refCount)++; } } Also this could be much simplified. shared_ptr(const shared_ptr &p) : refCount(p.refCount) , t(p.t) { if(isvalid()) { (*refCount)++; } } Prefer Copy/Swap Idiom for assignment. shared_ptr& operator =(const shared_ptr &p) { if(this != &p) { /* This LOOKS LIKE A BUG */ /* Don't think the ! should be there. */ if(!p.isvalid()) { this->destroy(); this->refCount = p.refCount; this->t = p.t; if(isvalid()) (*this->refCount)++; return (*this); } if(!isvalid()) { this->refCount = p.refCount; this->t = p.t; if(isvalid()) (*this->refCount)++; return (*this); } else { this->destroy(); this->refCount = p.refCount; this->t = p.t; if(isvalid()) (*this->refCount)++; } } return (*this); } Sorry that function is big and clumsy and hard to read. It also does not provide the strong exception guarantee. You modify the content of this object doing exception dangerous work (call destroy) before updating the content of this object. To do any work in exception safe way you need to follow a three step processes. Make a copy into temp. -> Dangerious as exceptions can fly. Swap the temp and current. -> Safe as swap should not throw exceptions. Destroy then temp. -> Safe as the state of current is now good. This 3 step process is ipitimized by the copy and swap idiom. shared_ptr& operator =(const shared_ptr &p) { shared_ptr temp(p); // Constructor copies. Destructor destoryes. temp.swap(*this); // Perform an exception safe transfer of state. return *this; } Lots of people take this one step further. And do the copy in the parameter: shared_ptr& operator =(shared_ptr p) // Notice the pass by value. { // this gets your copy. p.swap(*this); return *this; } Const correctness These two functions do not mutate the state of the object. T* operator ->() {return t;} T& operator *() {return *t;} So they should probably be marked as const.
{ "domain": "codereview.stackexchange", "id": 21875, "tags": "c++, c++11, pointers" }
Unit tests for User class with JUnit 5
Question: This is a follow-up question for Android app class serialization. Some problems have been mentioned in forsvarir's answer. Then, I am following JUnit 5 User Guide to redesign the test cases for User class. Because the part of Save and Load methods are the operations including read and write on storage. It seems that they're not a part of unit testing. The experimental implementation Project name: UnitTestsForUserClass Unit Tests for User class: package com.example.unittestsforuserclass; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Assertions; import java.security.NoSuchAlgorithmException; class UserTest { @org.junit.jupiter.api.Test void getFullName() { Assertions.assertThrows(NoSuchAlgorithmException.class, () -> { User User1 = new User( "Mike", "M12345678", "1990/10/13", "(555) 555-1234", "123456@test.com", "password"); assertEquals("Mike", User1.GetFullName()); }); } @org.junit.jupiter.api.Test void getPersonalID() { Assertions.assertThrows(NoSuchAlgorithmException.class, () -> { User User1 = new User( "Mike", "M12345678", "1990/10/13", "(555) 555-1234", "123456@test.com", "password"); assertEquals("M12345678", User1.GetPersonalID()); }); } @org.junit.jupiter.api.Test void getDateOfBirth() { Assertions.assertThrows(NoSuchAlgorithmException.class, () -> { User User1 = new User( "Mike", "M12345678", "1990/10/13", "(555) 555-1234", "123456@test.com", "password"); assertEquals("1990/10/13", User1.GetDateOfBirth()); }); } @org.junit.jupiter.api.Test void getCellPhoneNumber() { Assertions.assertThrows(NoSuchAlgorithmException.class, () -> { User User1 = new User( "Mike", "M12345678", "1990/10/13", "(555) 555-1234", "123456@test.com", "password"); assertEquals("(555) 555-1234", User1.GetCellPhoneNumber()); }); } @org.junit.jupiter.api.Test void getEmailInfo() { Assertions.assertThrows(NoSuchAlgorithmException.class, () -> { User User1 = new User( "Mike", "M12345678", "1990/10/13", "(555) 555-1234", "123456@test.com", "password"); assertEquals("123456@test.com", User1.GetEmailInfo()); }); } @org.junit.jupiter.api.Test void checkPassword() { Assertions.assertThrows(NoSuchAlgorithmException.class, () -> { User User1 = new User( "Mike", "M12345678", "1990/10/13", "(555) 555-1234", "123456@test.com", "password"); assertEquals(User1.CheckPassword("password"), true); assertEquals(User1.CheckPassword("password1"), false); }); } } User class implementation: package com.example.unittestsforuserclass; import android.content.Context; import android.util.Log; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class User implements java.io.Serializable{ private String fullName; private String personalID; private String dateOfBirth; private String cellPhoneNumber; private String emailInfo; private String password; public User(String fullNameInput, String personalIDInput, String dateOfBirthInput, String cellPhoneNumberInput, String emailInfoInput, String passwordInput) throws NoSuchAlgorithmException // User object constructor { this.fullName = fullNameInput; this.personalID = personalIDInput; this.dateOfBirth = dateOfBirthInput; this.cellPhoneNumber = cellPhoneNumberInput; this.emailInfo = emailInfoInput; this.password = HashingMethod(passwordInput); } public String GetFullName() { return this.fullName; } public String GetPersonalID() { return this.personalID; } public String GetDateOfBirth() { return this.dateOfBirth; } public String GetCellPhoneNumber() { return this.cellPhoneNumber; } public String GetEmailInfo() { return this.emailInfo; } public String GetHash() throws NoSuchAlgorithmException { return HashingMethod(this.fullName + this.personalID); } public String GetHashedPassword() throws NoSuchAlgorithmException { return this.password; } public boolean CheckPassword(String password) { boolean result = false; try { result = this.password.equals(HashingMethod(password)); } catch (Exception e) { e.printStackTrace(); } return result; } // Reference: https://stackoverflow.com/a/4118917/6667035 // fileName cannot contain any path separator public boolean Save(Context context, String fileName) { try { FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE); ObjectOutputStream os = new ObjectOutputStream(fos); os.writeObject(this); os.close(); fos.close(); return true; } catch (IOException i) { i.printStackTrace(); return false; } } public void Load(Context context, String fileName){ try { FileInputStream fis = context.openFileInput(fileName); ObjectInputStream is = new ObjectInputStream(fis); User simpleClass = (User) is.readObject(); is.close(); fis.close(); this.fullName = simpleClass.fullName; this.personalID = simpleClass.personalID; this.dateOfBirth = simpleClass.dateOfBirth; this.cellPhoneNumber = simpleClass.cellPhoneNumber; this.emailInfo = simpleClass.emailInfo; this.password = simpleClass.password; } catch (Exception e){ e.printStackTrace(); } } //***************************************************************************** // Reference: https://stackoverflow.com/a/2624385/6667035 private String HashingMethod(String InputString) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); String stringToHash = InputString; messageDigest.update(stringToHash.getBytes()); String stringHash = new String(messageDigest.digest()); return stringHash; } } All suggestions are welcome. The summary information: Which question it is a follow-up to? Android APP class serialization in JAVA What changes has been made in the code since last question? I am following JUnit 5 User Guide to redesign the test cases for User class. Why a new review is being asked for? If there is any possible improvement, please let me know. Answer: Unittests are (executable) documentation The name of a test method should read like a sentence from the requirements. Beginners should stick with the pattern suggested by Roi Osherove methodName_precondition_expectedResult() Keep AAA - Structure of test methods visible. Test Methods consist of three parts: Arrange Act Assert Others call it "given, when then" but I like this high quality rating analogy from the stock market... Always keep this three parts because this gives you the chance to introduce local variables with descriptive names, that help future readers unfamiliar with your code (which is yourself 5 month later) to guess what's going on here. And no, the setup method is no (complete) replacement for the arange part since the arrangement is always specific to the test method. Two test methods with the exact same arrangement obviously test the same behavior and are redundant (a nice word for "useless" ;o)). Any unittest method covers exactly one single expectation on the codes behavior. That effectively results in one single assertion in a test method. Yes, it is OK to have multiple assertion in a test method, but in that case you must have a good reason for that (given in the test methods name). General coding Adhere to the Java Naming Conventions. Names of methods and variables start with a lowercase letter, names of classes with an uppercase letter. Method names should start with a verb so that they read like an instruction. Names of variables should start with a noun. Exception to that are variables holding or methods returning a boolean which both should start with is, can, has or alike. Do not do work in Constructors. Checks that may lead to exceptions (other then NPEs) should be done before the data are passed to the constructor. Do not hide dependencies. In your method HashingMethod() you use an instance of MessageDigest This is a hidden dependency. You better pass that instance into your class as constructor parameter. Do not mix DTOs with Business logic classes. Any class should be either one, not both. DTOs with business logic will poisen other layers of the application with that. Imagine you want to transfer objects of your User class via network from a client to your server application. Most likely you don't want the other end to know about the hashing...
{ "domain": "codereview.stackexchange", "id": 41367, "tags": "java, object-oriented, unit-testing, android, classes" }
If a planetoid was wet and you spun it would the water move to the equator?
Question: If the moon was alone in space and covered in X feet of water and it began to rotate would it displace to a bias along the equator? Answer: It depends, and the specific parameters are made ambiguous by the example you're using. If the moon was alone in space and covered in X feet of water Specifiers that are really important: Density of the surface moon rock relative to water Does the planetoid have a molten interior? Are we talking about right away or over a billion years? The hydrostatic assumption, which is used to describe planets in the Newtonian sense, predicts that materials will stratify according to density. If this is taken as gospel, then we have contours of constant pressure that lie on a material boundary. However, there are several ways that it won't go so simply in practice. Imagine moon rock with a specific gravity of 1.0. If you spun-up that planetoid, then the water would move, and the rock would remain stationary. It has no physical force causing it to move. But for that matter, the rock could float around anywhere in the ocean without any forces compelling it to go one direction or the other to begin with. Then again, we might just declare the moon to be rigid. Sure, there's a molten center, but this is a long distance from the surface layer mechanics which are relevant here. So the water can move without the rock moving along with it. This leaves some stresses in the rock. If you are a mermaid on the moon's (former) surface, then you will feel a non-normal gravity. In other words, the surface will feel inclined. On the other hand, a sailor on the surface of the ocean will feel perfectly normal gravity under all conditions. If the ocean is sufficiently shallow, it could feasibly pool along the equator and dry up closer to the poles. In the rigidity assumption, this is because the rock doesn't move. In the assumption that the rock density equals the water density, the water moves to the equator simply because it's more mobile. But the rock material might still deform around the poles, in order to still form the perfect hydrostatic ellipsoid shape. However, if we assume a sufficiently molten interior, and rock material heavier than water (which is reasonable), then over a long period of time, the water and rock will reform to create a water-world again.
{ "domain": "physics.stackexchange", "id": 14857, "tags": "newtonian-mechanics, newtonian-gravity, rotational-dynamics, planets" }
Given a permutation of 0..N-1, determine the index of that permutation in the lexicographic ordering of all permutations of 0..N-1, in linear time
Question: There are various $\mathcal O(n \log n)$ or worse solutions, but I'm looking for one that runs in $\mathcal O(n)$, or a proof that none exist. Answer: The 2007 paper Linear-time ranking of permutations gives a linear time ranking algorithm for the lexicographic order, assuming arithmetic on numbers of length $O(n\log n)$ takes constant time. The 2001 paper Ranking and unranking permutations in linear time presents a linear time ranking algorithm not requiring fast arithmetic on large numbers, but not for the lexicographic order. Regarding the latter, it states The whole problem of ranking permutations in lexicographic order seems inextricably intertwined with the problem of computing the number of inversions in a permutation, and it seems that a major breakthrough will be required to do that computation in linear time, if indeed it it possible at all. On the other hand, it does mention an $O(n\log n/\log\log n)$ algorithm for ranking permutations in lexicographic order due to Dietz.
{ "domain": "cs.stackexchange", "id": 4409, "tags": "permutations" }
Wiring & driving TowerPro SG90 servos
Question: I got my hands on a few Tower Pro SG90 9G servos but cannot find their schematics or datasheet anywhere (besides that link). I have the following concerns: Looks like they're rated for 4.8V, but will they tolerate a 5V supply? How do I determine the current they require, in amps, mA, etc.? There's 3 wires: brown, red & yellow-orange, what do each of these guys do? If I had to guess I'd say that red is power, another one is direction, and another one is the position to rotate to Answer: Regarding the voltage, the Amazon listing for this servo gives the operating voltage range to be 3.0 to 7.2V, so it should accept 5V no problem. Regarding the current draw, on the user questions section of the same page, one user stated that these servos drew between 750 - 1000mA when fully loaded. Regarding the wiring, PCB has a great article on servos that says the wiring would go generally how you would think - red is (+), black or brown is (-), and the other wire is signal. It says that Tower servos use red, black, and white wires. Hope this helps!
{ "domain": "robotics.stackexchange", "id": 784, "tags": "rcservo, wiring" }
Calculating time from energy
Question: I am trying to calculate the time of a movement using the energy of the system. If $$E=\frac{m}{2}\dot{x}^2 + V(x)$$ where $V(x)$ is the potential energy (assuming the potential is time-independent) Now this can be solved for t, which gives $$t=\pm \int_{x_0}^x \frac{1}{\sqrt{\frac{2}{m}(E-V(x))}}dx$$ Now, I would like to calculate for a simple freefall from $h$ height,with $v_0=0$. Then $E=mgh$ and $V(x)=mgh$ so it's division by zero... What am I missing here? Answer: E is the initial mgh, a constant. V is mgx, a function of x.
{ "domain": "physics.stackexchange", "id": 22594, "tags": "homework-and-exercises, newtonian-mechanics, energy-conservation" }
Incoming and Outgoing Waves in Quantum Field Theory
Question: I apologize if this seems like a simple question, but I have been agonizing over it recently. In nonrelativistic quantum mechanics, a plane wave of the form $e^{\pm i\vec p\cdot \vec x}$ is called outgoing (incoming for the minus sign). However, in QFT (particularly in the context of the mode expansion) we have terms of the form $$\hat a(p)e^{-ip\cdot x}+\hat a^\dagger(p)e^{ip\cdot x} $$ where $p$ and $x$ are now the usual momentum and position 4-vectors. Books such as Lancaster and Blundell's Quantum Field Theory for the Gifted Amateur say that the plane wave $e^{-ip\cdot x}$ is an incoming wave, and $e^{ip\cdot x}$ is an outgoing wave. However, using just a simple definition of the 4-vector inner product, the former becomes $e^{i(\vec p\cdot \vec x -Et)}$, which would seem to be outgoing, not incoming! Doing the same thing for the wave $e^{ip\cdot x}$ I conclude that it must be incoming, not outgoing. So my question is, in quantum field theory how do we define incoming and outgoing waves? Am I wrong about the nonrelativistic definition? Edit: I used the mostly minus metric signature in this question. Answer: The notion of position space wavefunctions in Quantum Field Theory appears and reveals its usefulness in the context of the LSZ reduction formula. First I wish to emphasize that it has a different nature than in non-relativistic Quantum Mechanics. The reason is that there is no useful generalization of the position operators $X^i$ of non-relativistic QM to QFT. In the absence of those, we don't really have the position basis $|x\rangle$ and without it there is no sense in which we can construct an object $\psi(x)=\langle x|\psi\rangle$ which represents "the probability amplitude for a particle to be found at $x$". Instead, what happens is that we have one inner product on the space of solutions to the linearized field equations which allows us to extract from in/out fields the creation and annihilation operators for one-particle states. Let me be precise with a scalar field. In/out fields are defined by $$\phi_{\rm in/out}(x)=\int \dfrac{d^3 p}{(2\pi)^3 2p^0}\left(a_{\rm in/out}(p)e^{ipx}+a_{\rm in/out}^\dagger(p)e^{-ipx}\right)\tag{1}$$ where I use $(-,+,+,+)$ signature. The in/out fields are related to the interacting fields $\phi(x)$ in the asymptotic regions of spacetime as $$\phi(x)\to \sqrt{Z}\phi_{\rm in/out}(x),\quad \text{as $t\to \pm \infty$}\tag{2}$$ where $Z$ is a quantity called wavefunction renormalization. Now a scattering amplitude can be evaluated as $$\langle \text{out}|\text{in}\rangle=\langle 0|a_{\rm out}(p_1')\cdots a_{\rm out}(p_n')a^\dagger_{\rm in}(p_1)\cdots a_{\rm in}^\dagger(p_m)|0\rangle \tag{3}.$$ The idea of LSZ reduction is to invert (1) to write $a_{\rm out}(p_i')$ and $a_{\rm in}^\dagger(p_i)$ in terms of $\phi_{\rm in/out}(x)$ and then use (2) to relate to the interacting field. One effectively relates an ${\cal S}$-matrix element to correlation functions in a field theory. To see this discussion in more detail (and in particular understand why that $\sqrt{Z}$ appears in (2)) I suggest the book by Itzykson and Zuber. Now the relevant point to your question is: how do we invert (1)? The answer is that there is an inner product on the space of solutions to the KG equation, known as KG inner product, defined by $$(\phi,\psi)_{KG}=-i\int_{\Sigma}d\Sigma n^\mu \left(\phi^\ast \partial_\mu \psi-\psi\partial_\mu \phi^\ast\right)\tag{4}$$ whre $\Sigma$ is a so-called Cauchy slice (a generalization of the surfaces of constant Minkowski time). Using (4) one may show that \begin{eqnarray} (e^{ipx},e^{iqx})_{KG} &=&(2\pi)^3(2\omega_p)\delta^{(3)}(\vec{p}-\vec{q}),\tag{5.1}\\ (e^{-ipx},e^{-iqx})_{KG} &=&-(2\pi)^3(2\omega_p)\delta^{(3)}(\vec{p}-\vec{q}),\tag{5.2}\\ (e^{ipx},e^{-iqx})_{KG} &=&0\tag{5.3}, \end{eqnarray} where we assume that $p^0>0$ and $q^0>0$. These equations are orthogonality relations which allow you to extract the creation and annihilation operators from the in/out fields. In particular observe that: \begin{eqnarray} (e^{ipx},\phi_{\rm in/out})_{KG} &=& a_{\rm in/out}(p)\tag{6.1},\\ (e^{-ipx},\phi_{\rm in/out})_{KG} &=& -a_{\rm in/out}^\dagger(p)\tag{6.2}. \end{eqnarray} Therefore to evaluate (3) we need $a_{\rm in}^\dagger(p)=-(e^{-ipx},\phi_{\rm in})_{KG}$ and $a_{\rm out}(p)=(e^{ipx},\phi_{\rm out})_{KG}$. One then eventually chooses the Cauchy slice $\Sigma$ at $t\to \pm \infty$ to use (2) to write these as integrals involving the interacting field $\phi(x)$ and converts these into integrals over the whole spacetime. In the end one finds the LSZ formula which is what everyone uses to evaluate scattering amplitudes in practice $$\langle \text{out}|\text{in}\rangle = \prod_{i=1}^{m}\prod_{j=1}^n\int d^4x_{i}d^4x'_j e^{-ip_i\cdot x_i}e^{ip_j'\cdot x_j}\langle 0|T\{\phi(x_1)\cdots \phi(x_m)\phi(x_1')\cdots \phi(x_n')\}|0\rangle_{A,C}\tag{7}$$ where the $A,C$ subscript means that we have the connected component of the correlator with external legs removed. With this we can finally answer your question: in QFT position space wavefunctions appear as the solutions to the linearized field equations upon which we project the in/out quantum fields to extract creation and annihilation operators of asymptotic particle states. When we use these to evaluate a scattering amplitude, to get incoming particles we must project on $e^{-ipx}$ and to get outgoing particles we must project on $e^{ipx}$. The final result is the LSZ formula (7) in which the amplitude is obtained by integrating the connected amputated time-ordered correlator against the external wavefunctions. In particular the difference in sign of the exponentials dictates which are the incoming ones and which are the outgoing ones for the reasons that have been explained.
{ "domain": "physics.stackexchange", "id": 89439, "tags": "quantum-field-theory, waves, conventions, fourier-transform, plane-wave" }
spawning spheres in gazebo as simulated point cloud
Question: So I'm working on spawning spheres in gazebo to simulate point clouds for probabilities. I have been able to spawn objects with the command line, rosrun gazebo spawn_model -file /opt/ros/electric/stacks/simulator_gazebo/gazebo_worlds/objects/simple_box.urdf -urdf -x 1.18 -y .91 -z 1.549 -model box1 but it seems when spawning objects this way you can't make them static, or resize the objects. Is there a way to spawn objects with the ability to make them unaffected by gravity and resize-able? Originally posted by ncr7 on ROS Answers with karma: 325 on 2012-07-24 Post score: 0 Answer: You can make a static object .model file and just spawn that. For example, a static box model looks like this: <?xml version="1.0" ?> <model:physical name="small_box_model"> <!-- <xyz> 0.835 -0.55 0.5</xyz> <rpy> 0.0 0.0 30.0</rpy>--> <static>true</static> <body:box name="small_box_body"> <geom:box name="small_box_geom"> <kp>100000000.0</kp> <kd>0.1</kd> <mesh>default</mesh> <size>0.1 0.1 0.1</size> <mass> 0.05</mass> <visual> <size> 0.1 0.1 0.1</size> <material>Gazebo/Red</material> <mesh>unit_box</mesh> </visual> </geom:box> </body:box> </model:physical> By changing the 'static' tag to false, you'll get a object affected by gravity and colliding with other objects. I'm not sure about the scaling of a sphere though, I had some problems with that before (especially with the visuals getting scaled, but the collision model staying at 1m radius). Originally posted by Stefan Kohlbrecher with karma: 24361 on 2012-07-24 This answer was ACCEPTED on the original site Post score: 0
{ "domain": "robotics.stackexchange", "id": 10341, "tags": "ros" }
ros-kinetic-opencv3 and apriltags regression?
Question: Hello list, Using apriltags (link text) worked fine until the last update of kinetic (around 12 december). Now there is a crash in opencv when doing "roslaunch apriltags usb_cam_apriltags.launch" as soon as a tag is being recognized. It seems that removing the assertion solves the problem. See the output below. What can I do? Is there e.g. an easy way to replace the opencv3 code from ros-kinetic-opencv3 by using a (patched) version in /usr/local/bin so that ROS will use that? Thanks in advance, Sietse OpenCV Error: Assertion failed (mtype == type0 || (((((mtype) & ((512 - 1) << 3)) >> 3) + 1) == 1 && ((1 << type0) & fixedDepthMask) != 0)) in create, file /tmp/binarydeb/ros-kinetic-opencv3-3.3.1/modules/core/src/matrix.cpp, line 2542 terminate called after throwing an instance of 'cv::Exception' what(): /tmp/binarydeb/ros-kinetic-opencv3-3.3.1/modules/core/src/matrix.cpp:2542: error: (-215) mtype == type0 || (((((mtype) & ((512 - 1) << 3)) >> 3) + 1) == 1 && ((1 << type0) & fixedDepthMask) != 0) in function create [apriltags-1] process has died [pid 11062, exit code -6, cmd /home/p100213/ROS/ws2/devel/lib/apriltags/apriltags ~image:=/usb_cam/image_raw ~camera_info:=/usb_cam/camera_info ~marker_array:=/apriltags/marker_array ~detections:=/apriltags/detections __name:=apriltags __log:=/home/p100213/.ros/log/09d71dee-e56c-11e7-852c-002481150e15/apriltags-1.log]. Originally posted by Sietse on ROS Answers with karma: 168 on 2017-12-20 Post score: 1 Original comments Comment by pinxian on 2017-12-25: I have the same problem . Any idea? Comment by dpoiesz on 2018-01-16: I'm having a similar issue. Has anyone found a solution? Comment by ashwinvk94 on 2018-01-19: I am facing the same issue. Answer: In apriltags_ros/apriltags/src/TagDetection.cc change line 95, cv::Matx33f ... to : cv::Matx33d cameraMatrix( fx, 0, px, 0, fy, py, 0, 0, 1); (Just f to d) Originally posted by Orhan with karma: 856 on 2018-01-22 This answer was ACCEPTED on the original site Post score: 3 Original comments Comment by Sietse on 2018-01-25: First: the version of apriltags_ros I used was a different one. I now switched to the "regular" and patched it as above. The error does not occur anymore, and tags are detected, with correct id-number. But position/orientation is not given. Always all zero's apart from w. Still anything wrong? Comment by Orhan on 2018-01-25: I pushed changes from my other private repository, everything works fine there. github.com/cosmicog/apriltags_ros (branch: kinetic-devel) Comment by Sietse on 2018-01-25: It works when using this repository! I tested it on my home machine using Lunar. Will later test some more on kinetic. Comment by Sietse on 2018-01-25: Note that the version mentioned in the ros-wiki still has to be corrected. Comment by Cesare on 2018-02-05: Eureka! Matx33f -> Matx33d just works ^_^ Comment by Alex Beh on 2018-02-13: why I cannot find the Matx33d above? I download the package from https://github.com/xenobot-dev/apriltags_ros . Comment by Sietse on 2018-02-13: See my first comment. Use the version from Orhan or patch the version mentioned in the ros-wiki. Comment by Alex Beh on 2018-02-13: I am really new to ROS. so just git clone it to my /catkin_ws/src and run catkin_make @ /catkin_ws ? Comment by Sietse on 2018-02-13: Basically, yes. Comment by gvdhoorn on 2018-02-13: @Alex Beh: please see #q252478. There is a little more to it. Comment by Alex Beh on 2018-02-13: I have successfully install the version from Orhan and rosrun it. But why the problem still come out? Is it because I didn't do calibration of my usb_cam? Comment by Alex Beh on 2018-02-13: I think the code executed for Orhan's package in terminal is different from my previous package. I only know two commands to be executed in terminal, any other commands needed? Terminal 1: roscore Terminal 2: roslaunch apriltagsros example.launch /usbcam_tag.launch Terminal 3: Terminal 4:
{ "domain": "robotics.stackexchange", "id": 29583, "tags": "ros, ros-kinetic, opencv3" }
Moveit motion planning VERY slow
Question: Hello, I made a custom arm with dynamixel motors that I managed to move it with moveit. However, after planning, when I execute the movement, all the intermediate points are very distant in time (roughly 7 seconds between each point). In the log below you can find an extract of the goal with 3 sample points respectively at time 0, 7 and 14s. I tried with another goal and I had 8.5 seconds between each intermediate points... From where this "lag" comes from? do you have an idea? Thank you very much in advance positions: [-0.2684466378799872, -1.1274758790959463, 1.030835089459151, 1.6183497312193513, -0.5108156023659185, -0.9065826456404139] velocities: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] accelerations: [0.0004511662190817926, 0.0, 0.0, 0.0, 0.0, 0.0] effort: [] time_from_start: secs: 0 nsecs: 0 - positions: [-0.2562400395714328, -1.0762276932709398, 0.9839826590823839, 1.5447893388407326, -0.48759680001145106, -0.8653775109410078] velocities: [0.0016593982051817287, 0.006966817898581831, -0.006369246935989043, -0.01, 0.00315642720269342, 0.005601538187469333] accelerations: [3.5373454787627456e-19, -2.8298763830101965e-18, 2.59405335109268e-18, 0.0, -1.29702667554634e-18, -3.5373454787627456e-19] effort: [] time_from_start: secs: 7 nsecs: 356039237 - positions: [-0.2440334412628784, -1.0249795074459334, 0.9371302287056169, 1.4712289464621136, -0.4643779976569836, -0.8241723762416016] velocities: [0.0016593982051817287, 0.006966817898581831, -0.006369246935989043, -0.01, 0.00315642720269342, 0.005601538187469333] accelerations: [-3.5373454787627456e-19, 2.8298763830101965e-18, -2.59405335109268e-18, 0.0, 1.29702667554634e-18, 3.5373454787627456e-19] effort: [] time_from_start: secs: 14 nsecs: 712078475 Originally posted by raphael_leber_cpe on ROS Answers with karma: 16 on 2016-02-12 Post score: 0 Original comments Comment by dornhege on 2016-02-12: To be clear, what the question is about: It is not the planning that is slow, but the time parametrization of the resulting plan is resulting in plans that take to long to execute. Answer: Thank you for your answer dornhege. You are right, sorry. I found my mistake. I had not the expected values in joint_limits.yaml Originally posted by raphael_leber_cpe with karma: 16 on 2016-02-12 This answer was ACCEPTED on the original site Post score: 0
{ "domain": "robotics.stackexchange", "id": 23740, "tags": "ros, moveit, move-group" }
Moveit parametically disable one joint
Question: Hi all, I am currently planning the motion of my robot using <move_group_interface.h>. I am aware that I could deactivate one joint in config files (urdf or srdf). However is there any possibility for instance to exclude the 2. joint for the given motion task. I would like to realize this in a higher level like in the move_group_interface.cpp, because the deactivated joint has to be activated again in different environments. Originally posted by xman236 on ROS Answers with karma: 51 on 2020-08-08 Post score: 2 Original comments Comment by Gates on 2021-03-16: Can you update if you solved it? I am facing the same issue. Comment by fvd on 2021-03-17: Did the current answer not work for you? It looks correct. Comment by Gates on 2021-03-17: No unfortunately I couldn't make the solution work. Here is my trial after the answer: constrained move code. I check if I could make the constraints work at lines 50-52-61, I couldn't set. Then I tried (abnormally) attach the constraint to the goal_pose yet it didn't work. I don't know how/where to attach the constraints apparently... Comment by Gates on 2021-03-17: Also I tried attaching the constraint to my group (arm_group instead of goal_pose) but I get the same error: 'MoveGroupCommander' object has no attribute 'motion_plan_request' I tried using arm_group.set_path_constraints(goal_constraint). It sets only path constraints. arm_group.get_path_constraints() returns something but arm_group.get_known_constraints() returns still nothing. I don't know how to connect the constraints to my motion plan. Answer: Your goal might be achievable with Trajectory Constraints, especially Joint Constraints which you can set. Get your current joint values and construct the TrajectoryConstraint for your disabled joint to stay fixed to that value. Originally posted by pcoenen with karma: 249 on 2020-08-10 This answer was ACCEPTED on the original site Post score: 1
{ "domain": "robotics.stackexchange", "id": 35388, "tags": "ros, moveit, ros-melodic, move-group-interface, move-group" }
How to make a boy fall from the merry-go-round?
Question: I want to make this boy fall in the game and not able to figure out a way or formula which is responsible to make this boy fall from merry go round We know centrifugal force and centrifugal force theory. When a boy standing on merry go round he will experience a centripetal force along with centrifugal force. My question is when & why boy will fall from the merry go round? How to calculate centrifugal force because of this force boy will fall? What is the condition for calculating force acting on a boy when he falls from merry go round? and if there is no centrifugal force then on what basis i should make the boy fall from the marry go round? Answer: As pointed out, centrifugal force is imaginary force. It is just a reaction force to centripetal force, which acts towards the centre. The boy only falls off if the reaction force to centripetal force, $m\frac{v^2}{r}$ is greater than what is holding the boy back, which is friction, defined by $\mu mg$.
{ "domain": "physics.stackexchange", "id": 54376, "tags": "newtonian-mechanics, reference-frames, centripetal-force, centrifugal-force" }
Has optical interferometry been done at radio frequency using heterodyning with a laser in a nonlinear material?
Question: If one collects narrow band optical emission from a large telescope with frequency $f_1$ and mixes it in a nonlinear crystal with laser light of a nearby frequency $f_2$, it would produce two new signals at $|f_1+f_2|$ and $|f_1-f_2|$. The difference signal $|f_1-f_2|$ could be picked up electromagnetically or perhaps it would be detectable as an AC component in a photodetector somehow, perhaps the photodetector would be the nonlinear element itself. Once the signal is electrical, it could be recorded for later playback and offline interferometry, or for transmission over large distances for large baseline optical interferometry, or both. Is this "a thing"? Has anything like this been done or at least tried? Answer: Perhaps I've got it, or them. These may be what I was thinking of, an optical intensity interferometer based on the Hanbury Brown and Twiss effect effect, but down-converting via heterodyning with lasers. However: instead of the heterodyne down-conversion process happening in an optical crystal producing radio waves that are electrically amplified, mixing and detection happens in a semiconductor crystal acting as a photodiode and the output signal being photoelectron current. So this is not exactly what was described in the question. Since this is more likely to be the right way to do the measurement, probably I mis-remembered the conversion to radio followed by electronic amplification. Possibility of Measuring the Width of Narrow Fe II Astrophysical Laser Lines in the Vicinity of Eta Carinae by means of Brown-Twiss-Townes Heterodyne Correlation Interferometry The paper has a nice explanation of the effect and the measurement they are proposing. There is light amplification and photons are bosons, etc. Abstract We consider the possibility of measuring the true width of the narrow Fe II optical lines observed in spectra of the Weigelt blobs in the vicinity of Eta Carinae. The lines originate as a result of stimulated amplification of spontaneous emission of radiation in quantum transitions between energy levels showing inverted population (Johansson & Letokhov, 2002, 2003, 2004). The lines should have a subDoppler spectral width of 30-100 MHz, depending on the geometry of the lasing volume. To make measurements with a spectral resolution of R > 107 and an angular resolution better than 0.1 arcsec, we suggest the use of the Brown-Twiss-Townes optical heterodyne intensity correlation interferometry. The estimates made of the S/N ratio for the optical heterodyne astrophysical laser experiment imply that it is feasible. and more importantly from the introduction: The Brown-Twiss correlation interferometry (Hanbury Brown & Twiss, 1956; Hanbury Brown, 1974), modified by heterodyne detection using a CO2 laser as a local oscillator (Johnson et al., 1974) for the 10 µm region, is well suited to achieve very high angular and spectral resolution simultaneously. We will call this method the Brown-Twiss-Townes (BTT) technique. In the range 0.9-1.0 µm this can be done today by means of two spatially separated telescopes equipped with two heterodyne photoreceivers, e.g. avalanche diodes, and a tunable semiconductor laser diode transporting its radiation via an optical fiber (Sect. 3). A general approach of this method has already been considered and discussed in a non-astronomical journal (Lavrinovich & Letokhov, 1976; Letokhov, 1996). In the present paper, we focus on the use of the BBT correlation heterodyne interferometry to study the Fe II laser lines in the range 0.9-1.0 µm and the appropriate signal-to-noise (S/N) ratio estimates (Sect. 4). And from Section 3: To master new wavelength regions and achieve high spectral resolution levels, the intensity interferometry method was modified to become heterodyne interferometry (Johnson et al., 1974). This technique uses a local monochromatic laser oscillator to produce beats between the light wave of the star of interest and the coherent laser wave of the local oscillator. The method can be considered intermediate between intensity interferometry and direct interferometry. Townes and co-workers made successful observations in the 10-µm infrared window of the atmosphere using a CO2 laser as a local oscillator (Johnsson et al., 1974; Townes, 1977). The baseline used consisted of a pair of auxiliary telescopes spaced a few meters apart at Kitt Peaks solar telescope. M. A. Johnson, A. L. Betz, and C. H. Townes, 1974 10-μm Heterodyne Stellar Interferometer A spatial interferometer for 10-μm wavelength which uses two independent telescopes separated by 5.5 m, heterodyne detection of the infrared radiation, and path equalization by a variable-length rf cable, has given interference fringes from radiation of the planet Mercury. Continuous fringe observations during 4000 sec indicate remarkable stability in the optical-path difference through the atmosphere and the two telescopes, fluctuations between 20-sec averages being about 1/6 of the 10-μm wavelength. D. D. S. Hale et al (2000) The Berkeley Infrared Spatial Interferometer: A Heterodyne Stellar Interferometer for the Mid-Infrared A detailed description is given of the Infrared Spatial Interferometer (ISI), developed at the Space Sciences Laboratory of the University of California at Berkeley, which is a high spatial resolution interferometer for mid-infrared wavelengths. The instrumentation, its capabilities and performance, data analysis, science program, and future plans are all discussed. The system's use of heterodyne detection, analogous to that of a modern radio interferometer, is also compared with the homodyne or direct methods more commonly encountered in the visible and infrared. The ISI has been operating productively on Mount Wilson for the past 10 years measuring materials immediately surrounding stars and their changes as well as some stellar diameters. The new spectral capabilities described here, a recent increase in baseline length, and the upcoming expansion to a closure-phase imaging array provide important additional types of measurements. FIG. 1. Conceptual block diagram of the ISI optics, circuitry, and heterodyne detection system, including laser phase lock and path length compensation systems. Telescope 1 and its trailer, with associated optics and circuitry, is enclosed within the dashed line. Telescope 2 is represented by equipment outside the dashed line. The trailer for telescope 1 is the primary operating location, with the central computer, delay line, correlator, and data acquisition equipment. Telescope 2 and its trailer contains path-length compensation equipment in addition to the necessary optics and detection hardware. When a third telescope is installed, the controls, delay lines, data acquisition, correlators, and other equipment not needed in each single telescope, will be housed in a central station. See also Conceptual Design and Applications of HgCdTe Infrared Photodiodes for Heterodyne Systems, part 2 (big) Conceptual Design and Applications of HgCdTe Infrared Photodiodes for Heterodyne Systems
{ "domain": "astronomy.stackexchange", "id": 5506, "tags": "observational-astronomy, radio-astronomy, interferometry, radio" }
Why can define the electric potential (voltage) in alternating current?
Question: (All SI unit used in this question) The electric potential U is defined in electrostatic field that The electric field is the (negative) gradient of some scaler verctor, if and only if the electirc field is conservative, namely ,Or the Integral of the electric field is $0$ when the path is closed. This is only ture when ,as a consequence of the Faraday's Law. But in alternating current, the current changes, which means the disturbution of the charge varies. This means the integral of a closed path(or curl) of the electric field is definitely non-zero . So can we even define the concept of Electric Potential (The difference of potential is the alternating voltage which is used everywhere in the analysis of alternating current) here? Does that means there is a criterion that the curl of the electric field is approximately $0$ (May be when the frequency is low or because the simple harmonic sine wave “cancel” in a long period)? Thanks for giving a explanation on this. Answer: Yes, when textbooks treat AC circuits without using the full apparatus of Maxwell's equations which take into account all of the electrodynamical aspects of circuits, they are assuming that the fields are such that they vary slowly. For a field that is varying slowly, $${\partial\vec B\over\partial t}=0,$$ therefore Faraday's law implies that electrostatic conditions apply, i.e. $\nabla\times\vec E=0$. It is reasonable to ask one's self: is 60Hz really slowly varying? Well, given that the electric potentials satisfy the wave equation, then yes. Electromagnetic waves travel at the speed of light: $1/\sqrt{\epsilon_0\mu_0}$, thus changes in the circuit are equalized so rapidly that violations slowly varying assumption only become important at much larger frequencies.
{ "domain": "physics.stackexchange", "id": 100264, "tags": "electromagnetism, electric-fields, electric-current, voltage" }
Chess Dictionary Validator from Automatic Boring Stuff with Python
Question: This project is in chapter 5 introduced me to a whole new world of dictionary data structure. To put it briefly, I want to know whether the choice I took between lists, tuples, and dictionaries could've been justifiable calls or not. I'm also not that confident about where putting many return statements correctly and many other beginners' common mistakes that I probably have overlooked. The project's description and the code are shown below. import pprint, copy # Argument from Automate BS with Python chessgood = { '1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking'} # Argument when key/value is ok but its representative value/key pair raises an error chessbad = {'9z': 'bemperor', '10a': 'wking', '3a': 'bprince'} # Argument when a piece is more than allowed (e.g., wpawn more than 8) chessbad2 = {'4a': 'wpawn', '4b': 'wpawn', '4c': 'wpawn','4d': 'wpawn', '4e': 'wpawn', '4f': 'wpawn', '4g': 'wpawn', '4h': 'wpawn', '5a': 'wpawn', '5i': 'wpawn'} def isvcb(dctnry): ''' In this chapter, we used the dictionary value {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking'} to represent a chess board. Write a function named isValidChessBoard() that takes a dictionary argument and returns True or False depending on if the board is valid. A valid board will have exactly one black king and exactly one white king. Each player can only have at most 16 pieces, at most 8 pawns, and all pieces must be on a valid space from '1a' to '8h'; that is, a piece can’t be on space '9z'. The piece names begin with either a 'w' or 'b' to represent white or black, followed by 'pawn', 'knight', 'bishop', 'rook', 'queen', or 'king'. This function should detect when a bug has resulted in an improper chess board. ''' ver = ('a','b','c','d','e','f','g','h') hor = (8, 7, 6, 5, 4, 3, 2, 1) bd = dict() for i in hor: for j in ver: bd.setdefault(str(i) + j, str(i) + j) bdcopy = copy.copy(bd) #pprint.pprint(bdu) side = ('b','w') piece = {'pawn': 8, 'knight': 2, 'bishop': 2, 'rook': 2, 'queen' : 1, 'king': 1} pcs = dict() for m in side: for n in piece: pcs.setdefault(m + n, piece[n]) temp = dict() for k,v in dctnry.items(): temp.setdefault(v, 0) temp[v] += 1 if k in bd and v in pcs and temp[v] <= pcs[v]: bd[k] = v print('Input OK: ', k) elif k not in bd: bd = bdcopy print('Key(s) not in definition: ', k ) elif v not in pcs: bd = bdcopy print('Value(s) not in definition: ', v ) elif temp[v] > pcs[v]: bd = bdcopy print('Value of this piece exceeds threshold: ', v ) pprint.pprint(bd) if bd == bdcopy: return False else: return True print('chessgood: ', isvcb(chessgood), '\n') print('chessbad: ', isvcb(chessbad), ' \n') print('chessbad2: ', isvcb(chessbad2), '\n') I believe I covered all of the possible errors by error-checking using different arguments when calling the function, where: Key of the passed arguments are not on the matrix 1a - 8h Value of the passed arguments are outside from a combination of (white & black) and ('pawn', 'knight', 'bishop', 'rook', 'queen', 'king') All of the value from passed arguments don't exceed the threshold of each piece so that each piece will have aat most 16 pieces (e.g. wpawn is notmore than 8, bking is no more than 1) Show all the invalid input on the command line If there are any other subtle restrictions that I haven't overseen. Please let me know :) The results are shown below: Input OK: 1h Input OK: 6c Input OK: 2g Input OK: 5h Input OK: 3e {'1a': '1a', '1b': '1b', '1c': '1c', '1d': '1d', '1e': '1e', '1f': '1f', '1g': '1g', '1h': 'bking', '2a': '2a', '2b': '2b', '2c': '2c', '2d': '2d', '2e': '2e', '2f': '2f', '2g': 'bbishop', '2h': '2h', '3a': '3a', '3b': '3b', '3c': '3c', '3d': '3d', '3e': 'wking', '3f': '3f', '3g': '3g', '3h': '3h', '4a': '4a', '4b': '4b', '4c': '4c', '4d': '4d', '4e': '4e', '4f': '4f', '4g': '4g', '4h': '4h', '5a': '5a', '5b': '5b', '5c': '5c', '5d': '5d', '5e': '5e', '5f': '5f', '5g': '5g', '5h': 'bqueen', '6a': '6a', '6b': '6b', '6c': 'wqueen', '6d': '6d', '6e': '6e', '6f': '6f', '6g': '6g', '6h': '6h', '7a': '7a', '7b': '7b', '7c': '7c', '7d': '7d', '7e': '7e', '7f': '7f', '7g': '7g', '7h': '7h', '8a': '8a', '8b': '8b', '8c': '8c', '8d': '8d', '8e': '8e', '8f': '8f', '8g': '8g', '8h': '8h'} chessgood: True Key(s) not in definition: 9z Key(s) not in definition: 10a Value(s) not in definition: bprince {'1a': '1a', '1b': '1b', '1c': '1c', '1d': '1d', '1e': '1e', '1f': '1f', '1g': '1g', '1h': '1h', '2a': '2a', '2b': '2b', '2c': '2c', '2d': '2d', '2e': '2e', '2f': '2f', '2g': '2g', '2h': '2h', '3a': '3a', '3b': '3b', '3c': '3c', '3d': '3d', '3e': '3e', '3f': '3f', '3g': '3g', '3h': '3h', '4a': '4a', '4b': '4b', '4c': '4c', '4d': '4d', '4e': '4e', '4f': '4f', '4g': '4g', '4h': '4h', '5a': '5a', '5b': '5b', '5c': '5c', '5d': '5d', '5e': '5e', '5f': '5f', '5g': '5g', '5h': '5h', '6a': '6a', '6b': '6b', '6c': '6c', '6d': '6d', '6e': '6e', '6f': '6f', '6g': '6g', '6h': '6h', '7a': '7a', '7b': '7b', '7c': '7c', '7d': '7d', '7e': '7e', '7f': '7f', '7g': '7g', '7h': '7h', '8a': '8a', '8b': '8b', '8c': '8c', '8d': '8d', '8e': '8e', '8f': '8f', '8g': '8g', '8h': '8h'} chessbad: False Input OK: 4a Input OK: 4b Input OK: 4c Input OK: 4d Input OK: 4e Input OK: 4f Input OK: 4g Input OK: 4h Value of this piece exceeds threshold: wpawn Key(s) not in definition: 5i {'1a': '1a', '1b': '1b', '1c': '1c', '1d': '1d', '1e': '1e', '1f': '1f', '1g': '1g', '1h': '1h', '2a': '2a', '2b': '2b', '2c': '2c', '2d': '2d', '2e': '2e', '2f': '2f', '2g': '2g', '2h': '2h', '3a': '3a', '3b': '3b', '3c': '3c', '3d': '3d', '3e': '3e', '3f': '3f', '3g': '3g', '3h': '3h', '4a': '4a', '4b': '4b', '4c': '4c', '4d': '4d', '4e': '4e', '4f': '4f', '4g': '4g', '4h': '4h', '5a': '5a', '5b': '5b', '5c': '5c', '5d': '5d', '5e': '5e', '5f': '5f', '5g': '5g', '5h': '5h', '6a': '6a', '6b': '6b', '6c': '6c', '6d': '6d', '6e': '6e', '6f': '6f', '6g': '6g', '6h': '6h', '7a': '7a', '7b': '7b', '7c': '7c', '7d': '7d', '7e': '7e', '7f': '7f', '7g': '7g', '7h': '7h', '8a': '8a', '8b': '8b', '8c': '8c', '8d': '8d', '8e': '8e', '8f': '8f', '8g': '8g', '8h': '8h'} chessbad2: False I believe my code is way longer than necessary but I also believe that the result being true should be kept as the first priority. So as someone who has no background in coding. Any input is greatly appreciated. Thank you :) Answer: Naming Let's focus on a single variable, dctnry - a somewhat nasty abbreviation of dictionary. We of course shouldn't name it dict because that's a built-in, but neither name actually says what this is - a chess board that should simply be called board. You can indicate that it's a dictionary, but there's a better way to do it - type hints, like board: Dict[str, str]. isvcb is likewise impenetrable and should instead be is_valid or is_valid_board. Also, the textbook made a poor decision in suggesting isValidChessBoard - the Python standard is lower_snake_case, i.e. is_valid_chess_board. Don't use the name bd - call it perhaps full_board, and pieces instead of pcs. temp needs a better name as well. Later down, your piece dictionary should be pieces because it's a collection. Range hor should not use a manual tuple, and should instead use range(8, 0, -1). Boolean expressions if bd == bdcopy: return False else: return True should simply be return bd != bdcopy Dictionary literals pcs = dict() for m in side: for n in piece: pcs.setdefault(m + n, piece[n]) can simply be pieces = { m + n: piece_value for m in side for n, piece_value in piece.items() } I don't see a need for setdefault, since I think the indexes being visited will be unique.
{ "domain": "codereview.stackexchange", "id": 40169, "tags": "python, beginner, algorithm, python-3.x, validation" }
Graphs in which every minimal separator is an independent set
Question: Background: Let $u, v$ be two vertices of an undirected graph $G=(V,E)$. A vertex set $S\subseteq V$ is a $u,v$-separator if $u$ and $v$ belong to different connected components of $G-S$. If no proper subset of a $u,v$-separator $S$ is a $u,v$-separator then $S$ is a minimal $u,v$-separator. A vertex set $S\subseteq V$ is a (minimal) separator if there exist vertices $u, v$ such that $S$ is a (minimal) $u,v$-separator. A well-known theorem of G. Dirac states that a graph has no induced cycles of length at least four (called triangulated or chordal graph) if and only if every of its minimal separators is a clique. It is also well-known that triangulated graphs can be recognized in polynomial time. My questions: What are graphs in which every minimal separator is an independent set? Are these graphs studied? And what is the recognition complexity of these graphs? Examples for such graphs include trees and cycles. Answer: Your graphs have been characterized by this paper http://arxiv.org/pdf/1103.2913.pdf. Edit: In the paper above it is proved that graphs in which every minimal separator is an independent set are exactly those containing no cycle with exactly one chord. Graphs containing no cycle with exactly one chord have been studied in depth by Trotignon and Vuskovic, A Structure Theorem for Graphs with No Cycle with a Unique Chord and Its Consequences, J. Graph Theory 63 (2010) 31-67 DOI. As a result of this paper, these graphs can be recognized in polynomial time. (However, this paper did not point out the connection to independent minimal separators!) Edit (17 Sept 2013): Very recently (see here), Terry Mckee describes all graphs in which every minimal vertex separator is a clique or an independent set. It turns out that these are the ''edge sums'' of chordal graphs and graphs in which every minimal vertex separator is an independent set.
{ "domain": "cstheory.stackexchange", "id": 2614, "tags": "reference-request, graph-theory, graph-algorithms" }
Two addresses point to the same data - is the data then stored 2 times in the cache?
Question: Let's say a program reads the addresses 0x00 cd 10 54and0x00 cd 10 50. The tag size and and index size added are just 4 bits, the cache has 8 blocks to 8 Bytes and thus 4 together make a set. The CPU is 32 bit. Then above addresses would point to: 0x00 cd 10 50: ca 01 6b 7f ff 00 10 ee ff 41 45 e8 00 a7 56 00 and would want to write ca 01 6b 7f ff 00 10 ee into set 0 with tag 0x00 cd 10 5 Let's say further say, the cache were empty beforehand. Is the data now written once or two times? Answer: To answer the question: The read addresses are always rounded down to the next cache line address, then it will be looked up, whether an cache entry already matches this address. In case yes: Then the address will just be ignored. Nothing further happens. In case no: Then the data corresponding to the address will be load into the cache.
{ "domain": "cs.stackexchange", "id": 8192, "tags": "cpu-cache" }
Is there a difference between a postulate and a principle in physics?
Question: Is there a difference between a postulate and a principle in physics? Both seem unproved statements taken as true. If thats correct, why the different names? Answer: A postulate is an (usually fundamental) assumption a writer makes in order to discuss a subject in a coherent fashion. Examples of postulates are the Born rule in quantum mechanics (which defines how the wave function is to be interpreted), or in classical mechanics the existence of a Lagrangian (which defines the starting point of theoretical mechanics). A principle is a more or less universally observed (usually fundamental) fact. Examples of principles are the second law of thermodynamics (universal dissipation), the principle of relativity (independence of the reference frame), or Heisenberg's uncertainty relation. A hypothesis is a theoretical assumption made to develop a (usually alternative) theory. Examples are Planck's and Einstein's hypothesis of quantized light, or the existence of supersymmetry. One can turn a principle or hypothesis into a postulate, but not a postulate into a principle. Edit2: Note that it is possible that a principle is derived from a set of postulates. This reflects the fact that there is is some freedom in setting up the foundations. For example, the second law of thermodynamics can be derived from statistical mechnaics, and the principle of relativity can be derived from the postulate of Lorentz invariance.
{ "domain": "physics.stackexchange", "id": 4506, "tags": "terminology" }
Is ROS able to cancel the limit of karma to upload pictures?
Question: If the new user of ROS have some pictures to describe question clearly,it is very sad to see that he doesn't have enough karma to upload pictures. So I ask if there is possible to make new user also can upload pictures to describe his/her questions. Thank you~ Originally posted by sam on ROS Answers with karma: 2570 on 2011-09-13 Post score: 4 Answer: The karma requirement to upload is an anti-spam/abuse measure. The current requirement is 20 points to upload, which is only two upvotes, or several comments. Originally posted by tfoote with karma: 58457 on 2011-09-16 This answer was ACCEPTED on the original site Post score: 7 Original comments Comment by Eric Perko on 2011-09-17: There a number of online services that you could upload a picture to and then post a link to that hosted image. For example, http://imgur.com/ , http://imageshack.us/ or even a public gallery on something like Picasa or Dropbox. Comment by sam on 2011-09-16: For example: this link: http://answers.ros.org/question/2144/rviz-sensor-data-does-not-rotate , which doesn't have permit to upload picture,so he uses a lot of words to describe it. I also have similar question,but failed to compare with this question. Comment by sam on 2011-09-16: Karma couldn't prevent spam message,why just prevent picture uploading? Is picture upload will cause big problem for ROS server? Thank you~
{ "domain": "robotics.stackexchange", "id": 6679, "tags": "ros, meta, answers.ros.org" }
Symmetry of Bloch Hamiltonian
Question: If a crystal system preserve a symmetry C, why its Bloch Hamiltonian satisfy $H(C\vec k)=CH(\vec k)C^{-1} $ Answer: That a Hamiltonian preserves a symmetry means $$ [H, C] = 0 \Rightarrow CHC^\dagger = CHC^{-1} = H$$ For a unitary symmetry operator $C$ (or anti-unitary if it is time reversal). The Hamiltonian of a crystalline condensed matter system written in terms of the Bloch matrix is: $$ H = \sum_{\vec k} \psi^\dagger(\vec k) H(\vec k) \psi(\vec k) $$ Where $$\psi(\vec k) = \begin{pmatrix} \vdots \\ c_i(\vec k) \\ \vdots \end{pmatrix}.$$ And $c_i(\vec k)$ are the annihilators for electrons at $\vec k$ in state $i$ (which is a combined index of spin and band). As $C$ is applied to $\vec k$, it must be a spatial symmetry (that is a lattice symmetry). The transformation of $\psi(\vec k)$ under $C$ is easily obtained by argument. $C$ is a spatial transformation, thus $C\psi(\vec k)C^{-1}$ does the following: the coordinates are transformed. a particle with momentum $\vec k$ is destroyed in the new coordinates. the space rotation is undone leaving a particle with momentum $C \vec k$ destroyed in the original coordinates. I effect this means that $C\psi(\vec k)C^{-1} = \psi(C\vec k)$. Using the above results: $$ H = CHC^{-1} = \sum_{\vec k} C\psi^\dagger(\vec k)C^{-1}C H(\vec k) C^{-1}C \psi(\vec k)C^{-1}. $$ As $C\psi(\vec k)C^{-1} = \psi(C\vec k)$, $C H(\vec k) C^{-1} = H(C\vec k)$ must hold, in order to assure the equality to $H$ (which is then shown by relabelling the summation variable $\vec k' = C\vec k$).
{ "domain": "physics.stackexchange", "id": 22162, "tags": "quantum-mechanics, condensed-matter, symmetry" }
Will the Navigation2 GPS WPF be backported to Humble?
Question: I saw that a GPS Waypoint Follower including a demo was very recently merged into the main branch of the nav2 repository, great work! (PR #2814; demo). The GPS WPF has already been backported to the ROS2 Iron distribution (PR #3837). Will there also be a backport to ROS2 Humble, since it has LTS? I already tried to do the backport myself and cherry-picked the respective commit, but it seems like there are more API changes in nav2 that need to be migrated as well. Does anybody know what changes are needed for the GPS WPF to work with Humble? I couldn't find an up-to-date overview with all breaking changes in nav2 between Humble and Iron. Answer: No. It relies on items not available in Humble. Please upgrade to Iron or newer to use GPS Waypoint Follower
{ "domain": "robotics.stackexchange", "id": 38653, "tags": "ros2, ros-humble, nav2" }
Movie selection app
Question: I'm new to Angular and I would like some advice on how I can improve my code. The main things that I want to focus on are decoupling and code correctness. HTML: <body ng-controller="myController as myCtrl"> <fieldset> Select movie to display: <button ng-click="myCtrl.change('mortalkombat')">Mortal Kombat</button> <button ng-click="myCtrl.change('princessbride')">Princess Bride</button> <button ng-click="myCtrl.change('sherlockholmes')">Sherlock Holmes</button> <button ng-click="myCtrl.change('tmnt')">TMNT</button> <button ng-click="myCtrl.change('tmnt2')">TMNT2</button> </fieldset> <div ng-show="myCtrl.movie !== ''"> <h1>{{myCtrl.info[0] + " (" + myCtrl.info[1] + ")"}}</h1> <div id=outerbox> <div id=overview> <div> <img ng-src="{{myCtrl.movie}}/overview.png" alt="general overview" /> </div> <dl ng-repeat="over in myCtrl.overview"> <dt>{{over.split(':')[0]}}</dt> <dd>{{over.split(':')[1]}}</dd> </dl> </div> <div id=reviews> <div id=banner> <img ng-src="{{myCtrl.pic}}" alt="{{myCtrl.alt}}"/> {{myCtrl.info[2] + "%"}} </div> <div class=revcol> <span ng-repeat="rev in myCtrl.reviews | limitTo : (myCtrl.reviews.length / 2 |number:0)"> <p> <img ng-src="{{myCtrl.image(rev['type'])}}" alt="{{rev['type']}}"/> <q>{{rev['comment']}}</q> </p> <p> <img src="/critic.gif" alt="Critic"/> {{rev['name']}} <br/> {{rev['from']}} </p> </span> </div> <div class=revcol> <span ng-repeat="rev in myCtrl.reviews | limitTo : -(myCtrl.reviews.length / 2)"> <p> <img ng-src="{{myCtrl.image(rev['type'])}}" alt="{{rev['type']}}"/> <q>{{rev['comment']}}</q> </p> <p> <img src="/critic.gif" alt="Critic"/> {{rev['name']}} <br/> {{rev['from']}} </p> </span> </div> </div> <div id=footer> <p>(1-{{myCtrl.reviews.length}}) of {{myCtrl.reviews.length}}</p> </div> </div> JS: (function(){ var app = angular.module('myApp', []); app.controller('myController', ['$http', function($http){ this.movie = ''; var myApp = this; myApp.info = []; myApp.overview = []; myApp.over = []; myApp.pic = ''; myApp.alt = ''; myApp.reviews = []; this.change = function(movie){ this.movie = movie; $http.get("./" + movie + "/info.txt").success(function(data){ myApp.info = data.split('\n'); console.log(myApp.info); myApp.rank(); }); $http.get("./" + movie + "/overview.txt").success(function(data){ myApp.overview = data.split('\n'); console.log(myApp.overview); }); $http.get("./" + movie + "/reviews.json").success(function(data){ myApp.reviews = data; console.log(myApp.reviews); }); }; this.rank = function(){ if(myApp.info[2] >= 60){ myApp.pic = "/freshbig.png"; myApp.alt = "Fresh"; } else{ myApp.pic = "/rottenbig.png"; myApp.alt = "Rotten"; } }; this.image = function(r){ if(r === 'FRESH'){ return "/fresh.gif"; } else{ return "/rotten.gif"; } }; }]); })(); Answer: I think you need to decouple the view (html part) from the controller. You can do this by using $scope. For example, instead of writing <span ng-repeat="rev in myCtrl.reviews | limitTo : (myCtrl.reviews.length / 2 |number:0)"> You should <span ng-repeat="rev in reviews | limitTo : (reviews.length / 2 |number:0)"> In the controller you put reviews in the $scope. Please see this doc https://docs.angularjs.org/tutorial/step_02
{ "domain": "codereview.stackexchange", "id": 11458, "tags": "javascript, beginner, html, angular.js" }
Does learning conjunctions with malicious noise reduce to learning conjunctions with random noise?
Question: In Feldman-Gopalan-Khot-Ponnuswami 06 the authors show that agnostically learning parities reduces to learning parities with random classification noise. They also remark (among other things) that learning conjunctions in this model is NP-hard. Though I can't remember the source right now, I also recall that a random projection argument gives a reduction from learning parities with malicious noise to learning parities with uniform random noise. Is there a reduction from learning conjunctions with malicious noise to learning conjunctions with random noise? Answer: Let me clarify the question a bit first: Agnostic learning conjunctions is known to be NP-hard only if the learner needs to be proper (output a conjunctions as a hypothesis) and work for any input distribution. The reductions in FGKP06 are for the uniform distribution and to the best of my knowledge there is no similar result for general distributions. But in either case the answer to your question is "no" (in the sense that such a reduction is not known and unlikely to exist). Learning conjunctions with random (classification) noise is an easy problem that was solved in a paper of Anguin and Laird "Learning From Noisy Examples" from 1988 that introduced the model of random noise (see also Kearns 1993 paper on Statistical Queries) Learning conjunctions with malicious noise is at least as hard as agnostic learning of conjunctions which is believed to be a hard problem (even over the uniform distribution it is at least as hard as learning log-n sparse parities with noise)
{ "domain": "cstheory.stackexchange", "id": 3186, "tags": "lg.learning, reductions" }
Prime generator
Question: I'm coming from a Python background(look at indentation :) ) and trying to learn basics of C++. I wrote a simple prime generator, I know there is better algorithms, but I want advices about coding style, inconsistencies, or better language use. Here is my main.cpp: #include <iostream> #include "PrimeGenerator.h" using namespace std; int main(){ PrimeGenerator *generator; generator = new PrimeGenerator(); for(int i=0;; i++){ generator->addPrime(); cout<<generator->getPrimes()->back()<<endl; } delete generator; #I know this is unnecessary at the end of program, but I think it is a better practice. return 0; } And PrimeGenerator.h: #pragma once #include <list> #include <iostream> typedef std::list<unsigned long long int> PrimeList; class PrimeGenerator{ PrimeList *primes; public: PrimeGenerator(); ~PrimeGenerator(); PrimeList *getPrimes(); void addPrime(); }; PrimeGenerator::PrimeGenerator(){ primes = new PrimeList; primes->push_back(2); primes->push_back(3); } PrimeGenerator::~PrimeGenerator(){ delete primes; } void PrimeGenerator::addPrime(){ unsigned long long int num = primes->back()+2; while(true){ bool isPrime = true; for(auto it=primes->begin(); it!=primes->end(); ++it){ if(*it > (num / 2)) break; if((num % *it) == 0){ isPrime = false; break; } } if(isPrime){ primes->push_back(num); break; } num += 2; } } PrimeList *PrimeGenerator::getPrimes(){ return primes; } Answer: Your indentation style is unusual for C++. There are a variety of styles used in C++, I recommend you take a look at them, http://en.wikipedia.org/wiki/Indent_style, pick one you like. As it is you are combing elements of several styles. We don't need more indentation styles, so use a standard one, don't invent your own. #include <iostream> #include "PrimeGenerator.h" using namespace std; Many people use this, but I recommend against it. It looks doing a from std import * in python. I think its better to just use the prefix. int main(){ PrimeGenerator *generator; generator = new PrimeGenerator(); You can combine this into one line: PrimeGenerator * generator = new PrimeGenerator(); You can also avoid using a pointer altogether and write: PrimeGenerator generator; for(int i=0;; i++){ I think you are missing the middle element, as it is this is an infinite loop generator->addPrime(); cout<<generator->getPrimes()->back()<<endl; I'd add spaces around the << } delete generator; #I know this is unnecessary at the end of program, but I think it is a better practice. If you use the pointerless version I suggested, it will automatically be destroyed at the end of main. return 0; } #pragma once This may not work on all compilers, so be careful. #include <list> #include <iostream> typedef std::list<unsigned long long int> PrimeList; List is a linked list, unlike lists in python which are resizable arrays. Linked lists are almost always the wrong choice as a datastructure. Perhaps a vector would be better? Vectors act like python lists. unsigned long long int can be written as unsigned long long. You also repeat it often enough creating a typedef might be a good idea. class PrimeGenerator{ PrimeList *primes; Don't make this a pointer. Just use the object directly. public: PrimeGenerator(); ~PrimeGenerator(); PrimeList *getPrimes(); void addPrime(); }; PrimeGenerator::PrimeGenerator(){ primes = new PrimeList; If you avoid make primes a pointer like I suggest, this is unneccesary. primes->push_back(2); primes->push_back(3); } PrimeGenerator::~PrimeGenerator(){ delete primes; } If you avoid making primes a pointer like I suggest, this is unneccesary. void PrimeGenerator::addPrime(){ unsigned long long int num = primes->back()+2; while(true){ bool isPrime = true; for(auto it=primes->begin(); it!=primes->end(); ++it){ if(*it > (num / 2)) break; This limitation isn't obvious, a comment explaining would be good. if((num % *it) == 0){ Operator precedence rules were defined to make sense, use them. isPrime = false; break; } } if(isPrime){ primes->push_back(num); break; } num += 2; } } Your logic can be simplified: bool isPrime = false; unsigned long long int num = primes->back(); while(!isPrime) { num += 2; for(auto it = primes->begin(); it != primes->end(); it++) { if(*it > num / 2) { break; } if( num % *it == 0 ) { isPrime = false; break; } } } primes->push_back(num); I try to avoid using break when possible. Basically, I try to restrict to cases where it is skipping the rest of the loop as an optimisation. If the breaks were removed, the code would be valid but slower. PrimeList *PrimeGenerator::getPrimes(){ return primes; }
{ "domain": "codereview.stackexchange", "id": 5411, "tags": "c++, beginner, primes" }
Search function for books
Question: I was making a library program for trying to practice C++. I wanted to use a vector to store all the books, the books being a struct to hold the general things the books would have. struct Book { string bookName; // book's name string bookAuthor; // book's author string bookID; // a random generated string int bookType; // what type of book }; The books in the library would be stored in a vector. To find one of these books I used a function that takes in a bookId parameter and uses it to find the book. Book LibrarySystem::LocateBook(string bookId) { /* May not be the fastest search algorithm */ for (int i = 0; i <= mBooks.size(); i++) { Book result = mBooks[i]; if (bookId == mBooks[i].bookID) { return result; } else { cout << "FAILED TO FIND " + bookId << endl; } } } This works but I was wondering if it could be faster. Looking at it, I am going through it one by one checking if the bookId is equal to the one provide in the parameter which seems slow. I did do a small test to check if it all worked. I created a function: string LibrarySystem::BookDataOutput(string bookId) { Book book = LocateBook(bookId); string data = "Book author: " + book.bookAuthor + "\n" + "Book name: " + book.bookName + "\n" + "Book type: " + to_string(book.bookType) + "\n" + "Book Id: " + book.bookID; return data; } Which outputs a single string with all the book's information. It uses LocateBook to find the the book with the bookId. I run in main: int main(int args, char* argv[]) { /* Seed the random generator */ srand(time(NULL)); LibrarySystem library; library.RegisterBook("Test1", "Test1", BOOK_TYPE::Adult, "test1"); cout << library.BookDataOutput("test1") << endl; cin.get(); } and the output is: Book author: Test1 Book name: Test1 Book type: 5 Book Id: test1 Which matches all the information I provided. Answer: Since your search is only by 1 parameter, a map<string,Book> would work a lot better than a vector. map<string,Book> mBooks; string LibrarySystem::BookDataOutput(string bookId) { Book book = mBooks[bookId]; string data = "Book author: " + book.bookAuthor + "\n" + "Book name: " + book.bookName + "\n" + "Book type: " + to_string(book.bookType) + "\n" + "Book Id: " + book.bookID; return data; }
{ "domain": "codereview.stackexchange", "id": 23632, "tags": "c++, search" }
Does entropy increase with a decrease or with an increase in a system’s temperature?
Question: I was trying to understand why in a heat engine there is an increase in entropy. If heat (lower) quality energy is converted to work (higher quality energy), even if not all, why wouldn’t entropy decrease?! And I got to a website that explained, that is, what I gathered from it was that, high temperature heat (heat from a higher temperature source) had more quality, a higher ability to be turned into work, than heat from a lower temperature source. [I get that it is most likely wrong to state it like this, but it’s the reasoning I made]. And so, high quality heat would come in the machine, some would be turned into work and some other would be turned into a much lower quality heat, so that, the resulting balance would be an increase in entropy. Less from the work exiting the system, but much more from the lower quality heat energy also being transferred from it, resulting in more entropy overall. (Whichever other system work was done on would have its entropy decreased, more mechanical energy, but the surroundings would end up with a much higher entropy, lower quality thermal energy, lower temperature.) Here’s the picture they have: Which made sense to me because at lower temperatures energy is much more “spread” and not so “concentrated”. But then, I read somewhere else, (and in many other places too, so this must be “where it’s at”, it must be correct) that: “i understand that as temperature increases, entropy increases as well, as there are more quanta of energy and more thermal states(energy levels) available.” Which also makes sense to me: a macrostate has more entropy if it has a greater number of microstates associated with it. Higher temperature -> more possible energy levels -> more possible microstates -> higher entropy. So how can I make sense of both things? I get the feeling they are both right in some way and I just don’t know how to connect them. Does entropy increase with a decrease or with an increase in a system’s temperature? I apologize for the long question and for the, most likely, wrong statements in it. Also, if it would be easy to just “google it by myself”. I have already read some other questions here, but I haven’t understood it yet. Thank you. References: To the image: http://energyeducation.ca/encyclopedia/Entropy To the quote: https://www.physicsforums.com/threads/effect-of-temperature-on-entropy.517807/ Answer: Change in entropy is proportional to the reciprocal of temperature. So a lower temperature means less entropy, but higher temperature means less entropy per unit of energy. All else being equal, adding heat to a cold object increases entropy more than adding it to a hot one. Let's say you have a cold reservoir at 100 K and a hot one at 500 K (both have one unit of heat capacity). You extract work, and at the end they're both at 300 K. You started with log(100)+log(500) entropy, and ended with 2log(300), an increase of .255. When you started, most of the heat was in the hot reservoir, where it "counted less" for entropy, and then you moved it to the cold reservoir, where it "counts more" for entropy. Another way of thinking about it: for energy, it's the sum that matters. But for microstates, it's the product; the total number of microstates for the system involving both reservoirs is not the sum of microstates of the hot and cold reservoirs, but the product: if the cold reservoir has n microstates, and the hot one has m, then there are n*m different combinations of sub-microstates. So if you take away microstates from the hot reservoir, and add them to the cold one, then the total number of microstates increases.
{ "domain": "physics.stackexchange", "id": 48570, "tags": "thermodynamics, temperature, entropy, heat-engine" }
Minimum Number of People Such That No Two People Know the Same Two People
Question: In a population of $n$ people, each person knows $k$ other people and each person is known by the same $k$ people. However, no two people, p1 and p2, know the same two people p3 and p4. What is the minimum $n$ such that this is possible for a given $k$? Or, in other words, what's the minimum number of nodes that must exist such that it is possible to connect each node to $k$ other nodes while not allowing a cycle of length 4? Also, if it is possible, is there a program that can generate these graphs? I don't have much on this problem yet besides a weak lower bound of $n\geq k^2-k+2$. In the graphs below, an edge means that the two people it connects know each other. In 1), this is a demonstration of what we don't want, both A and C know D and B. In 2) these are configurations that work for k=2. For k=2, n=3 and all n>4 work. In 3) n=10, this is the smallest possible configuration for k=3. Answer: The comment of Carlos actually gives an upper bound. There is a much better (and almost tight) upper bound for $k+1$ being a prime number: $n=k(k+1)$. The construction is a classical result in extremal graph theory, namely $C_4$-free $k$-regular graphs, which can be found here. The vertices are labeled with $(a,b)$ where $1\leq a\leq k, 0\leq b\leq k$. Two vertices $(a,b)$ and $(c,d)$ are linked if and only if $ac\equiv b+d\mod (k+1)$. Notice that for any given pair $(a,b)$ the number of solutions $(c,d)$ is exactly $k$, so the graph is $k$-regular. To see the graph is $C_4$-free, consider the following congruence equations $$\left\{ \begin{array}{ll}ax\equiv b+y\mod (k+1)\\ cx\equiv d+y\mod (k+1)\end{array} \right.$$ Since these imply $(a-c)x\equiv b-d \mod (k+1)$, and $k+1$ is prime, there is at most one solution whenever $(a,b)\neq (c,d)$, so the graph contains no $4$-cycle. There are many other constructions among this context, for instance, when $k-1$ is a prime power there is a construction of size $n=2(k^2-k+1)$ with bipartite incidence graph (See, e.g., here).
{ "domain": "cs.stackexchange", "id": 9976, "tags": "graphs, trees" }
How to understand that the strong nucleair force his reach is so short?
Question: I thought that de radius of the strong force is about 1/r7. The elekctromagnetic and gravity force is with a radius of about 1/r2. I understand that for those last ones twice as far away gives a four times weaker radiation per surface and three times further away gives a nine times weaker radiation per surface. It is good to understand. But how can you explain that such a strong force loose so fast of its strength? Does it have somthing to do with the fact that the gluons creating the force are so different from photons? Answer: Actually, the stronge force does not diminish with distance. When you pass a certain length, it stays fixed in a figure, about 10.000 Newtons. related : About free quarks and confinement
{ "domain": "physics.stackexchange", "id": 27844, "tags": "strong-force" }
Stability of equilibrium points
Question: For a spinning top, the linearised equation in the angle $\theta$ when the top is spinning about its axis of symmetry, which is vertical, is of the form $$A\ddot\theta+\left(\frac{C^2n^2}{4A}-Mgh\right)\theta=0.$$ Why should we require that the bracket coefficient be positive if we want the top to be stable, i.e. if we want small disturbances to remain small? Answer: Here's the math. Suppose you have an equation of the form $$ \ddot\theta +\alpha\theta = 0 $$ If $\alpha <0$, then we can write $\alpha = -\omega^2$ for some $\omega >0$ and the general solution becomes $$ \theta(t) = Ae^{\omega t} + Be^{-\omega t} $$ In particular, notice that these solutions are not oscillatory. In fact, the solution blows up exponentially as a function of $t$. Consider, for example, the following initial conditions: $$ \theta(0) = 0, \qquad \dot\theta(0) = \omega_0 $$ then we get $$ A+B = 0, \qquad A-B=\frac{\omega_0}{\omega} $$ and the solution becomes $$ \theta(t) = \frac{\omega_0}{\omega}\frac{e^{\omega t} - e^{-\omega t}}{2} $$ Notice, in particular, that no matter how small the initial velocity $\dot\theta(0) = \omega_0$ is, the solution has the property that $\theta(t)$ leaves the neighborhood of $\theta(0)$ for sufficiently large $t$. On the other hand, if $\alpha >0$, then the equation we want to solve is simply the equation for simple harmonic motion with oscillatory solutions that remain in a vicinity of the initial position for all times.
{ "domain": "physics.stackexchange", "id": 9125, "tags": "homework-and-exercises, stability" }
Unable to compile main.cpp for avr_bridge
Question: I have been trying to follow the "Hello Tutorial" for avr_bridge, and when I run "make" after creating main.cpp, I get this error message: uav@UAV-PC-2:~/ros_tutorials/avr_bridge_callResponse$ make [ 5%] Building CXX object CMakeFiles/firmware.dir/src/main.cpp.o /home/uav/ros_tutorials/avr_bridge_callResponse/src/main.cpp:26: error: variable or field ‘response’ declared void /home/uav/ros_tutorials/avr_bridge_callResponse/src/main.cpp:26: error: ‘Msg’ was not declared in this scope /home/uav/ros_tutorials/avr_bridge_callResponse/src/main.cpp:26: error: ‘msg’ was not declared in this scope /home/uav/ros_tutorials/avr_bridge_callResponse/src/main.cpp: In function ‘void setup()’: /home/uav/ros_tutorials/avr_bridge_callResponse/src/main.cpp:48: error: ‘response’ was not declared in this scope make[2]: *** [CMakeFiles/firmware.dir/src/main.cpp.o] Error 1 make[1]: *** [CMakeFiles/firmware.dir/all] Error 2 make: *** [all] Error 2 Originally posted by UAV on ROS Answers with karma: 25 on 2011-07-05 Post score: 0 Answer: Hi, avr_bridge is in the middle of being phased out in favor of the new, soon to be released/announced rosserial pkg. We are in the middle writing the documentation for rosserial which you can find here. You should be able to use most of the documentation by the end of today. Anyway, it looks like your cmake file is just incorrect or you havent generated the avr_ros files. However, I wouldn't spend any time working with avr_bridge. I will actually be deleting the avr_bridge repo next week after we formally announce rosserial. Originally posted by adasta with karma: 508 on 2011-07-05 This answer was ACCEPTED on the original site Post score: 1
{ "domain": "robotics.stackexchange", "id": 6039, "tags": "ros" }
Compute count of unique words using ES6 sets
Question: I have written a function which counts how many unique words are included in a given text. The source-code: const computeCountUniqueWords = (strToExamine) => { let parts = strToExamine.split(" "); let validWords = parts.filter((word) => { return /^\w/.test(word); }); let uniqueWords = new Set(validWords); return uniqueWords.size; } let text1 = "Lorem ipsum dolor sit amet consectetuer adipiscing elit aenean commodo ligula eget dolor."; let text2 = "Etiam ultricies nisi vel augue. Curabitur ullamcorper"; console.log(`Text 1 has ${computeCountUniqueWords(text1)} words`); console.log(`Text 2 has ${computeCountUniqueWords(text2)} words.`); I think it has become quite neat and short. Nevertheless: Is there a better way to solve the described task? Moveover: Is my checking with the regular expression sufficient? Or should it be enhanced? Looking forward to reading your answers. Answer: Two problems Your code has two problems. It does not remove punctuation from the words resulting in the same words not matching. Eg text1 has 12 unique words not 13. You count dolor and dolor. as different words. You are ignoring capitalization. You would count Dolor and dolor as different words rather than the same. String.match Update I was not paying attention on first posting. There is no /*RegExp.match*/ The better solution is to use the String.match to convert the matches to an array and then directly create the set from that. The code is just one line and the performance is 2.5 times faster than using String.replace as shown. thus the ideal solution becomes... const uniqueWords = txt => new Set(txt.toLowerCase().match(/\w+/g)).size; String.replace You can use a string replace to iterate over RegExp matches. It's a little hacky but I much prefer it over other methods such a using a RegExp to split the string, or RegExp.match, or RegExp.exec which have an ugly interface and are slower than String.replace. Converting the text to lowercase using String.toLowerCase solves the capitalization problem const countUniqueWords = text => { const words = new Set(); text.toLowerCase().replace(/\w+/g, word => words.add(word)); return words.size; } const a = "Lorem ipsum dolor sit amet consectetuer adipiscing elit aenean commodo ligula eget dolor."; const b = "Etiam ultricies nisi vel augue. Curabitur ullamcorper."; info1.textContent = `A has ${countUniqueWords(a)} unique words`; info2.textContent = `B has ${countUniqueWords(b)} unique words.`; <code>A: "Lorem ipsum dolor sit amet consectetuer adipiscing elit aenean commodo ligula eget dolor."</code></br> <code id="info1"></code><br> <code>B: "Etiam ultricies nisi vel augue. Curabitur ullamcorper."</code></br> <code id="info2"></code>
{ "domain": "codereview.stackexchange", "id": 32587, "tags": "javascript, regex, ecmascript-6" }
rosserial: cstring: No such file or directory (arduino ide)
Question: I have been trying to make rosserial work for days now to no avail. This is the most recent issue off a fresh arduino install with a successful catkin_make and catkin_make install. I am running ubuntu 20.04. This happens when I try to verify the code in IDE Arduino: 1.8.15 (Linux), Board: "Arduino Uno" In file included from /home/ubuntu/Desktop/arduino library/sketchbook/libraries/Rosserial_Arduino_Library/src/std_msgs/Time.h:7:0, from /home/ubuntu/Desktop/arduino library/sketchbook/libraries/Rosserial_Arduino_Library/src/ros/node_handle.h:40, from /home/ubuntu/Desktop/arduino library/sketchbook/libraries/Rosserial_Arduino_Library/src/ros.h:38, from /home/ubuntu/Desktop/arduino library/sketchbook/Hello_world/Hello_world.ino:9: /home/ubuntu/Desktop/arduino library/sketchbook/libraries/Rosserial_Arduino_Library/src/ros/msg.h:40:10: fatal error: cstring: No such file or directory #include <cstring> ^~~~~~~~~ compilation terminated. exit status 1 Error compiling for board Arduino Uno. This report would have more information with "Show verbose output during compilation" option enabled in File -> Preferences. Originally posted by matthewfwork on ROS Answers with karma: 15 on 2021-08-24 Post score: 0 Answer: Seems to be a known issue: ros-drivers/rosserial#518 and apparently ros-drivers/rosserial#525 should fix it. Originally posted by gvdhoorn with karma: 86574 on 2021-08-24 This answer was ACCEPTED on the original site Post score: 1 Original comments Comment by matthewfwork on 2021-08-24: Sweet that seemed to have worked because now I get a new error when compliling Arduino: 1.8.15 (Linux), Board: "Arduino Uno" Hello_world:2:14: error: expected constructor, destructor, or type conversion before 'Publisher' * rosserial Publisher Example ^~~~~~~~~ exit status 1 expected constructor, destructor, or type conversion before 'Publisher' Comment by gvdhoorn on 2021-08-24: That would be a different problem. Comment by matthewfwork on 2021-08-24: got it thanks for the help for original issue!
{ "domain": "robotics.stackexchange", "id": 36842, "tags": "arduino" }
prove that context free languages are closed under the $\circ$ operation
Question: Prove that if $C$ and $D$ are context-free languages, then so is $C\circ D := \cup_{n\ge 0} C^n D C^n $. I know that $\{0^n 1 0^n : n\ge 0\}$ is context free, being the intersection of $L(0^* 10^*)$ and $L(G)$, where $G$ is the context free grammar with start symbol S given by $S\mapsto S1 S | 0S | \epsilon$. Also, I know basic properties like the fact that context free languages are closed under taking prefixes, union, and concatenation. The issue with applying this technique to the given problem is that $C^* B C^*$ may not be regular. How can I circumvent this issue to solve the given question? Answer: As you state the language $\{0^n 1 0^n\mid n\ge 0\}$ is context-free. (You do not need closure properties for this: $S\to 0S0\mid 1$ will do.) Now continue as follows. Consider instead the language $\{X^n Y X^n\mid n\ge 0\}$, where $X,Y$ are the axioms of context-free grammars for $C$ and $D$.
{ "domain": "cs.stackexchange", "id": 20126, "tags": "formal-languages, automata, finite-automata" }
How certain are we that and objects spacetime speed is constant
Question: I just recently realized - through the aid of a simple yet effective video - that mass curves not space, but spacetime. This has lead me to finally understand why we use geodesics to explain the apparent acceleration of bodies toward massive objects. My current understanding is thus that the curvature of spacetime leads to a rotation of the spacetime velocity vector, "transferring" (I'm certain that this isn't kosher nomenclature) some of the temporal velocity component into a spatial velocity component. For this to make sense I gather that the spacetime speed must be constant, as is also taught in special relativity. I wonder though if this is actually something we have tested? Have we gathered any empirical evidence for the constancy of the spacetime speed of an object? Is this even feasible to test? Answer: Have we gathered any empirical evidence for the constancy of the spacetime velocity of an object? Is this even feasible to test? Yes, this is very feasible. The easiest manifestation of the constancy of the spacetime velocity is called time dilation. This has been experimentally tested from subatomic particles moving inertially to particles undergoing enormous accelerations in colliders to pieces of metal on rotors to macroscopic clocks on airplanes to clocks in satellites and even clocks just in labs. All of them have confirmed the relativistic prediction as described by the constancy of the spacetime velocity.
{ "domain": "physics.stackexchange", "id": 73426, "tags": "general-relativity, spacetime, curvature, speed" }
Many to many service communication
Question: Hi all, as far as I understood a service can be used by different clients as long as in the source code the ServiceServer and the ServiceClient are declared with the same service name (see code below, each line belongs to a different node). ros::ServiceServer service = n.advertiseService("add_two_ints", add); ros::ServiceClient client1 = n.serviceClient<beginner_tutorials::AddTwoInts>("add_two_ints"); ros::ServiceClient client2 = n.serviceClient<beginner_tutorials::AddTwoInts>("add_two_ints"); How are multiple concurrent requests managed? As far as I understood they are processed in a synchronous way according to a FIFO policy, right? I'm also wondering if it is possible to have a many-to-many connection (multiple servers) ros::ServiceServer service = n.advertiseService("add_two_ints", add); ros::ServiceServer service2 = n.advertiseService("add_two_ints", add); ros::ServiceClient client1 = n.serviceClient<beginner_tutorials::AddTwoInts>("add_two_ints"); ros::ServiceClient client2 = n.serviceClient<beginner_tutorials::AddTwoInts>("add_two_ints"); How are requests managed in this case? Finally, are these concepts valid also for actions? Originally posted by maverik on ROS Answers with karma: 3 on 2013-06-03 Post score: 0 Answer: You cannot have multiple nodes advertising the same service, and you cannot advertise the same service more than once from the same node; this doesn't make sense given that services are effectively remote function calls. I'm not certain, but I believe service requests are handled serially by design. If you want many-to-many communication, topics may be a better choice. Originally posted by ahendrix with karma: 47576 on 2013-06-03 This answer was ACCEPTED on the original site Post score: 4 Original comments Comment by maverik on 2013-06-03: Thanks! What you said makes sense from a theoretical point of view! However I tried to create two nodes that advertise the same service and when I lunched them I didn't see any error. However the services were always provided by the same node, probably the second I lunched. Comment by joq on 2013-06-04: For topics, the publisher advertises. The many-to-one typically means many subscribers. Comment by FrankAllen on 2015-07-11: "I'm not certain, but I believe service requests are handled serially by design." - this is true on the client side, but the service provider executes requests concurrently on separate threads... at least in rospy. Comment by ahendrix on 2015-07-11: roscpp handles service requests serially, unless you explicitly create a multithreaded async spinner to handle service callbacks.
{ "domain": "robotics.stackexchange", "id": 14403, "tags": "ros, service, ros-service" }
Problems with a new hydro install of hector quadrotor demo
Question: Hello all, I observe the following when trying to test out the new version of the most excellent hector_quad_rotor sudo apt-get install ros-hydro-hector-quadrotor-demo. user@happyplace:~$ roslaunch hector_quadrotor_demo outdoor_flight_gazebo.launch ... logging to /home/ubuntu/.ros/log/297f0af6-c010-11e3-8a21-fa163eaa4736/roslaunch-10-100-16-5-23452.log Checking log directory for disk usage. This may take awhile. Press Ctrl-C to interrupt Done checking log file disk usage. Usage is <1GB. Invalid <arg> tag: hector_quadrotor_description ROS path [0]=/opt/ros/hydro/share/ros ROS path [1]=/opt/ros/hydro/share ROS path [2]=/opt/ros/hydro/stacks. Arg xml is <arg name="model" value="$(find hector_quadrotor_description)/urdf/quadrotor_hokuyo_utm30lx.gazebo.xacro"/> It seems that ros-hydro-hector-quadrotor-description should be a dependency. Can anyone else confirm this experience? Originally posted by SL Remy on ROS Answers with karma: 2022 on 2014-04-09 Post score: 0 Answer: Hi I get the same error solved running sudo apt-get install ros-hydro-hector* all hector_quadrotor packages will be installed, then gazebo can find the right one ciao! thanks Originally posted by RiccardoLasagno with karma: 26 on 2014-04-10 This answer was ACCEPTED on the original site Post score: 1 Original comments Comment by SL Remy on 2014-04-10: Ok. That's good to know! I don't have a physical quadrotor personally, so I did not install the entire hector package as I thought it would be overkill. Running sudo apt-get install ros-hydro-hector-quadrotor-demo ros-hydro-hector-quadrotor-description was the path that I tried.
{ "domain": "robotics.stackexchange", "id": 17598, "tags": "ros" }
How could we travel to the nearest supermassive Black hole?
Question: I have just watched a trailer for the upcoming movie Interstellar and started to wonder about some physics involved. In the end of the trailer, they are obviously plunging into a Black hole hoping to travel into a different universe. Let us for a moment forget about the fact that most Black holes just probably are not worm-holes. But a large problem is, how do they get there since the closest Black holes such as Sagittarius A* are several thousand light-years away? The Black hole at Sgr A* is surely massive enough for tidal forces not to pose a larger problem for the starship. My first guess of transport would be a warp drive, since in the trailer there is a ring around the starship resembling the one usually included in warp drive designs (see the NASA concept below). But for a warp drive we need exotic matter and how much exotic matter would we need to get through 26 000 light-years in few tens of Earth years (using also hibernation of the pilots)? Is there possibly enough exotic matter in the Solar system for such a transport? Or is there something I am missing such as a very large Black hole nearby (i.e. large enough for tidal forces not to rip the spaceship apart)? EDIT: Luboš Motl pointed rightly out that Sgr A* isn't the closest black hole, this doesn't change the argument that the closest known black holes are still too far away. I also edited some of the wording - even primordial black holes would not be good wormholes, only exotic matter allows them to be traversable. (Thanks again to Luboš for the point.) Everybody seems to be very perplexed by the concept of exotic matter. Yes, it is a highly speculative idea which might not have any physical significance, thus eliminating the possibility of both wormholes and warp drive. But, it is not completely ruled out. We could e.g. speculate that the negative energy density is actually an underdensity of dark energy. Etc. etc. Either way, both traversable wormholes and warp drives are serious lines of (speculative) research not so different in empirical substantiality from e.g. all quantum gravity theories including the very much stressed string theory, so let us consider them at least for a while. Answer: Warp drives are not allowed by the basic laws of physics, in particular the theory of relativity prohibits any superluminal motion or superluminal propagation of usable information. So whatever "exotic matter" or other wordings are proposed to justify the superluminal warp drives is banned, too. The typical "exotic matter" needed for warp drives would need to admit a negative energy-mass density. If Nature allowed the energy density to go negative, the vacuum itself would be unstable. The laws of physics also ban the transfer of an object from a universe to a different universe through a black hole, whether it is primordial or not. Wormholes allowed by the laws of physics, if there are any, have to be non-traversable. It means that by jumping into such a black hole, he is guaranteed to end up in the singularity. At most, the singularity where he ends may be shared between a pair (or perhaps a higher number) of black holes. Such a pair of black holes is known as the non-traversable wormhole or the Einstein-Rosen bridge (at least the simplest one). But whoever falls into a black hole can never escape to the "liberated space" outside it, in any Universe, by the very definition of a black hole. Incidentally, the technical reason why a traversable wormhole can't be built is the very same why the warp drives are impossible: negative energy density would be needed for them, too. Sagittarius A* is in no way the nearest black hole to the Earth. For example, V404 Cygni has a black hole in it that https://en.wikipedia.org/wiki/V404_Cygni is 7,800 light years away, and there are probably many closer ones, too. It wasn't my plan to correct statements in the question but I have to. While an idealized empty large black hole is indeed mildly curved and one may survive the fall behind the horizon, that's not true for realistic black holes, especially Sagittarius A*. The latter is surrounded by plasma, matter that the black hole devours. A good description of the plasma around Sgr A* is the two-temperature plasma. The temperature of the electron component of the plasma is about 100 billion kelvins. No material that could be used to build a spaceship could survive these conditions. We would need a much more isolated black hole to avoid this thermal hell but it isn't clear whether such astrophysical black holes exist.
{ "domain": "physics.stackexchange", "id": 15309, "tags": "general-relativity, black-holes, popular-science, warp-drives" }
Make a map using a splay tree
Question: In my data structures and algorithms class, we were introduced to the splay tree, a BST with the additional property that recently accessed elements are quick to access (because they stay at the top of the tree until a different element is accessed). I know that std::map uses a BST; I heard it's a Red-Black Tree. Anyway, I thought I'd implement my own map using the splay tree idea, and I'd like to know what people think of my implementation. Does it look efficient? Is it readable? #ifndef SplayTree_ms_map_h #define SplayTree_ms_map_h #include <iostream> #include <assert.h> #include <exception> namespace ms { template <class KeyType, class ValueType> class map { protected: class Node { public: Node *llink = NULL; Node *rlink = NULL; Node *parent = NULL; KeyType key; ValueType value; void left_rotate() { assert(parent != NULL); assert(parent->rlink = this); Node *t2 = llink; Node *p = parent; Node *gp = p->parent; if (gp != NULL) { if (gp->llink == parent) { gp->llink = this; } else { assert(gp->rlink = parent); gp->rlink = this; } parent = gp; } else { parent = NULL; } p->rlink = t2; if (t2 != NULL) { p->rlink->parent = p; } llink = p; llink->parent = this; } void right_rotate() { assert(parent != NULL); assert(parent->llink = this); Node *t2 = rlink; Node *p = parent; Node *gp = p->parent; if (gp != NULL) { if (gp->llink == parent) { gp->llink = this; } else { assert(gp->rlink = parent); gp->rlink = this; } parent = gp; } else { parent = NULL; } p->llink = t2; if (t2 != NULL) { p->llink->parent = p; } rlink = p; rlink->parent = this; } Node *find(KeyType key) { if (this->key == key) { return this; } Node *found = NULL; if (llink != NULL) { found = llink->find(key); } if (found == NULL && rlink != NULL) { found = rlink->find(key); } return found; } void insert(KeyType key, ValueType value) { if (key < this->key) { if (this->llink == NULL) { this->llink = new Node; this->llink->key = key; this->llink->value = value; this->llink->parent = this; } else { this->llink->insert(key, value); } } else { if (this->rlink == NULL) { this->rlink = new Node; this->rlink->key = key; this->rlink->value = value; this->rlink->parent = this; } else { this->rlink->insert(key, value); } } } }; Node *root = NULL; void splay(Node *x) { assert(x != NULL); while (x->parent != NULL) { if (x->parent->llink == x) { x->right_rotate(); } else { assert(x->parent->rlink == x); x->left_rotate(); } } root = x; } class NodeProxy { private: map<KeyType, ValueType> *m; KeyType key; public: NodeProxy(map<KeyType, ValueType> *m, KeyType key) : m(m), key(key) {} NodeProxy &operator=(ValueType value) { m->set(key, value); return *this; } operator ValueType() const{ return m->get(key); } friend std::ostream& operator <<(std::ostream &os, NodeProxy nodeProxy) { os << nodeProxy.m->get(nodeProxy.key); return os; } }; public: void set(KeyType key, ValueType value) { if (root == NULL) { root = new Node; root->key = key; root->value = value; } else { Node *found = root->find(key); if (found != NULL) { found->value = value; } else { root->insert(key, value); } } } ValueType get(KeyType key) { Node *x = root->find(key); if (x == NULL) { throw std::runtime_error("Key does not exist in the map"); } splay(x); return x->value; } NodeProxy operator[](KeyType key) { return NodeProxy(this, key); } }; } #endif Usage is pretty straight-forward ms::map<std::string, int> reputation; reputation["Stack Overflow"] = 1422; reputation["Chemistry"] = 286; reputation["Code Review"] = 101; // This question gets down-voted reputation["Code Review"] = 99; std::cout << "My reputation on stackoverflow.com is " << reputation["Stack Overflow"] << std::endl; Answer: It would be better to separate the class interface declaration from the implementation. The declaration would serve as a nice overview of the class's functionality, and it's the recommended practice anyway, for information hiding. This is especially important when you also have inner classes, and member variables declared in unusual order (between methods), like root. I suggest to use K, V as the template parameter names instead of KeyType, ValueType. K, V are commonly used and understood as key-value types. When I see KeyType without the declaration, my first thought is that it's a typedef. But it's actually a template type parameter, which is different. It's confusing. llink and rlink are not so good names. By that logic you should suffix all pointers with link. I suggest to rename to left and right, that would be perfectly understandable, and more readable. I would also rename left_rotate and right_rotate to rotate_left and rotate_right. It seems more straightforward, and sound more like actions. Declare variables closer to where they are actually used. In this code: Node *t2 = llink; Node *p = parent; Node *gp = p->parent; if (gp != NULL) { if (gp->llink == parent) { gp->llink = this; } else { assert(gp->rlink = parent); gp->rlink = this; } parent = gp; } else { parent = NULL; } p->rlink = t2; if (t2 != NULL) { p->rlink->parent = p; } llink = p; llink->parent = this; The declaration and assignment of t2 is too far from where t2 is actually used, which seriously hurts readability. It would be better this way: Node *p = parent; Node *gp = p->parent; if (gp != NULL) { if (gp->llink == parent) { gp->llink = this; } else { assert(gp->rlink = parent); gp->rlink = this; } parent = gp; } else { parent = NULL; } Node *t2 = llink; p->rlink = t2; if (t2 != NULL) { p->rlink->parent = p; } llink = p; llink->parent = this; Not only it's more readable what is t2, now it's clear that it's actually pointless: you could use llink directly without t2. Btw, I took a closer look at t2 because of its poor name. I was wondering what it does, because its didn't explain anything. If you had tried to give a more meaningful name to it in the beginning, something that describes well its purpose, you probably would have realized yourself early on that it has no purpose. The variable p, being a single letter, is also confusing. At first look I thought its declaration can be moved down just like t2, I had to look closer to realize that it's important to store the original value of parent in it. If it was named origParent or oldParent, this would have been much harder to overlook.
{ "domain": "codereview.stackexchange", "id": 10507, "tags": "c++, tree" }
If sulfur is directly below oxygen on the periodic table, why isn't SO the most common sulfur oxide? Instead of third, behind SO2 and SO3?
Question: Chalcogen like oxygen and sulfur want to 'grab' (or share) two electrons to get to eight, if possible, or maybe 'give up' (or share) six, if necessary, to again get to eight... Right? So, why is sulfur dioxide, where the sulfur shares four electrons (usually), more common than sulfur monoxide or sulfur trioxide? Isn't sulfur dioxide a higher energy, less stable molecule? Answer: Nobody really knows why $\ce{SO}$ is such a rare and unstable substance. It is an orange gas at room temperature. The only way to synthesize $\ce{SO}$ is to reduce thionyl chloride $\ce{SOCl2}$ with some reagent eager to react with the chlorine atom, like sodium, silver or tin : $$\ce{SOCl2 + 2 Na -> SO + 2 NaCl}$$ The strangest property of this gas is its reaction with water. It is decomposed with the smallest amount of water vapor according to the disproportion equation : $$\ce{3SO + H2O -> H2S + 2 SO2}$$ It is an extraordinary reaction, as it requires $3$ molecules $\ce{SO}$. Another oxide is known to disproportionate with water : $\ce{NO2}$. But there is a good reason for this behavior : $\ce{NO2}$ has an uneven number of electrons. It is not the case for $\ce{SO}$.
{ "domain": "chemistry.stackexchange", "id": 16708, "tags": "stoichiometry, molecules, covalent-compounds, periodic-table" }
Creating Menubar using Angularjs 1.5
Question: I've a sample code to create a simple menubar here which works, but I'm not sure if that's the best way to code it. Can somebody please validate if there is a better way to do the same? In short I've create a sample page with a directive called <menu-bar> <menu-bar></menu-bar> The directive merely points to a template code and a controller app.directive("menuBar", function () { return { restrict: 'E', templateUrl: 'main-nav.html', controller: 'navController', controllerAs: 'nc' } }); The controller loads the menubar (which will eventually fetch the items from the DB app.controller('navController', ['$scope', '$location', function ($scope, $location) { $scope.navigationTabs = [ new NAV("file","/file","File","fa fa-file-o", "active"), new NAV("edit","/edit","Edit","fa fa-edit", "inactive"), new NAV("view","/view","View","fa fa-search", "inactive"), new NAV("hist","/history","History","fa fa-history", "inactive"), new NAV("bmark","/bookmarks","Bookmarks","fa fa-bookmark-o", "inactive"), new NAV("hlp","/help","Help","fa fa-life-buoy", "inactive") ]; ... }]); The controller defines a 'selectTab()' method which changes the url of the application when the user selects a menu-item. It also clears the active class on all the other items and sets the 'active' class on the one selected ... $scope.selectTab = function (nav) { $scope.navigationTabs.forEach(function (nav) { nav.active=""; }); console.log("navigating to url: " + nav.key); $location.path(nav.key); nav.active = "active"; } The NAV item is defined in the app.js as follows: var NAV = function (id, key, value, icon, active) { this.id = id; this.key = key; this.value = value; this.icon = icon; this.active = active; }; Answer: $scope.navigationTabs = [ new NAV("file","/file","File","fa fa-file-o", "active"), ... ] All this piece of code does is define an instance of a NAV with the specified properties. It's not sharing methods, no inheritance, making the use of a constructor overkill. This is no different from doing: $scope.navigationTabs = [ { id: "file", key: "/file", value: "File", icon: "fa fa-file-o", active: "active" } The above method throws away the need for a constructor, names your properties verbosely, and order of appearance doesn't matter. If you want defaults, a factory function that merges your object with a default one does the same thing. It may just be replacing your constructor, but you still keep the perks of using an object. function createNav(settings){ return Object.assign({ // defaults here }, settings); } Taking this further, you can just store the objects in an array, and run map through it to create the tabs. This way, you avoid always calling the function and concentrate on just the data. var navItems = [ { id: "file", key: "/file", value: "File", icon: "fa fa-file-o", active: "active" }, .... ]; $scope.navigationTabs = navItems.map(createNav); console.log("navigating to url: " + nav.key); Consider avoiding console.log when debugging. Use the browser's developer tools instead. Should you really want to log, use Angular's $log service as it safely detects the presence of console. I would recommend that the directive be like a standalone component and written like: <menu-bar menu-items="someVarWithMenuItems"></menu-bar> In this manner, you make the directive portable, letting the enclosing controller decide what the menu items are. Another idea would be to have another directive and let the consumer write it this way: <menu-bar> <menu-item ...props...>tab text</menu-item> <menu-item ...props...>tab text</menu-item> <menu-item ...props...>tab text</menu-item> </menu-bar> This way, you can just let the consumer drop in the scripts and not have to worry about them. They can just declare the tabs in the markup.
{ "domain": "codereview.stackexchange", "id": 19801, "tags": "javascript, angular.js" }
Total Differential of Chemical Potential
Question: I have seen many sources (for example this libretext) cite that the total differential of chemical potential is $$d\mu = V_m dP - S_m dT$$ where $V_m$ is the molar volume and $S_m$ is the molar entropy. The usual justification for this formula is that chemical potential is the same as partial molar Gibbs free energy, but I was hoping that someone could make this connection more clear. My understanding is that partial molar quantities are quite literally the rate of change of a certain quantity with respect to the number of moles of a substance (please correct me if this understanding is incorrect), so saying that molar Gibbs free energy and chemical potential are the same seems purely definitional and I don't see what conclusions can be drawn from that claim or how that can be used to derive this relationship. Answer: $$dG=VdP-SdT-\sum{\mu_in_i}$$So, $$\frac{\partial G}{\partial P}=V$$and $$\frac{\partial G}{\partial n_i}=\mu_i$$So, $$\frac{\partial^2 G}{\partial n_i \partial P}=\frac{\partial^2 G}{\partial P\partial n_i}=\frac{\partial V}{\partial n_i}=V_{m,i}=\frac{\partial \mu_i}{\partial P}$$
{ "domain": "chemistry.stackexchange", "id": 17730, "tags": "thermodynamics, free-energy, chemical-potential" }
Subfile program using user input validation
Question: I have written a subfile program, which is working as expected. It would be great if the experts here could review it and provide feedback if the RPG or DDS can be improved in any way. Kindly note that some of the text in the screenshots have been hidden for the sake of privacy. Requirement: Present a display file to the user when the program is called with blank input fields. Inital screen to be presented to the user Validate the input that is provided by the user and if all validations pass, display the subfile records on the screen matching the input provided as below: Matching records DDS code: A* INDICATORS USED: A* ---------------- A* 01 - SFILE01 SFLCLR A* N01 - SFILE01 SFLDSPCTL A* 02 - SFILE01 SFLDSP A* 03 - SFILE01 SFLEND A* 20 - SSPLNT (RI,PC) A* 21 - SSURSC (RI,PC) A* 22 - FROM DATE FIELDS (RI,PC) A* 23 - TO DATE FIELDS (RI,PC) A* A* 90 - ERRORSF SFLCLR A* N90 - ERRORSF SFLDSPCTL A* 91 - ERRORSF SFLDSP A* 99 - ERRORSF SFLEND A*====================================================================***** A*====================================================================***** A DSPSIZ(24 80 *DS3) A CA05(05) A PRINT(*LIBL/QSYSPRT) A*====================================================================***** A R SFILE01 SFL A SSOPT 1A B 11 3VALUES(' ' '5' '7') A SSORD# 7A O 11 5 A SSASRT 3A O 11 13 A SSSEQN 3S 0O 11 17 A SSSKU 7A O 11 21 A SSPTN1 2A O 11 29 A SSPTN2 14A O 11 32 A SSMCHN 10A O 11 47 A SSDATE 6Y 0O 11 58EDTCDE(Y) A SSTIME 4Y 0O 11 67EDTWRD(' : ') A SSQTY 5Y 0O 11 73EDTCDE(K) A SSPLVL 2 H A*====================================================================***** A R SFCTL01 SFLCTL(SFILE01) A SFLSIZ(9999) A SFLPAG(0011) A CA03 A OVERLAY A 01 SFLCLR A N01 SFLDSPCTL A 02 SFLDSP A 03 SFLEND(*MORE) A SF1RRN 4S 0H SFLRCDNBR A 1 3DATE A EDTCDE(Y) A 1 28'WestPoint Home' A DSPATR(HI) A 1 57SYSNAME A 1 69'MF040R25' A 2 3TIME A 2 21'Work Center Production Inquiry' A DSPATR(HI) A 2 69USER A 4 3'Plant:' A COLOR(BLU) A SSPLNT 10A B 4 10COLOR(WHT) A 20 DSPATR(PC) A 20 DSPATR(RI) A 4 22'Work Center:' A COLOR(BLU) A SSURSC 10A B 4 35COLOR(WHT) A 21 DSPATR(PC) A 21 DSPATR(RI) A SSWCDS 30A O 4 46 A 5 3'From Date:' A COLOR(BLU) A SSFMON 2Y 0B 5 14COLOR(WHT) A 22 DSPATR(PC) A 22 DSPATR(RI) A SSFDAY 2Y 0B 5 18COLOR(WHT) A 22 DSPATR(PC) A 22 DSPATR(RI) A 6 14'MM' A COLOR(BLU) A 6 18'DD' A COLOR(BLU) A SSTMON 2Y 0B 5 42COLOR(WHT) A 23 DSPATR(PC) A 23 DSPATR(RI) A SSFYEAR 4Y 0B 5 22COLOR(WHT) A 22 DSPATR(PC) A 22 DSPATR(RI) A 6 22'YYYY' A COLOR(BLU) A 5 33'To Date:' A COLOR(BLU) A SSTDAY 2Y 0B 5 46COLOR(WHT) A 23 DSPATR(PC) A 23 DSPATR(RI) A SSTYEAR 4Y 0B 5 50COLOR(WHT) A 23 DSPATR(PC) A 23 DSPATR(RI) A 6 42'MM' A COLOR(BLU) A 6 46'DD' A COLOR(BLU) A 6 50'YYYY' A COLOR(BLU) A 7 46'Total Produced:' A 8 3'Options: 5=MO Inquiry 7=Event Hi- A story Inquiry' A COLOR(BLU) A 9 3'O' A COLOR(WHT) A 10 3'P' A COLOR(WHT) A DSPATR(UL) A 10 5'Mfg. Order # ' A COLOR(WHT) A DSPATR(UL) A 10 21'SKU ' A COLOR(WHT) A DSPATR(UL) A 10 47'Machine ' A COLOR(WHT) A DSPATR(UL) A 10 58'Date ' A COLOR(WHT) A DSPATR(UL) A 10 67'Time ' A COLOR(WHT) A DSPATR(UL) A 10 73'Qty ' A COLOR(WHT) A DSPATR(UL) A SSTQTY 9Y 0O 7 62EDTCDE(J) A 10 29'CL' A COLOR(WHT) A DSPATR(UL) A 10 32'Pattern ' A COLOR(WHT) A DSPATR(UL) A*====================================================================***** A* ERROR SUBFILE A*====================================================================***** A R ERRORSF SFL A SFLNXTCHG A MESG 78 O 24 2DSPATR(RI) A COLOR(RED) A*====================================================================***** A* ERROR SUBFILE CONTROL A*====================================================================***** A R ERRORSFC SFLCTL(ERRORSF) A SFLSIZ(9999) A SFLPAG(0001) A 90 SFLCLR A N90 SFLDSPCTL A 91 SFLDSP A 99 SFLEND A ERRRRN 4S 0H SFLRCDNBR A 23 3'F3=Exit' A COLOR(BLU) A 23 13'F5=Refresh' A COLOR(BLU) RPG code: ¹********************************************************************** * File descriptions ¹********************************************************************** FMF040D25 CF E Workstn F SFILE(SFILE01:SF1RRN) F SFILE(ERRORSF:ERRRRN) F Infds(Info) FQSYSPRT O F 132 Printer ¹********************************************************************** * Arrays ¹********************************************************************** D Msg s 75 Dim(5) ctdata perrcd(1) ¹********************************************************************** * Data structures ¹********************************************************************** DInfo ds D Cfkey 369 369 D DS D #Ssfdate 1 8 0 inz(0) D Ssfyear 1 4 0 D Ssfmon 5 6 0 D Ssfday 7 8 0 D DS D #Sstdate 1 8 0 inz(0) D Sstyear 1 4 0 D Sstmon 5 6 0 D Sstday 7 8 0 D Dsp_Fields DS D SSORD# 7 D SSASRT 3 D SSSEQN 3 0 INZ(*Zeros) D SSSKU 7 D SSPTN1 2 D SSPTN2 14 D SSMCHN 10 D SSDATEd 8 0 INZ(*Zeros) D SSTIMEd 6 0 INZ(*Zeros) D SSQTY 5 0 INZ(*Zeros) D SSPLVL 2 ¹********************************************************************** * Stand Alone Variables ¹********************************************************************** D ValidFlag S 1 Inz(*Blanks) D ErrorFound S N Inz(*Off) D RecordFound S N Inz(*Off) D CursorDeclared S N Inz(*Off) D Sseqnc S 3 D Sdatec S 8 D SavRrn S Like(Sf1Rrn) Inz(1) D MOMode S 10 Inz('DISPLAY') ¹********************************************************************** * Constants ¹********************************************************************** D Moinquiry C Const('5') D Hisinquiry C Const('7') D ParmCorp C Const('HF') D ParmDivi C Const('30') D Refresh C Const(X'35') D SflSize C Const(9999) ¹********************************************************************** ¹********************************************************************** * Procedures ¹********************************************************************** // Procedure MOINQUIRY - M.O. MAINTENANCE Display Mode D MOINQUIRYPR PR Extpgm('MOHD01') D 10a CONST D 10a CONST D 10a CONST D 2a CONST D 7a CONST D 3a CONST D 3 CONST D 7a CONST D 1a CONST // Procedure HISTORYINQPR - Call MF040R01 Program D HISTORYINQPR PR Extpgm('MF040R01') D 10 CONST D 8p 0 CONST D 7 CONST D 3 CONST D 3 CONST D 1 CONST D 10 CONST D 15 CONST D 10 CONST D 8p 0 CONST D 10 CONST D 10 CONST D 10 CONST D 8p 0 CONST ¹********************************************************************** * Main program logic ¹********************************************************************** Write Errorsfc; Exfmt Sfctl01; Dow *Inkc = *off; Exsr Clrerrsf; //Validate input only if Refresh not hit... If (Cfkey <> Refresh); Exsr Edit_sfl01; EndIf; //If Errors found in input, Display Error Subfile... If (ErrorFound); *In91 = *on; Errrrn = 1; *In02 = *off; Else; //If no errors found, produce subfile Exsr Build_Sfile01; //If no records were found and refresh not hit, //Display message no records were found... If ( (Not RecordFound) and (CfKey <> Refresh) ); *In91 = *on; Mesg = Msg(05); Exsr write_error; EndIf; Endif; *In03 = *On; Write Errorsfc; //Display the subfile record that was last //changed by user (SavRrn), else display 1st rec... Sf1Rrn = SavRrn; Exfmt Sfctl01; //If user does not hit refresh after Subfile displyed, //Process options taken on subfile records... If ( (RecordFound) and (CfKey <> Refresh) ); Exsr Process_Sfile01; Else; //If refresh hit by user, Clear all fields and display blank //Subfile... If (CfKey = Refresh); Clear Sfctl01; Exsr Clear_Sfile01; EndIf; EndIf; Enddo; *Inlr = *On; //******************************************************************* // Edit Subile Fields -- Validate input entered //******************************************************************* Begsr Edit_sfl01; //Validate Plant entered ValidFlag = *Blanks; Exec Sql SELECT 'Y' INTO :VALIDFLAG FROM SYSIBM.SYSDUMMY1 WHERE EXISTS (SELECT 1 FROM AAPAP00 WHERE PAPLNT = :SSPLNT AND PACORP = '' AND PADIVI = ''); Exsr Check_SqlCode; If (ValidFlag = *Blanks); *In20 = *On; Mesg = Msg(01); Exsr write_error; ErrorFound = *On; EndIf; //Validate Work Center entered... ValidFlag = *Blanks; Exec Sql SELECT 'Y' INTO :VALIDFLAG FROM SYSIBM.SYSDUMMY1 WHERE EXISTS (SELECT 1 FROM PAWMP00 WHERE WMPLNT = :SSPLNT AND WMURSC = :SSURSC AND WMAIST = 'A' AND WMCORP = '' AND WMDIVI = ''); Exsr Check_SqlCode; If (ValidFlag = *Blanks); *In21 = *On; Mesg = Msg(02); Exsr write_error; ErrorFound = *On; Else; //Display Work center description... Exec Sql SELECT WMDESC INTO :SSWCDS FROM PAWMP00 WHERE WMPLNT = :SSPLNT AND WMURSC = :SSURSC AND WMAIST = 'A' AND WMCORP = '' AND WMDIVI = ''; Exsr Check_SqlCode; EndIf; //Validate From date input... Test(de) *iso #ssfdate; If %Error = '1'; *In22 = *on; Mesg = Msg(03); Exsr write_error; ErrorFound = *On; Endif; //Validate To date input... Test(de) *iso #sstdate; If %Error = '1'; *In23 = *on; Mesg = Msg(03); Exsr write_error; ErrorFound = *On; Endif; //Validate that To date > From Date input... If (#ssfdate > #sstdate); *In23 = *on; *In22 = *on; Mesg = Msg(04); Exsr write_error; ErrorFound = *On; EndIf; Endsr; //******************************************************************* // Write Error Subfile //******************************************************************* Begsr write_error; *In99 = *On; Monitor; Errrrn += 1; On-Error; Errrrn = *Hival; EndMon; write errorsf; endsr; //******************************************************************* // clear Error Subfile/Error Indicators //******************************************************************* Begsr clrerrsf; //Clear field error indicators... *In20 = *Off; *In21 = *Off; *In22 = *Off; *In23 = *Off; //Initialise Indicators... ErrorFound = *Off; RecordFound = *Off; //Clear Subfile... Errrrn = *zeros; Mesg = *blanks; *In99 = *off; *In91 = *off; *in90 = *on; write errorsfc; *in90 = *off; Endsr; //******************************************************************* // Clear Subfile //******************************************************************* Begsr Clear_Sfile01; Sf1Rrn = *Zero; *In01 = *On; Write Sfctl01; *In01 = *Off; Clear Ssopt; Clear Sstqty; EndSr; //******************************************************************* // Build Subfile //******************************************************************* Begsr Build_Sfile01; Exsr Clear_Sfile01; //Declare Cursor for loading subfile records... Exec Sql Declare CTOE_Fetch_Cursor cursor for SELECT OEWORD, OEWAST, OEWSEQ, OESKU,COALESCE(FCCLTH,''),COALESCE(PTPTNM,''), OEMACH, OECRDT, OECRTM, CASE WHEN OECODE IN ('FP5000','FS5000') THEN OEQTY WHEN OECODE IN ('FP5010','FS5010') THEN OEFQTY * -1 END AS QTY, OELEVL FROM CTOEP00 TBL1 LEFT OUTER JOIN PAFCP00 TBL2 ON TBL1.OESKU = TBL2.FCSKU LEFT OUTER JOIN RMPTP00 TBL3 ON TBL3.PTPTRN = TBL2.FCPATT WHERE OECRDT >= :#SSFDATE AND OECRDT <= :#SSTDATE AND OEPLNT = :SSPLNT AND OEWCTR = :SSURSC AND OECODE IN ('FP5000', 'FP5010', 'FS5000', 'FS5010'); Exec Sql Close CTOE_Fetch_Cursor; Exec Sql Open CTOE_Fetch_Cursor; Exsr Check_SqlCode; Exec Sql FETCH NEXT FROM CTOE_Fetch_Cursor INTO :DSP_FIELDS; Exsr Check_SqlCode; Dow (SQLCod = *Zeros and Sf1Rrn < SflSize); Monitor; Sf1rrn += 1; On-Error; Sf1rrn = *Hival; EndMon; //Get only hours and minutes of OECRTM Monitor; Sstime = sstimed/100; On-Error; Sstime = *Loval; EndMon; //Format OECRDT to mmddyy format... Monitor; Sdatec = %Char(Ssdated); Sdatec = %Subst(Sdatec:5:2) + %Subst(Sdatec:7:2) + %Subst(Sdatec:3:2); SSdate = %Dec(Sdatec:6:0); On-Error; SSdate = *Loval; EndMon; //Calculate total quantity produced... Monitor; Sstqty += Ssqty; On-Error; Sstqty = *Loval; EndMon; Write Sfile01; Exec Sql FETCH NEXT FROM CTOE_Fetch_Cursor INTO :DSP_FIELDS; Exsr Check_SqlCode; EndDo; If (Sf1rrn = *Zeros); *In02 = *Off; Else; Sf1Rrn = 1; *In02 = *On; RecordFound = *On; EndIf; EndSr; //******************************************************************* // Process Subfile //******************************************************************* BegSr Process_Sfile01; ReadC Sfile01; Dow Not %Eof; Monitor; Sseqnc = %Char(Ssseqn); On-Error; Sseqnc = *Loval; EndMon; Select; //If option 5 taken, call MO Inquiry program... When SSOPT = Moinquiry; MoInquiryPR(ParmCorp:ParmDivi:SSPLNT:SSPLVL:SSORD#: SSASRT:SSEQNC:MOMODE:'1'); //If option 7 taken, call History Inquiry program... When SSOPT = Hisinquiry; HistoryInqPR('':0:SSORD#:SSASRT:SSEQNC:'':'':'':'': 0:'':'':Ssplnt:0); EndSl; ReadC Sfile01; EndDo; SavRrn = Sf1Rrn; EndSr; //******************************************************************* // Check for SQL Errors //******************************************************************* BegSr Check_SqlCode; If SqlCod <> *Zero; If SqlCod <> 100; Except $ERR; Dump(a); *Inlr = *On; // Halt indicator return; EndIf; EndIf; EndSr; //******************************************************************* OQSYSPRT E $ERR 2 1 O + 1 '************************' O + 0 '************************' OQSYSPRT E $ERR 1 O + 1 'SQLAID=' O SQLAID + 1 O E $ERR 1 O + 1 'SQLABC=' O SQLABC + 1 O E $ERR 1 O + 1 'SQLCOD=' O SQLCOD L + 1 O E $ERR 1 O + 1 'SQLERL=' O SQLERL L + 1 O E $ERR 1 O + 1 'SQLERM=' O SQLERM + 1 O E $ERR 1 O + 1 'SQLERP=' O SQLERP + 1 O E $ERR 1 O + 1 'SQLER1=' O SQLER1 L + 1 O E $ERR 1 O + 1 'SQLER2=' O SQLER2 L + 1 O E $ERR 1 O + 1 'SQLER3=' O SQLER3 L + 1 O E $ERR 1 O + 1 'SQLER4=' O SQLER4 L + 1 O E $ERR 1 O + 1 'SQLER5=' O SQLER5 L + 1 ¹********************************************************************** * Error Message Array ¹********************************************************************** ** ==== Error Messages ==== Invalid Plant 01 01 Cannot Determine Work Center 02 01 Date Entered is Invalid 03 01 From Date must be less than or equal to To Date 04 01 No matching records found for Input Provided 05 01 Please note that my organization has not yet adopted RDi or fully free RPG. This code has been written in SEU. Answer: I would say that if you are looking for a code review of code written right now, you should be using modern practices. I can excuse the lack of **free as it appeared with v7.3 (PTF'd back to v7.1). But you still should be using free form H, F, and D specs. Also ditch the O specs for print files as those do not have a free form equivalent. Also realize that by sticking with SEU, you are not able to use any advances in RPG or SQL put forth since v6.1 (about 10 years) without turning off syntax checking. So that is a big issue as well. On to style, I have just a few points here: Use sub-procedures instead of sub-routines. There are several advantages to this: You can start creating a library of reusable code so you don't have to keep coding the same business logic in every program. It allows you to use local variables, and even define files locally. They are far more flexible as they can reside in service programs or programs, and can be used for recursion if you need that. You can return a value so the sub-procedure can be called inline in an expression. Use named indicators rather than numeric indicators. Even with display files. The INDDS() keyword should be used to name your indicators. Otherwise you are going to have to keep going back to the display file to determine what all those numeric indicators mean. It is a lot more readable if you can write something like sflDspCtl = TRUE; rather than *IN01 = *On;. Use Qualified file references. That is activated by the QUALIFIED keyword on the file spec. This way you can keep your file activity seperate by using a qualifier rather than by forcing yourself to rename fields or set prefixes. This allows you to read and write into data structures and assign values by name (using EVAL-CORR). Break SQL out into it's own procedure, it just clutters the logic of the routine that contains it. Because local variables and parameters are scoped to the sub-procedure, the DECLARE CURSOR does need to be in the same sub-procedure as it's associated OPEN, but keep everything else separate. Don't mix and match command key processing. In your DDS you specify CA05(05) but CA03. You are also assigning indicators 01 - 03 to subfile control keywords. So F3 must be detected by the AID byte in the file information data structure or the old K indicaotrs, but F5 can be detected either by the AID byte or *IN05, and *IN01 - *IN03 don't refer to Function keys. This will be initially confusing to anyone coming behind you. Either use the AID byte exclusively, or reserve indicators 01 - 24 for function keys F1 - F24. Once you start using Qualified on your display files, the K indicators will not be usable. Not a big deal, the letters aren't contiguous anyway (there are gaps in the sequence, do you know off the top of your head where they are)? Finally, your life will be made a bit easier by using a message subfile rather than a standard subfile for error messages.
{ "domain": "codereview.stackexchange", "id": 28028, "tags": "db2, ibm-rpg" }
Are humans a plague?
Question: We have: Reached a population of 8 billion Doubled greenhouse gases Extincted numerous species Filled the ocean floor with waste Contaminated the soil with petroleum derivatives Contaminated aquifers Could we be considered a plague? Do we have solution? Answer: In some (Or most ways) Yes. Pollution, Poaching, littering and etc Has hurt Biodiversity, lots of Animals who went extinct because of Humans wouldnt be familiar to an Average person, this link provides some insight into the animals that went extinct. Humans are the most adaptable Animals in the world, this degree of Adaptability causing tremendous Population growth, Urbanization and etc. However there is a way to solve this. Denial and Politics has kept us doing this in the recent past, but yes, there is a way to fix this.
{ "domain": "earthscience.stackexchange", "id": 2281, "tags": "ecology" }
Do objects besides strings, ropes, and rods have tension?
Question: Why do we define tension only in strings and ropes and rods and such? Shouldn't every object experience tension force? Like when you pull a paper from opposite sides, it gets taut, and experiences what seems like a state of tension. If every object does experience tension, can you define tension? Answer: Tension is not defined only for strings. However, the unique thing about ideal strings is that they can ONLY experience tension, whereas rigid bodies can experience tensions and compression. Ideal strings would collapse. Hope this helps
{ "domain": "physics.stackexchange", "id": 59908, "tags": "newtonian-mechanics, forces" }
The Difference between Thomas-Fermi Screening and Lindhard Screening
Question: Assuming the general theory of screening related to electron-electron interactions, I was wondering if anyone could provide a clear, yet conceptually complete explanation of the differences between the Thomas-Fermi and the Lindhard theories? Following the treatment by Ashcroft and Mermin (1976),I get the impression that the main difference is that the Thomas-Fermi model assumes that the electrostatic potential is slowly-varying in $\vec{r}$: $$E_i(\vec{k}) = \frac{\hbar^2k^2}{2m}-e\phi(\vec{r})$$, but I'm having trouble grasping the full physical significance of this statement. Answer: First, the Thomas-Fermi screening is a semiclassical static theory which assumes that the total potential $\phi(\mathbf{r})$ varies slowly in the scale of the Fermi length $l_{\text{F}}$, the chemical potential $\mu$ is constant and that $T$ is low. In principle, it does not rely on linear response theory. The condition of slowly varying potential is a general condition of validity of semiclassical models. Physically, if the particle [electron] is represented by a wave packet, what is tellying us is that all the waves in the wavepacket will see the same potential and the particle will suffer [or enjoy!] a force as if it was point-like ["classical"] because such potentials gives rise to ordinary forces in the equation of motion describing the evolution of the position and wavevector of the packet. The wavepacket must have a well-defined wavevector on scale of the Brillouin zone [thus $\Delta k \simeq k_{\text{F}}$] and therefore can be spread in the real space over many primitive cells. Mathematically, the assumption that your potential is a slowly varying function of the position implies that the theory is not valid for $|\mathbf{q}| \gg k_{\text{F}}$ [and therefore for $|\mathbf{r}| \ll l_{\text{F}}$]. On the other hand, the static Lindhard dielectric function is a fully quantum treatment of the problem and it is valid for all the ranges of $\mathbf{q}$. It includes, in the limit $\mathbf{q} \rightarrow 0$, the linearized Thomas-Fermi dielectric function. It only assumes linear response, that is, the induced density of charge is proportional to the total potential $\phi(\mathbf{r})$. Note also that the Lindhard treatment is far more general than the Thomas-Fermi in the sense that it can describe both dynamic and static screening.
{ "domain": "physics.stackexchange", "id": 2896, "tags": "condensed-matter, solid-state-physics" }
Whose concentration is more 1 molar or 1 molal?
Question: I was reading about concentration terms like molarity, molality, etc. and then I came across a question: which concentration is more: 1M(molar) of solute x dissolved in water vs. 1m(molal) of solute x dissolved in water When I Google it, I did not find exact answers but did find some related information. My approach is: Convert 1M into molality and then compare if it is less or more than 1m. (?) The density of water is 1kg per L. When solute is added to it, density would definitely increase(?) And therefore 1L of that solution will weigh more than 1 kg. now if we calculate molality of 1M solution it would be less than 1m . (?) am I correct ?? Density would always(?) Increase after adding solute **Hence 1m will always be more than 1M ** Answer: To convert from molal to molar, one generally needs to know the density of solution as well as the formula weight of solute. Suppose there is a single solute $x$ in water, and that $x$ has a formula weight of $f_x$ g/mol. Suppose also that the solution of $x$ has a density of of $\rho$. Let the molarity of $x$ in the solution be $C_x$ mol/L. Then: the mass concentration of $x$ in g/L is $C_x f_x$. the weight fraction of $x$ in grams of $x$ per total gram of solution is thus $w_x = \frac{C_x f_x}{\rho}$. The weight fraction $w_x$ must be a number between 0 and 1. The weight ratio of $x$ in grams of $x$ per gram of water is $\frac{\frac{C_x f_x}{\rho}}{1-\frac{C_x f_x}{\rho}} = \frac{w_x}{1-w_x}$. The molality is simply the weight ratio divided by the formula weight, $\frac{1000}{f_x}\frac{\frac{C_x f_x}{\rho}}{1-\frac{C_x f_x}{\rho}}$. The factor of 1000 is because molality is moles per kg of solvent, not moles per g. That last expression can be written as $\frac{1000}{f_x}\frac{\frac{C_x f_x}{\rho}}{1-\frac{C_x f_x}{\rho}} = \frac{1000}{f_x} \frac{w_x}{1-w_x}$ This last formula shows that molality values will always be higher than molarity values. Because $w_x$ has to be between zero and 1, then the molality formula will divide by a smaller number than then molarity formula. One molar water "dissolved" in water (say we are dissolving distilled water in tap water, or dissolving isotopically labeled water into regular water) has a molality of around 1.02. My approach is: Convert 1M into molality and then compare if it is less or more than 1m. (?) Good approach. The density of water is 1kg per L. True, but as noted in the comments, the density of solutions in water can be either higher or lower than the density of pure water. When solute is added to it, density would definitely increase(?) Not necessarily true. And therefore 1L of that solution will weigh more than 1 kg. Not true, and this is the point where I think your logic mislead you. To make one liter of a 1 molar solution, less than one liter of pure water is usually required. This is because part of the liter of solution is taken up by solute. So not all of the liter needs to come from pure water. And since water has a density of 1 kg/L, if we need less than one liter of pure water, we need less than 1 kg of pure water. This then means that our one mole of solute is being dissolved by less than kg of solvent: thus the molality of a one-molar solution is greater than one. The neat thing is that this is true regardless of the density or formula weight of the species being considered.
{ "domain": "chemistry.stackexchange", "id": 7572, "tags": "physical-chemistry, concentration" }
What do hector_slam with /odom?
Question: Hi, I have a question about hector_slam. This link link text say "Use in place of gmapping". In this case, I edit my launch file how say the text: "param name="odom_frame" value="odom" . My question is, What do hector_slam with this topic (/odom)? In case that hector do something. Someone have a example tf.? Thanks. Originally posted by alex.filgueira on ROS Answers with karma: 62 on 2014-02-10 Post score: 0 Answer: The odom frame is used for providing compatibility with REP-105 (and thus, gmapping). Currently, odometry information is otherwise ignored internally by hector_mapping, as in the original application it´s use actually lead to degradation of performance (due to severe slippage of robot platforms). Originally posted by Stefan Kohlbrecher with karma: 24361 on 2014-02-10 This answer was ACCEPTED on the original site Post score: 3 Original comments Comment by alex.filgueira on 2014-02-10: OK, thanks.
{ "domain": "robotics.stackexchange", "id": 16932, "tags": "slam, navigation, odometry, gmapping, hector-slam" }
Solvation effect on cyclohexane
Question: I ran molecular dynamics simulation with a molecule of methylcyclohexane soaked into a water box. On the other hand I ran Monte Carlo with the molecule alone (no soaking). I performed this for the equatorial and axial conformers. The axial conformer with MD stayed axial (the methyl group). The equatorial with MD stayed equatorial. So far no visual change. Is there a way to compute the average energy in VMD for these systems (I have around 250 frames). On the other hand, the axial conformer alone with MC was transformed into equatorial. While the equatorial stayed the same (visually speaking). I am trying to understand what's happening here. What I read is that always the equatorial configuration is more stable as it has less steric hindrance (BTW I am computer scientist learning this), so this explains the interconversion in Monte Carlo simulation from axial to equatorial. On the other hand, I would expect also that in MD the axial conformer turn into equatorial but it didn't, what I believe here is that the water molecules are having some "Solvation effect" on the methylcyclohexane that prevents the interconversion. So I would like to know if my thought are good and if you could give some references to get more info about solvation effects. Answer: The difference in behavior between the two methods is likely how much "wiggle" the molecule is allowed to have, or how much additional kinetic energy you allow the molecule to have when searching for the minimum energy conformation. The equatorial conformation is the global minimum conformation, but the axial conformation is a local minimum. Additionally, between the two conformations, there is another minimum called the twist-boat. You can read about them on this Wikipedia article or you could check out an introductory organic chemistry book from a library. Molecular dynamics tend to stop when a minimum is found. In other words, if a small alteration to the geometry increases the potential energy, the calculation stops. Monte Carlo calculations on molecules are designed to examine the evolution of conformation with time, and so geometry moves out of energy minima are allowed. Unsubstituted cyclohexane has four different conformations: Chair (relative energy 0 kJ/mol), half chair (+45 kJ/mol), twist boat (+23 kJ/mol), and boat (+30 kJ/mol). A molecular dynamics calculation may not allow large enough steps to get over the activation barrier to get out of a chair conformation. The following energy diagram shows the conformational space of cyclohexane. The energy difference between equatorial and axial methylcyclohexane is 7.6 kJ/mol (1.6 kcal/mol on this table), which is small compared to the difference between the chair and the half-chair conformation. The energy diagram below approximates the energy steps between equatorial and axial methylcyclohexane. Any computational method that allows potential energy steps large enough to get to the half-chair will certainly isomerize the axial conformer to the equatorial conformer. Presence or absence of solvent molecules in the simulation may be irrelevant.
{ "domain": "chemistry.stackexchange", "id": 464, "tags": "solvents, conformers, cyclohexane" }
How will these hydrogen atoms interact?
Question: Assume that we have a space with just two $\ce{H}$ atoms and their distance to each other is $d$. Let's say they don't have initial velocity. What is the force with which they will act on each other? This question might have some mistakes in itself, but the main thing I'm trying to learn is how an atom of element $X$ interact with an atom of element $Y$. Answer: If you just have two H atoms, nothing else then the only forces acting are gravity and interatomic forces, in particular, the van-der-waals force (note slide 5 which says the van der waals potential is applicable to monatomic gases) . The van der walls force varies and the inverse sixth power, so it will be zero until the hydrogen atoms are quite close, so weak ol' gravity will be doing most of the work until then. So, you should set up your potential around the center of mass of the system with U including the gravitational and van-der-waals potentials. For all but the closest distances, be prepared for very slow dynamics. If you don't know how to use potentials, then take the negative of the derivative of the potential for the van der waals and then add in the force of gravity, both acting in the same direction.
{ "domain": "chemistry.stackexchange", "id": 729, "tags": "atoms" }
rosdoc_lite issues
Question: As rosdoc is deprecated, we've recently switched from rosdoc to rosdoc_lite for our private, internal documentation of not-ready-for-primetime packages. But the web docs created by rosdoc_lite seem to ignore the (private) URLs in our manifest.xml files and just default to ros.org/wiki/ for all packages. So, we are debating going back to dependable rosdoc, unless of course there are some undocumented tricks for rosdoc_lite that will help us out. Originally posted by pbeeson on ROS Answers with karma: 276 on 2013-02-08 Post score: 5 Answer: I agree that rosdoc-lite should honor the URL specified, and not default to ros.org/wiki, even if that is the usual case. I recommend opening a rsodoc_lite issue to get it fixed. Originally posted by joq with karma: 25443 on 2013-02-09 This answer was ACCEPTED on the original site Post score: 1
{ "domain": "robotics.stackexchange", "id": 12816, "tags": "ros, rosdoc, documentation" }
Dual tensor in electrodynamics
Question: Is $F^{\mu\nu}$ not the dual tensor to $F_{\mu \nu}$? I always thought that this was the case, but now I came across the dual tensor defined as $\tilde{F}^{\mu \nu}=\epsilon^{\mu \nu \rho \sigma}F_{\rho \sigma}$. Can somebody explain to me the difference? Answer: Is not $F^{\mu\nu}$ the dual tensor to $F_{\mu\nu}$? What you are calling dual above is essentially the musical isomorphism that identifies vectors and covectors when one has a metric tensor. In more common language in Physics it is the process of "raising and lowering indices". Two tensors related in this way are sometimes called physically equivalent, see e.g. "General Relativity for Mathematicians" by Sachs & Wu for the usage of this terminology. In your context, however, by "dual" one means more precisely the Hodge dual of a differential form. Let me be more precise. A differential form is a totally skew-symmetric covariant tensor. If it has $k$-indices we call it a $k$-form. In a local coordinate system $x^\mu$ it has therefore components $\omega_{\mu_1\dots \mu_k}$ such that $$\omega_{[\mu_1\cdots \mu_k]}=\omega_{\mu_1\cdots \mu_k}\tag{1}$$ In this context, if one is working on a $d$-dimensional manifold (for physical spacetime $d=4$) one may define the Hodge dual of the $k$-form $\omega$ to be the $(d-k)$-form $\star \omega$ which has components $$(\star\omega)_{\mu_1\cdots \mu_{d-k}}=\dfrac{1}{k!}\epsilon^{\nu_1\cdots \nu_k}_{\phantom{\nu_1\cdots \nu_k}\mu_1\cdots \mu_{d-k}}\omega_{\nu_1\cdots \nu_k}.\tag{2}$$ The $\epsilon_{\mu_1\cdots \mu_d}$ are the components of a $d$-form which is called the volume element and which, in general, reads $$\epsilon_{\mu_1\cdots \mu_d} = \sqrt{-g}\varepsilon_{\mu_1\dots \mu_d},\tag{3}$$ where $\sqrt{-g}$ is the square root of the negative of the determinant of the metric tensor and where $\varepsilon_{\mu_1\dots \mu_d}$ is the Levi-Civita symbol with $d$ indices. In Minkowski spacetime with cartesian coordinates with the flat metric $\eta_{\mu\nu}$ this factor is equal to one and therefore the components of the volume element coincide with the components of the Levi-Civita symbol. Finally, concerning the electromagnetic field, $\tilde{F}^{\mu\nu}$ is nothing more than the Hodge dual of $F_{\mu\nu}$ with the indices raised: $$\tilde{F}^{\mu\nu}=g^{\alpha \mu}g^{\beta \nu}(\star F)_{\alpha\beta}\tag{4}.$$ Notice that since one is working in $d = 4$ dimensions and since $F_{\mu\nu}$ is a $2$-form then its dual $\star F$ is a $2$-form as well.
{ "domain": "physics.stackexchange", "id": 63998, "tags": "electromagnetism, metric-tensor, tensor-calculus" }
Can we use a magnetic vector potential in the case of time varying $E$-fields?
Question: Most discussions of the magnetic vector potential defined through $\mathbf{B}=\nabla\times\mathbf{A}$ are only for working with static electric fields (for example, Griffiths: If we instead require that $$\nabla\times\mathbf{B}=\nabla\times(\nabla\times\mathbf{A}) = \nabla(\nabla\cdot\mathbf{A})\ -\nabla^2\mathbf{A} = \mu_0\mathbf{J} +\mu_0\epsilon_0\frac{\partial\mathbf{E}}{\partial t}$$ using the full form of Ampere's law, then we can still have the freedom to choose an $\mathbf{A}$ with zero divergence, giving us a form of Poisson's equation: $$\nabla^2\mathbf{A} = -\mu_0\mathbf{J} -\mu_0\epsilon_0\frac{\partial\mathbf{E}}{\partial t}$$ Which can be solved in principle using analogies to the electric scalar potential $V$. Why is this form of the magnetic vector potential in its full generality seldom seen? Is there a contradiction which prevents its use? Answer: Yes it can be used, Given,$ \nabla × A = B$ Then $\nabla ×E = -\frac{\partial B}{\partial t}$ $\nabla × E = -\frac{\partial (\nabla × A) }{\partial t}$ $\nabla × E = -\nabla × \frac{\partial A }{\partial t}$ $\nabla × E + \nabla × \frac{\partial A }{\partial t} = 0$ $\nabla × (E + \frac{\partial A }{\partial t})= 0$ Because the curl of this quantity is zero, it can be written as the gradient of a scalar function ( or the negative of a gradient of a scalar function, which is used to match the definition of electrostatic potential) $E + \frac{\partial A }{\partial t} = -\nabla V$ $E = -\nabla V -\frac{\partial A }{\partial t} $ From here we can substitute the definitions of E into the other maxwell equations This will obtain 2 equations that interlink A and V in terms of the source terms $\rho$ and J. using the "lorenz" gauge choice ( not lorentz) we can decouple these and solve easier( or using the coulomb gauge) This is called the potential formulation of maxwells equations
{ "domain": "physics.stackexchange", "id": 85477, "tags": "electromagnetism, potential, gauge-theory, maxwell-equations, gauge-invariance" }
Chemical structure of xenon heptafluoride anion
Question: When $\ce{XeF6}$ acts as a fluoride acceptor, $\ce{XeF7-}$ is formed. What is the hybridisation, geometry, and shape of $\ce{XeF7-}$? Answer: About the geometry and shape: Source: Housecroft, Sharpe, Inorganic Chemistry, Pearson Education Limited, 2005
{ "domain": "chemistry.stackexchange", "id": 9139, "tags": "inorganic-chemistry, bond, hybridization, lewis-structure" }
How long to regrow hair?
Question: This is one of the questions I wasn't exactly sure where to post. Basically, I want to make an X-Men parody, and for the part of Professor X I need to shave off my hair. Now I have a simple french crop, not really long or anything, but I was wondering if there's an estimate for how long it would take me to regrow my hair. Again, sorry if this is the wrong site, but I just thought "human body", so I guess it fits. Answer: According to https://en.wikipedia.org/wiki/Human_hair_growth: Scalp hair is known to grow between 0.6cm and 3.36cm per month. The growth rate of scalp hair somewhat depends on age (hair tends to grow more slowly with age), sex, and ethnicity. It was previously thought that Caucasian hair grew more quickly than Asian hair and that the growth rate of women's hair was faster than that of men. However, more recent research has shown that the growth rate of hair in men and women does not significantly differ and that the hair of Chinese people grew more quickly than the hair of French Caucasians and West and Central Africans. Depending on your age, follicle-condition, nutrition or possible inhibiting factors it can vary how long it will take until your hair has grown back to the previous length.
{ "domain": "biology.stackexchange", "id": 11297, "tags": "growth, hair" }
What is the relation between P-immune languages and NP-complete languages?
Question: Can a NP-complete language be P-immune? Why can't existence of P-immune languages separate NP from P? Answer: Assuming that pseudorandom generators and secure one‐way permutations exist, it follows that $\mathsf{NP}$‐complete sets are not $\mathsf P$‐immune. Christian Glaßer, A. Pavan, Alan L. Selman, and Samik Sengupta, Properties of NP‐Complete Sets SIAM J. Comput., 36(2), 516–542, 2006.
{ "domain": "cstheory.stackexchange", "id": 4185, "tags": "complexity-classes, fl.formal-languages, computability" }
What interesting physics problems can't be solved because mathematics is not developed enough?
Question: I'm curious as to what sorts of physical problems to which we don't have an answer, because we haven't developed the right mathematics yet (or advanced-enough mathematics). Related to this question on the Math StackExchange: In what ways has physics spurred the invention of new mathematical tools? Answer: Arthur Suvorov gives a nice comment, I am just going to give a list of a few specific physical problems I can think of from the top of my head. Yang Mills existence and mass gap (Millenium Prize) and generally the problematic of rigorous definitions and constructions of quantum field theories Navier Stokes equations and smoothness (also Millenium) - it's not only Navier Stokes, but the whole topic of turbulence that bugs even MHD people etc. Exact solutions to Einstein equations - we have exact solutions for supersimple situations, but as soon as we would like to generate physically plausible solutions for situations only slightly more complicated, as an axially symmetric stationary space-time (see Ernst equation), the math just does not provide the tools. This applies generally to soliton generation techniques in various fields. The question of ergodicity of general systems - the "arrow of time" is considered in the most general case a consequence of the ergodic hypothesis. But it has been proven only for a very restricted class of systems. The whole "arrow of time" discussion might get a kick out of a more general truths about ergodicity or even a really rigorous treatment of the fact of complexity rising against the pull of entropy growth. Finding non-perturbative solutions to QFT problems (see a popular account of a recent neat development) Equation of state of the centre of a neutron star - this is connected with the previous question, because the conditions in the center of a neutron star are such that a non-perturbative treatment of e.g. a quark-gluon plasma would be needed. The ignorance of such equations of state is a major obstruction in understanding phenomena such as black hole formation. Good definedness of the Feynmann path integral formulation - you can see a review here. I am not sure what physics can be lurking there, but I believe that a rigorous definition might provide a hallway to new knowledge. Much more - basically all of the speculative beyond-standard theories are a mix of taking physically plausible steps with solving mathematical issues which spring up at every of the steps. There will surely be a long list which I don't feel qualified to even start.
{ "domain": "physics.stackexchange", "id": 15610, "tags": "mathematical-physics, mathematics, big-list" }
Error importing android library into android project using rosjava.jar
Question: Hi, There is a problem with importing "import org.ros.rosjava.android.MessageCallable;" "import org.ros.rosjava.android.views.RosTextView;" which are part of the android library into the MainActivity.java inside the android project. The project uses rosjava.jar which contains necessary java files to build; However, there is a difficulty with incorporating the android library into the project? I am not that knowledgeable with using the android library together with rosjava. Can you advise on how to get this done? Thank you! Soe Originally posted by soetommy on ROS Answers with karma: 47 on 2011-06-24 Post score: 0 Answer: First, build the rosjava.jar by running ant dist in the rosjava directory. Currently, the directions to accomplish this are in flux, but it's something like this for the moment: roscd rosjava rosmake ant dist Then, you should be able to reference the Android library project by following the directions here: http://developer.android.com/guide/developing/projects/projects-eclipse.html#ReferencingLibraryProject Originally posted by damonkohler with karma: 3838 on 2011-06-27 This answer was ACCEPTED on the original site Post score: 1
{ "domain": "robotics.stackexchange", "id": 5956, "tags": "ros, library, android" }
HTML5 Canvas game starts to lag 10 seconds after loading page
Question: I got bored and started making a game using HTML5, CSS3, and JavaScript/jQuery. I've been working on it for about 2 weeks and it was running pretty well. Today I opened it and was moving the player's ship around the screen and noticed that it became very slow as the game went on, starting at 10 seconds after the page loaded. This happens whether the ship has been moving around the entire time or sat still and was then moved after the 10 seconds. I have never made a game before and did this more as a learning exercise than anything else. HTML: <!DOCTYPE html> <html lang='en'> <head> <title>Flying Ship</title> <link type='text/css' rel='stylesheet' href='stylesheet.css'/> <script type='text/javascript' src='jquery-1.11.3.js'></script> <script type='text/javascript' src='jquery-color.js'></script> <script type='text/javascript' src='jquery-shadow.js'></script> <script type='text/javascript' src='flying_ship_scripts.js'></script> </head> <body> <canvas id='solar_system_canvas'>Your browser does not appear to support HTML5!</canvas> <canvas id='game_abilities_bar_canvas'></canvas> <div id='abilities_boost_text'>Speed Boost:</div> <div id='canvas_shadow_container_left' class='canvas_shadow_container'></div> <div id='canvas_shadow_container_top' class='canvas_shadow_container'></div> <div id='canvas_shadow_container_right' class='canvas_shadow_container'></div> <div id='canvas_shadow_container_bottom' class='canvas_shadow_container'></div> </body> </html> JavaScript/jQuery: $(document).ready(function() { /* ----------------------------------------------------------------------------------------------------- */ /* Variables and Set-up */ /* ----------------------------------------------------------------------------------------------------- */ // Get the width and height of the browser view port. var windowW = $(window).width(); var windowH = $(window).height(); // Number of images that will need to be loaded. var imagesToLoad = 1; // Initial number of images that we have loaded. // The ReportAllImagesLoaded() function will increment imageLoaded each time // an image is loaded until it equals imageToLoad. var imagesLoaded = 0; // Indicators of whether that specified border is being "touched" by // the player's ship. var borderLeft = false; var borderTop = false; var borderRight = false; var borderBottom = false; // The percentage of the player's speed boost. var boost_bar_percent = 100; // The player's ship. PNG image. The image is 150x300 pixels. // The ship is 110px wide and 200px tall. (20px to 130px, 50px to 250px). var player_ship_image; // Ships object variables. var player_ship; // The state of each key in dictionary form. // 37: Left arrow. // 38: Up arrow. // 39: Right arrow. // 40: Down arrow. var keyStates = { 37: false, // Left arrow. 38: false, // Up arrow. 39: false, // Right arrow. 40: false, // Down arrow. 65: false, // 'a' key ('left-arrow'). 87: false, // 'w' key ('up-arrow'). 68: false, // 'd' key ('right-arrow'). 83: false, // 's' key ('down-arrow'). 16: false // Shift key. }; /* ----------------------------------------------------------------------------------------------------- */ /* ----------------------------------------------------------------------------------------------------- */ /* Program Code */ /* ----------------------------------------------------------------------------------------------------- */ // Get the context of the HTML5 canvas and set it to 2D. var canvas = $('#solar_system_canvas'); var ctx = canvas[0].getContext('2d'); // Get the context of the canvas used for the abilities bar. // A second canvas is used on the assumption that it will yield a performance increase (however small). var abilities_canvas = $('#game_abilities_bar_canvas'); var abilities_ctx = abilities_canvas[0].getContext('2d'); // Initialize the canvas size the first time. SetupCanvas(); // Load all of the images, initialize the ship objects, and start the game. // LoadImages() calls ReportAllImagesLoaded(), which calls InitializeShips(), which // calls the main GameLoop(). LoadImages(); /* ----------------------------------------------------------------------------------------------------- */ /* ----------------------------------------------------------------------------------------------------- */ /* Window Events */ /* ----------------------------------------------------------------------------------------------------- */ // When the browser window is resized... $(window).on("resize", function() { // Get the new size and height of the window. windowW = $(window).width(); windowH = $(window).height(); // Resize the canvas by calling SetupCanvas(). SetupCanvas(); // Redraw all the ships. DrawAllShips(); }); // Listen for key-down and key-up events. Set the corresponding key to // true or false depending on which key is pressed. $(window).keydown(function(e) { keyStates[e.keyCode || e.which] = true; }).keyup(function(e) { keyStates[e.keyCode || e.which] = false; }); /* ----------------------------------------------------------------------------------------------------- */ /* ----------------------------------------------------------------------------------------------------- */ /* Functions */ /* ----------------------------------------------------------------------------------------------------- */ // The main game loop. function GameLoop() { // Check which keys are pressed and modify the player's position. CheckKeyPresses(); // Check to make sure the ship is still within the browser window. EnsureNoOutOfBounds(); // Check if the player is at the window border and activate the border // highlight if so. EnableBorderMarker(); // Draw all the ships on the canvas. DrawAllShips(); DrawAbilitiesBar(); // Repeat on next screen refresh. window.requestAnimationFrame(GameLoop); } // Sets up the canvas size and pixel resolution. function SetupCanvas() { // Set the canvas width, height, and resolution to match the window size. canvas.width(windowW); canvas.height(windowH); canvas[0].width = windowW; canvas[0].height = windowH; abilities_canvas[0].width = 450; abilities_canvas[0].height = 40; // Set the width and height of the window border container $('#canvas_inset_shadow_container').width(windowW); $('#canvas_inset_shadow_container').height(windowH); } // Loads all the images. function LoadImages() { // Load the player ship image. player_ship_image = new Image(); player_ship_image.src = 'images/ships/player_ship.png'; // Once loaded, notify in the console and check if all images loaded. player_ship_image.onload = function() { console.log("Player ship image loaded."); ReportAllImagesLoaded(); } } // Checks if all images have loaded and reports to user. function ReportAllImagesLoaded() { // Increment the number of images loaded. imagesLoaded++; // If the images loaded equals the number of images we are supposed to load... if (imagesLoaded == imagesToLoad) { // Notify in the console. console.log("All images loaded."); // Initialize all the ships. InitializeShips(); } } // Creates new ships objects for each ship function InitializeShips() { // Create the player ship, starting it at the center of the screen. player_ship = new Ship(player_ship_image, windowW / 2, windowH / 2, 16, 32, 0); // Start the "game". GameLoop(); } // Calls the DrawImage() method for each ship object to draw them. function DrawAllShips() { // Clear the canvas. ctx.clearRect(0, 0, windowW, windowH); // Draw the player's ship. player_ship.DrawImage(); } // Ship class containing image, position, and rotation. // Rotation starts at 90 degrees (direct north) and goes clockwise. function Ship(image_src, pos_x, pos_y, width, height, rotation) { // The actual image variable. this.image = image_src; // Set the x and y position of the image. this.pos_x = pos_x; this.pos_y = pos_y; // Set the width and height of the image. this.image_width = width; this.image_height = height; // Set the rotation of the image. this.rotation = rotation; // Loads the image from the image source. this.SetImage = function(new_image) { this.image = new_image; } // Sets the x-position of the image. this.SetPos_X = function(new_pos_x) { this.pos_x = new_pos_x; } // Sets the y-position of the image. this.SetPos_Y = function(new_pos_y) { this.pos_y = new_pos_y; } // Sets the rotation of the image. this.SetRotation = function(new_rotation) { this.rotation = new_rotation; } // Returns the x-position of the image. this.GetPos_X = function() { return this.pos_x; } // Returns the y-position of the image. this.GetPos_Y = function() { return this.pos_y; } // Returns the rotation of the image. this.GetRotation = function() { return this.rotation; } // Returns the width of the image. this.GetImageWidth = function() { return this.image_width; } // Returns the height of the image. this.GetImageHeight = function() { return this.image_height; } // Draws the image on the canvas. this.DrawImage = function() { // Save the canvas. ctx.save(); // Move the canvas to the image's position. ctx.translate(this.pos_x, this.pos_y); // Rotate the canvas (the image along with it) by the image's rotation. ctx.rotate(this.rotation * Math.PI / 180); // Center the image on its position. ctx.translate(-(this.GetImageWidth() / 2), -(this.GetImageHeight() / 2)); // Draw the image. ctx.drawImage(this.image, 0, 0, this.image_width, this.image_height); // Restore the canvas to before it was translated and rotated. ctx.restore(); } } // Checks key presses and updates player ship information based on it. function CheckKeyPresses() { // Check and update the rotation of the player's ship. // Rotate counter-clockwise by 5 degrees if left arrow or 'a' is pressed. if ((keyStates[37] == true) || (keyStates[65] == true)) { // If turning counter-clockwise results in a rotation // less than -180 degrees, set to +175 degrees. if ((player_ship.GetRotation() - 5) < -180) { player_ship.SetRotation(175); } // Otherwise, get the rotation and subtract 5 degrees. else { player_ship.SetRotation(player_ship.GetRotation() - 5); } } // Rotate clockwise by 5 degrees if right arrow or 'd' is pressed. if ((keyStates[39] == true) || (keyStates[68] == true)) { // If turning clockwise results in a rotation // greater than +180 degrees, set to -175 degrees. if ((player_ship.GetRotation() - 5) > 180) { player_ship.SetRotation(-175); } // Otherwise, get the rotation and add 5 degrees. else { player_ship.SetRotation(player_ship.GetRotation() + 5); } } // If any of the move forward or move backward keys are pressed... if ((keyStates[38] == true) || // Up arrow. (keyStates[40] == true) || // Down arrow. (keyStates[87] == true) || // 'w' key. (keyStates[83] == true)) // 's' key. { // If the shift key is pressed, change ship "speed" to 8px. if (keyStates[16] == true) { moveDistance = 8; } // Otherwise, set it to 5px. else { moveDistance = 5; } // If the rotation is 0 degrees (ship is pointing "up")... if (player_ship.GetRotation() == 0) { // If the ship is supposed to move forward... if ((keyStates[38] == true) || (keyStates[87] == true)) { // Get the current ship position. var y_pos = player_ship.GetPos_Y(); // Set the position to 5 pixels ahead of where it is. player_ship.SetPos_Y(y_pos - moveDistance); } // If the ships is supposed to move backwards... if ((keyStates[40] == true) || (keyStates[83] == true)) { // Get the current ship position. var y_pos = player_ship.GetPos_Y(); // Set the position to 5 pixels behind where it is. player_ship.SetPos_Y(y_pos + moveDistance); } } // Else if the rotation is +180 or -180 degrees (player ship is pointing "down")... else if ((player_ship.GetRotation() == 180) || (player_ship.GetRotation() == -180)) { // If the ship is supposed to move forward... if ((keyStates[38] == true) || (keyStates[87] == true)) { // Get the current ship position. var y_pos = player_ship.GetPos_Y(); // Set the position to 5 pixels ahead of where it is. player_ship.SetPos_Y(y_pos + moveDistance); } // If the ships is supposed to move backwards... if ((keyStates[40] == true) || (keyStates[83] == true)) { // Get the current ship position. var y_pos = player_ship.GetPos_Y(); // Set the position to 5 pixels behind where it is. player_ship.SetPos_Y(y_pos - moveDistance); } } // Else if the player ship is between 0 and -180 degrees... else if (player_ship.GetRotation() < 0) { // Get the current ship position. var x_pos = player_ship.GetPos_X(); var y_pos = player_ship.GetPos_Y(); // The change in x and y directions. var deltaX = 0; var deltaY = 0; // Get the ship's rotation. var ship_angle = player_ship.GetRotation(); // If the angle is in the second quadrant (top-left)... if (ship_angle >= -90) { // Convert rotation to radians and calculate the change in // the x-direction using Soh-Cah-Toa (sin(theta) = opposite/hypotenuse). deltaX = moveDistance * Math.sin(ToRadians(ship_angle)); // Convert rotation to radians and calculate the change in // the y-direction using Soh-Cah-Toa (cos(theta) = adjacent/hypotenuse). deltaY = moveDistance * Math.cos(ToRadians(ship_angle)); // Negate the change in y so it "points" in the right direction. deltaY = deltaY * (-1); } // Else if the angle is in the third quadrant (bottom-left)... else if (ship_angle < -90) { // Convert rotation to radians and calculate the change in // the x-direction using Soh-Cah-Toa (cos(theta) = adjacent/hypotenuse). deltaX = moveDistance * Math.cos(ToRadians(ship_angle + 90)); // Convert rotation to radians and calculate the change in // the y-direction using Soh-Cah-Toa (sin(theta) = opposite/hypotenuse). deltaY = moveDistance * Math.sin(ToRadians(ship_angle + 90)); // Negate the change in y and x so it "points" in the right direction. deltaX = deltaX * (-1); deltaY = deltaY * (-1); } // If the ship is supposed to move forward... if ((keyStates[38] == true) || (keyStates[87] == true)) { // Move the ship 5 pixels ahead of where it is. player_ship.SetPos_X(x_pos + deltaX); player_ship.SetPos_Y(y_pos + deltaY); } // If the ships is supposed to move backwards... if ((keyStates[40] == true) || (keyStates[83] == true)) { // Move the ship 5 pixels behind of where it is. player_ship.SetPos_X(x_pos - deltaX); player_ship.SetPos_Y(y_pos - deltaY); } } // Else if the player ship is between 0 and +180 degrees... else if (player_ship.GetRotation() > 0) { // Get the current ship position. var x_pos = player_ship.GetPos_X(); var y_pos = player_ship.GetPos_Y(); // The change in x and y directions. var deltaX = 0; var deltaY = 0; // Get the ship's rotation. var ship_angle = player_ship.GetRotation(); // If the angle is in the second quadrant (top-left)... if (ship_angle <= 90) { // Convert rotation to radians and calculate the change in // the x-direction using Soh-Cah-Toa (sin(theta) = opposite/hypotenuse). deltaX = moveDistance * Math.sin(ToRadians(ship_angle)); // Convert rotation to radians and calculate the change in // the y-direction using Soh-Cah-Toa (cos(theta) = adjacent/hypotenuse). deltaY = moveDistance * Math.cos(ToRadians(ship_angle)); // Negate the change in y so it "points" in the right direction. deltaY = deltaY * (-1); } // Else if the angle is in the third quadrant (bottom-left)... else if (ship_angle > 90) { // Convert rotation to radians and calculate the change in // the x-direction using Soh-Cah-Toa (cos(theta) = adjacent/hypotenuse). deltaX = moveDistance * Math.cos(ToRadians(ship_angle - 90)); // Convert rotation to radians and calculate the change in // the y-direction using Soh-Cah-Toa (sin(theta) = opposite/hypotenuse). deltaY = moveDistance * Math.sin(ToRadians(ship_angle - 90)); // Negate the change in y so it "points" in the right direction. //deltaY = deltaY * (-1); } // If the ship is supposed to move forward... if ((keyStates[38] == true) || (keyStates[87] == true)) { // Move the ship 5 pixels ahead of where it is. player_ship.SetPos_X(x_pos + deltaX); player_ship.SetPos_Y(y_pos + deltaY); } // If the ships is supposed to move backwards... if ((keyStates[40] == true) || (keyStates[83] == true)) { // Move the ship 5 pixels behind of where it is. player_ship.SetPos_X(x_pos - deltaX); player_ship.SetPos_Y(y_pos - deltaY); } } } } // Converts the angle to radians. function ToRadians(angle) { return angle * (Math.PI / 180); } // Converts the angle to degrees. function ToDegrees(angle) { return angle * (180 / Math.PI); } // Checks to make sure that the player's ship does not leave the window. function EnsureNoOutOfBounds() { // If the player's ship is within 15 pixels of the left side of the screen, // set it's x-position to no less than 15 pixels. if (player_ship.GetPos_X() < 15) { player_ship.SetPos_X(15); } // If the player's ship is within 15 pixels of the right side of the screen, // set it's x-position to no more than 15 pixels from the right. if (player_ship.GetPos_X() > windowW - 15) { player_ship.SetPos_X(windowW - 15); } // If the player's ship is within 15 pixels of the top side of the screen, // set it's y-position to no less than 15 pixels. if (player_ship.GetPos_Y() < 15) { player_ship.SetPos_Y(15); } // If the player's ship is within 15 pixels of the bottom side of the screen, // set it's y-position to no more than 15 pixels from the bottom. if (player_ship.GetPos_Y() > windowH - 15) { player_ship.SetPos_Y(windowH - 15); } } // Changes the box shadow of the left, top, right, and bottom divs to red when the ship touches // that border, and deactivates the border highlight when the ship moves away from it. function EnableBorderMarker() { // Left border. if (player_ship.GetPos_X() === 15 && borderLeft === false) { borderLeft = true; $('#canvas_shadow_container_left').css('box-shadow', '0 0 10px 5px red'); } if (player_ship.GetPos_X() !== 15 && borderLeft === true) { borderLeft = false; $('#canvas_shadow_container_left').css('box-shadow', 'none'); } // Right border. if (player_ship.GetPos_X() === (windowW - 15) && borderRight === false) { borderRight = true; $('#canvas_shadow_container_right').css('box-shadow', '0 0 10px 5px red'); } if (player_ship.GetPos_X() !== (windowW - 15) && borderRight === true) { borderRight = false; $('#canvas_shadow_container_right').css('box-shadow', 'none'); } // Top border. if (player_ship.GetPos_Y() === 15 && borderTop === false) { borderTop = true; $('#canvas_shadow_container_top').css('box-shadow', '0 0 10px 6px red'); } if (player_ship.GetPos_Y() !== 15 && borderTop === true) { borderTop = false; $('#canvas_shadow_container_top').css('box-shadow', 'none'); } // Bottom border. if (player_ship.GetPos_Y() === (windowH - 15) && borderBottom === false) { borderBottom = true; $('#canvas_shadow_container_bottom').css('box-shadow', '0 0 10px 6px red'); } if (player_ship.GetPos_Y() !== (windowH - 15) && borderBottom === true) { borderBottom = false; $('#canvas_shadow_container_bottom').css('box-shadow', 'none'); } } // Draw the speed boost bar in the abilities tab. Indicates how much boost is left. function DrawAbilitiesBar() { // Save the abilities bar context. abilities_ctx.save(); // Clear the abilities bar canvas. abilities_ctx.clearRect(0, 0, 450, 40); // Set the width of the speed bar border to 2px; abilities_ctx.lineWidth = "2"; // Set the border color to white with 50% opacity. abilities_ctx.strokeStyle = "rgba(255, 255, 255, 0.5)"; // Create the speed boost bar border to evenly fill the rest of the container. // Does not appear until stroke() or fill() is called. abilities_ctx.rect(160 , 13, 270, 16); // Stroke the border with the stroke color. abilities_ctx.stroke(); // Calculate the width of the actual speed boost bar using the boost_bar_percent // and multiplying it by the space inside the border. var boost_bar_width = (boost_bar_percent / 100) * 264; // The bar will be full white. abilities_ctx.fillStyle = "white"; // Fill the speed boost bar to the calculated width. abilities_ctx.fillRect(163, 16, boost_bar_width, 10); // Restore the abilities bar context. abilities_ctx.restore(); } }); I know I've done some things inefficiently and the game isn't completed (the speed boost bar does not have any functionality at the moment). I would appreciate if anyone could point out or help me figure out why it has started to lag. Here is a link to the github repository. Answer: I discovered why it would lag after 10 seconds. After some debugging I figured out it was coming from my DrawAbilitiesBar() function. Apparently it was because I was using ctx.rect(windowW - 300 , windowH - 37, 270, 16); ctx.stroke(); instead of ctx.strokeRect(windowW - 300 , windowH - 37, 270, 16); Using the second fixed my issue.
{ "domain": "codereview.stackexchange", "id": 15087, "tags": "javascript, performance, jquery, html5, canvas" }
aluminum as cathode electrode
Question: Aluminum really wants to and will form aluminum oxide. Upon research, aluminum oxide is fairly unreactive. I wanted to ask if I had aluminum anode which would quickly form aluminum oxide (which is unreactive), will that inhibit the aluminum from being oxidized? Basically, will aluminum metal loose electrons and become an aluminum ion? Answer: Aluminum can and is used as both anodes and cathodes in electrochemical cells, but there are some peculiarities to using it as an anode in aqueous solutions. As you note, aluminum forms a passivating oxide layer quite readily, even by exposure to atmosphere. In an aqueous solution, if the potential is high enough, $\ce{OH-}$ and $\ce{O^2-}$ are generated at the anode, which can then react with the aluminum to produce aluminum oxide. $\ce{Al^3+}$ can also be generated directly. The electric field will draw the anions through the growing aluminum oxide layer towards the aluminum surface and the $\ce{Al^3+}$ towards the solution, making the oxide layer grow both away from the electrode surface and into the surface of the electrode. In this way, coatings thicker than the normal passivation in air can be produced. However, aluminum oxide is a good electrical insulator, thus if a dense non-porous layer is grown, it will become impossible to pass current through it and growth will stop, leaving a relatively thin oxide layer (this is how the dielectric layers in electrolytic capacitors are made). This is the normal behaviour in aqueous solutions at near-neutral pH (5–7). [1] However, if a thick aluminum oxide layer is desired (e.g. to produce coatings on aluminum parts for dying or durability), maintaining porosity is necessary to avoid completely blocking access to the surface. One technique that is commonly used is using a low pH solution, which tends to redissolve some of the oxide and neutralize some of the formed $\ce{OH-}$, leaving pores in the oxide layer through which the ions can travel and continue to react. These pores also give a good structure to retain dyes or lubricants, but generally need to be sealed after to protect against corrosion.
{ "domain": "chemistry.stackexchange", "id": 6153, "tags": "electrochemistry" }
Review my first jQuery slider plugin
Question: This is my first jQuery plugin. It is a simple slider that requires very little mark up in html. It works for my purposes but I am not a jQuery expert and I am wondering if there are mistakes or shortcuts that I took in its creation. Thank you for taking a look at the plugin! The HTML <script type="text/javascript"> $(document).ready(function(){ $('.st-slider').stSlider(); }); </script> <div id="feature-slider" class="st-slider"> <ul> <li data-collection-name="Collection 1"><a href="#"><img src="images/slide1.jpg"></a></li> <li data-collection-name="Collection 2"><a href="#"><img src="images/slide2.jpg"></a></li> <li data-collection-name="Collection 3"><a href="#"><img src="images/slide3.jpg"></a></li> <li data-collection-name="Collection 4"><a href="#"><img src="images/slide4.jpg"></a></li> </ul> </div> The CSS .st-slider { overflow: hidden; width: 685px; height: 412px; margin-top: 15px; position: relative; margin-bottom: 70px; } .st-slider ul { margin: 0; padding: 0; position: relative; } .st-slider ul li { display: block; margin: 0; padding: 0; background: #fff; float: left; padding: 5px; border: 1px solid #ddd; } .st-slider .st-slider-caption { background: rgba(215,204,186,0.8); font-size: 18px; color: #fff; text-transform: uppercase; letter-spacing: .3em; position: relative; z-index: 2; text-align: center; height: 40px; top: 280px; width: 685px; } .st-slider .st-slider-caption span { position: absolute; top: 9px; left: 0; text-align: center; width: 685px; } .st-slider .st-slider-nav { position: relative; top: 229px; z-index: 3; height: 62px; width: 100%; } .st-slider .st-slider-nav div { background: url('../images/st-slider-nav.png'); width: 30px; height: 62px; position: absolute; cursor: pointer; } .st-slider .st-slider-nav .next { background-position: -30px 0; left: 655px; } .st-slider .st-slider-nav .prev:hover { background-position: -60px 0; } .st-slider .st-slider-nav .next:hover { background-position: -90px 0; } .st-slider-go-to-nav { display: block; margin-top: -55px; padding-top: 0; font-size: 12px; color: #aaa; float: right; } .st-slider-go-to-nav { list-style: none; } .st-slider-go-to-nav li { padding: 0; margin-right: 10px; float: left; } .st-slider-go-to-nav li:last-child { margin-right: 0; } .st-slider-go-to-nav li a { padding: 5px 8px; color: #aaa; text-decoration: none; cursor: pointer; } .st-slider-go-to-nav li a:hover, .st-slider-go-to-nav li.current a { color: #666; background: #eee; } The jQuery (function( $ ) { $.fn.stSlider = function() { var sliderContainer = $(this), slidePane = sliderContainer.find('ul'), cloneFirst = slidePane.find('li:first-child').clone(), cloneLast = slidePane.find('li:last-child').clone(); cloneFirst.attr('data-clone', 'last').appendTo(slidePane); cloneLast.attr('data-clone', 'first').prependTo(slidePane); var slides = slidePane.find('li'); var slideWidth = $(this).width(), negSlideWidth = 0 - slideWidth, slidesArray = $.makeArray(slides), slidePaneWidth = ( slidesArray.length * slideWidth ); // Build slider controls var captionHolderDiv = $('<div class="st-slider-caption"></div>'), captionDiv = $('<span></span> '), navDiv = $('<div class="st-slider-nav"></div>'), prevDiv = $('<div class="prev"></div>'), nextDiv = $('<div class="next"></div>'), goToNav = $('<ul class="st-slider-go-to-nav"></ul>'); // Insert slider controls into DOM slidePane.after(captionHolderDiv); captionDiv.appendTo(captionHolderDiv); captionHolderDiv.after(navDiv); prevDiv.appendTo(navDiv); nextDiv.appendTo(navDiv); sliderContainer.after(goToNav); // Build and insert each slide number link for(var i = 0; i < slidesArray.length - 2; i++) { var count = i + 1; var goToNavItem = $('<li id="' + count + '"><a>' + count + '</a></li>'); goToNavItem.appendTo(goToNav); if ( count == 1 ) { goToNavItem.addClass('current'); } } var slideCaptionHolder = sliderContainer.find('.st-slider-caption span'), slideCaption = sliderContainer.find('li:nth-child(2)').data('collection-name'), goToArray = $('.st-slider-go-to-nav li'); slidePane.width(slidePaneWidth); slides.addClass('st-slider-slide'); slidePane.animate({left: negSlideWidth}, 0); slideCaptionHolder.html(slideCaption); function slide(direction, location) { var x = parseInt(slidePane.css('left'), 10), y = Math.abs(x), i = 0, theSlide = slides.eq(i), slideCaption = theSlide.data('collection-name'), slideClone = theSlide.data('clone'), lastPosition = 0 - slidePaneWidth + (slideWidth * 2); if ( direction == 'null' ) { } else if (direction == 'prev') { i = (y / slideWidth) -1; i = i % slidesArray.length; theSlide = slides.eq(i); slideCaption = theSlide.data('collection-name'); slideClone = theSlide.data('clone'); slidePane.animate({left: parseInt(slidePane.css('left'), 10) + slideWidth}, 600); slideCaptionHolder.fadeOut(300, function() { $(this).html(slideCaption); $(this).fadeIn(300, function(){ if ( slideClone && slideClone == 'first' ) { slidePane.animate({left: lastPosition}, 0); } }); }); goToArray.removeClass('current'); if ( slideClone == 'last') { goToArray.eq(slidesArray.length - 2).addClass('current'); } else { goToArray.eq(i - 1).addClass('current'); } } else { i = (y / slideWidth) +1; i = i % slidesArray.length; theSlide = slides.eq(i); slideCaption = theSlide.data('collection-name'); slideClone = theSlide.data('clone'); slidePane.animate({left: parseInt(slidePane.css('left'), 10) - slideWidth }, 600); slideCaptionHolder.fadeOut(300, function() { $(this).html(slideCaption); $(this).fadeIn(300, function(){ if ( slideClone && slideClone == 'last' ) { slidePane.animate({left: negSlideWidth }, 0); } }); }); goToArray.removeClass('current'); if ( slideClone == 'last') { goToArray.eq(0).addClass('current'); } else { goToArray.eq(i - 1).addClass('current'); } } if ( location ) { i = location; theSlide = slides.eq(i); slideCaption = theSlide.data('collection-name'); slideClone = theSlide.data('clone'); slidePane.animate({left: 0 - (i * slideWidth) }, 600); slideCaptionHolder.fadeOut(300, function() { $(this).html(slideCaption); $(this).fadeIn(300, function(){ if ( slideClone && slideClone == 'last' ) { slidePane.animate({left: negSlideWidth }, 0); } else if ( slideClone && slideClone == 'first' ) { slidePane.animate({left: lastPosition}, 0); } }); }); goToArray.removeClass('current'); goToArray.eq(i - 1).addClass('current'); } } timer = setInterval(slide, 5000); sliderContainer.hover(function(){ clearInterval(timer); }, function(){ timer = setInterval(slide, 5000); }); var slidePrev = sliderContainer.find('.prev'), slideNext = sliderContainer.find('.next'); slidePrev.click(function(){ slide('prev'); }); slideNext.click(function(){ slide(); }); $('.st-slider-go-to-nav li a').click(function(){ if ( $(this).parent().hasClass('current') ) { } else { var location = $(this).parent().attr('id'); slide('null', location); clearInterval(timer); timer = setInterval(slide, 5000); } }); }; })( jQuery ); Answer: Your code seems solid to me, only a few things my eye caught: you're using $(this) in multiple places, while your sliderContainer already holds that jQuery object. This object can be then reused instead of making jQuery convert DOM into jQuery several times instead of writing cloneFirst.attr('data-clone', 'last').appendTo(slidePane); it's advised to use jQuery's data() function to set data for DOM elements: cloneFirst.data('clone', 'last').appendTo(slidePane);
{ "domain": "codereview.stackexchange", "id": 2486, "tags": "javascript, jquery, plugin" }
Why isn't the phosphoglycerate kinase reaction of the glycolysis pathway irreversible?
Question: Step 7 of the glycolysis pathway is the conversion of 1,3-bisphosphoglycerate into 3-phosphoglycerate by the action of the enzyme phosphoglycerate kinase, resulting in the production of 2 ATP molecules (per glucose). This reaction has a large negative value of ΔG (-18.5 kJ/mol). If reactions having large negative value of ΔG are classed as being irreversible, then why is Step 7 of Glycolysis reversible? Answer: The free energy change that you quote for the phosphoglycerate kinase (PGK) forward reaction is, of course, the standard free energy change (ΔG0') for the overall reaction. The standard free energy change is defined for all reactants at a concentration of 1M. Note that this value includes the formation of ATP - the free energy of hydrolysis of 1,3-BPG would be much larger, and some of that energy is 'captured' in the ATP product. The actual free energy change for the PGK reaction, ΔG, will differ from this value because of the fact that the actual reactant concentrations are very far from the idealised 1M. You can find a Table here which compares, for each step in glycolysis, the standard free energy change with a true free energy change, calculated on the basis of cellular conditions in erythrocytes (also shown). You will see that for the PGK step the actual free energy change is 0.09 kJ mol-1 rather than the -18.9 kJ mol-1 that you quote in your question. You can also see from the Table that there are only two reactions in the glycolytic pathway with large negative values for ΔG: those catalysed by phosphofructokinase and by pyruvate kinase. These are of course the two steps that are bypassed in gluconeogenesis because they are essentially irreversible. So - your reasoning was correct, but it was based on the wrong ΔG values. added much later As pointed out in the comments, the 1st step in glycolysis also has a large negative value for ΔG and is also bypassed. Not sure how I forgot to include that!
{ "domain": "biology.stackexchange", "id": 2061, "tags": "biochemistry, metabolism, thermodynamics" }
How to auto-derivate sequential iterative programs from a mathematical specification?
Question: I had to derivate, by hand, sequential iterative programs at school using an unified Hoare-Dijkstra-Hehner programming theory. First, write down the formal specification as a Hoare triple and figure out invariants for loops. Second, apply logic rules and theorems to find an implementation that satisfies completely the specification ensuring total correctness. Actually not an easy job. How to automate this process? is it feasible? Answer: Short answer: no. Long answer: No, because the synthesis problem is in general undecidable once you allow for a modest amount of expressive power in the assertions (pre- and post-conditions). The specification for your synthesizer $S$ would look something like this. Its type would be $S:\mathit{Assn}^2\rightarrow\mathit{Prog}$, that is, given two assertions (a pre- and a post condition) it would return a program. Its functionality would be given by $\{\phi\}S(\phi,\psi)\{\psi\}$, for all $\phi,\psi\in\mathit{Assn}$. I understand your question as "is $S$ computable?" Before we need to get technical, note that we've been a bit sloppy. $S$ can hardly be a total function for we could feed it an infeasible spec such at $[\mathit{true},\mathit{false}]$. Consequently, the best we could hope for is a partial function that works for all implementable specifications. To answer the refined question we need to answer another first. What expressive power would we need in the assertion language? Firstly, assuming that we're living in a simple world where we only deal with integers, we require the usual operations from integer arithmetic. Secondly, we need a mechanism to refer in the post-condition to the value of a program variable in the pre-condition. Without such a mechanism, we cannot even specify an increment-by-one function. Various such mechanisms exist. Let us here use one borrowed from the Z specification language: in the post-condition primed occurrences $x'$ of a variable $x$ refer to its value after the program has terminated whereas unprimed occurrences denote its value in the pre-condition. With this convention the increment-$x$-by-one function is specified by $[true,x'=x+1]$. Thirdly, we'd also want quantifiers so we can at least specify simple examples such as a primality checker $[x > 0, x=x'\land(p\Leftrightarrow x>1\land\forall k(k>1\land \exists j(kj=x)\Rightarrow k=x))]$, and a sorter that takes arrays of arbitrary size as inputs $[\mathit{true},\mathit{length}(a)=\mathit{length}(a')\land\mathit{elements}(a)=\mathit{elements}(a')\land\forall i(1\leq i <\mathit{length}(a')\Rightarrow a'[i]\leq a'[i+1])]$. With those ingredients, we have quite some power at our disposal, too much as it turns out. Even the domain of $S$ is undecidable because we would need to say whether a spec $[\mathit{true},\phi]$ is implementable or not, for arbitrary formulas $\phi$ of Peano arithmetic, before worrying about how to synthesize implementations. But that is already undecidable.
{ "domain": "cstheory.stackexchange", "id": 1777, "tags": "lo.logic, pl.programming-languages, formal-methods, automated-theorem-proving" }
Named tuple with less-than operator
Question: I have the following implementation for the __lt__. Could you please check if it's okay to compare objects like that? class Record(NamedTuple): video_id: str uuid: Optional[UUID] mac: Optional[str] s3_bucket: str s3_key: str reference_date: date @staticmethod def _lt(a: Any, b: Any) -> bool: if a and b: return a < b if a is None and b: return True return False def __lt__(self, other: "Record") -> Union[bool, Type["NotImplementedType"]]: if not isinstance(other, Record): return NotImplemented for field in self._fields: self_ = getattr(self, field) other_ = getattr(other, field) if self_ == other_: continue return self._lt(self_, other_) return False Answer: This code is dangerous: if a and b: return a < b if a is None and b: return True return False Consider a = -1 and b = 0. a and b is False because b is falsey, so a < b is never computed. Since a is None is false, we skip to return False, yielding a surprising result for Record._lt(-1, 0) You should explicitly test a is not None and b is not None instead of a and b. Based on your typing, it currently doesn’t look like you’d pass in an int or a float, but if the class changes in the future, or is used as the model for another similar class, the unexpected behaviour might arise.
{ "domain": "codereview.stackexchange", "id": 41607, "tags": "python, python-3.x" }
Geometric interpretation of perturbation theory in quantum field theory
Question: I am studying GR right now, and one interesting thing I learned about vectors is that they are defined to have the same properties as derivatives. With this in mind, can I make a differential geometric interpretation of ordinary perturbation theory used in quantum field theory in the following way:? The set of all field configurations makes a (very complicated) manifold. We do perturbation theory about a background field configuration corresponding to a point on this manifold. The perturbations are like expanding functions out to first order -- can be viewed like tangent vectors Am I on some track to enlightenment, or is this a dead-end train of thought? Answer: At the non-rigorous/intuitive level, OP's observations are spot on. To facilitate such thinking, physicists often use DeWitt's condensed notation, where a field $\phi^{\alpha}(x)$ is written as $\phi^{i}$, while pretending that $i=(\alpha,x)$ is an index of a local coordinate $\phi^{i}$ for some differential manifold. The problem is that the space of all field configurations is typically an infinite-dimensional space, while ordinary differential geometry is usually only discussed in the context of finite-dimensional manifolds. Thus strictly speaking, one would have to master/study/develop an infinite-dimensional mathematical version of differential geometry to make OP's picture precise/rigorous.
{ "domain": "physics.stackexchange", "id": 5356, "tags": "quantum-field-theory, differential-geometry, perturbation-theory" }
A question on decidable formal languages and turing machines
Question: Let $L' \subseteq L \subseteq \Sigma^*$ be decidable languages with deterministic Turing machines $M'$ and $M$ which decide the languages. Typically we have $t_M(w) \le t_{M'}(w)$ for all $w \in \Sigma^*$, where $t_M(w)$ is the time of $M$ on input $w$. Suppose furthermore that $M$ and $M'$ have minimum length when interpreted on some chosen universal Turing machine $U$. So if $M''$ decides $L'$ then $l(M'')\ge l(M')$ where $l(M)$ is the length of $M$ when interpreted on $U$. Is this just a coincidence of the chosen Turing machines, or does this property hold for all deciders of $L$ and $L'$ with minimum length? "Typically" here means the following situation: For instance if $L'$ is a decision problem on graphs and $L$ is the language of graphs (meaning that words correspond to adjacency matrix of a directed graph), then first for a word $w\in \Sigma^*$ one must decide if this word corresponds to an adjacency matrix of a graph, then decide if that graph has the property one is looking for. If you know a counterexample to that, that would also answer the question. Answer: We can make the relationship between $t_M$ and $t_{M^\prime}$ quite arbitrary. For example, consider $L$ the language of strings that encode a prime number, and $L^\prime$ the language of strings that encode either a prime number, or a satisfiable formula. Then $t_M<t_{M^\prime}$ if P$\not=$NP. On the other hand, if we choose $L^\prime=\Sigma^{\star}$, then $t_{M^\prime}<t_{M}$.
{ "domain": "cs.stackexchange", "id": 7163, "tags": "formal-languages, turing-machines" }
What would be the extent of the feedback on climate of unattended deaths event?
Question: Being given that decaying corpses will stop emitting digestive metane, but would release huge amount of methane during their decaying process, I was wondering if this could be considered among the Climate change feedback loops? To illustrate this, let's just say that scenarii for year 2050 include possibility that population (and livestock) would collapse in a decade. We may have something like 200'000'000 tons mammals decaying in a 5-10 years span... This is not even a quarter on below image, but already so many methane released at once! Edit: I am not looking for existing signs, I am thinking of the effect of billions of mammals death on the greenhouse effect caused by the consequent huge methane release. (copied from https://media.treehugger.com, credits XKCD) Answer: Mass of Earth's atmosphere: $5 \times 10^{18} kg$ Concentration of methane in Earth's atmosphere: $1866 ppb$ Mass of methane in Earth's atmosphere, present day: $9.3 \times 10^{12} kg$ = 9,300,000,000 tons If all those dead mammals were composed entirely of methane, they would increase the atmospheric concentration of methane by about 2%. They aren't, and (as @trond hansen commented) most of their carbon would be converted to $\ce{CO_2}$ with a 30-fold smaller global warming footprint. So, I think it's safe to say the impact of decomposing mammals would be relatively small. Worry more about effects on plants, which constitute 80% of the Earth's biomass; bacteria, which constitute 15%; and fungi, which constitute about 2%. The entire animal kingdom amounts to much less than half a percent of global biomass, and half of that is arthropods (which have their own concerns for the future). (Source: figures from The biomass distribution on Earth, Yinon M. Bar-On, Rob Phillips, and Ron Milo, PNAS June 19, 2018 115 (25) 6506-6511; first published May 21, 2018 https://doi.org/10.1073/pnas.1711842115)
{ "domain": "earthscience.stackexchange", "id": 1759, "tags": "climate-change, carbon-cycle, methane" }
Graph with $\Theta(2^n)$ minimum $(s, t)$-cuts
Question: Is there any graph with $\Theta(2^n)$ minimum $(s, t)$-cuts? Given an undirected graph $G = (V, E)$ and two distinct vertices $s$ and $t$ of $G$. A minimum $(s, t)$-cut is a $(S, T)$ cut of G which has the minimum cost over ALL cuts of G, and which also satisfies the additional requirement that $s \in S$ and $t \in T$. A minimum $(s, t)$-cut does not neccessary have to be a global minimum cut. Answer: If we fix the vertices $s$ and $t$ in the graph, then we can have an exponential number of $(s,t)$ min-cuts. Following is an example of a graph that contains an exponential number of $(s,t)$-min cuts. Let the vertex set be $V = \{s\} \cup \{u_{1},\dotsc,u_{n}\} \cup \{v_1,\dotsc,v_n\} \cup \{t\}$. Let the edges set contains the edges $(s,u_{i})$, $(u_{i},v_{i})$, and $(v_{i},t)$ for each $i \in \{1,\dotsc,n\}$. Therefore, there are total $3 n$ edges. Each edge has capacity $1$. Let $C = (S,T)$ be a cut such that $s \in S$ and $t \in T$. Consider the vertices $u_{i}$ and $v_i$. There are four possibilities: $u_i \in S$ and $v_i \in T$. Then edge $(u_i,v_i)$ is in the cut. $u_i \in T$ and $v_i \in S$. Then edge $(u_i,v_i)$ is in the cut. $u_i \in S$ and $v_i \in S$. Then edge $(v_i,t)$ is in the cut. $u_i \in T$ and $v_i \in T$. Then edge $(s,u_i)$ is in the cut. For every pair of $u_i$ and $v_i$ at least one edge adds to the cut. Therefore, minimum cut cost is at least $n$. To find all the cuts of size exactly $n$, add all the vertices: $u_1,\dotsc,u_n$ to $S$. It is optional to include a vertex $v_{i}$ in the set $S$. The remaining vertices, i.e., $V \setminus S$ belongs to $T$. Any such cut has a capacity $n$. Therefore, it is a min-cut. Since there are $2^n$ choices of including $v_{i}$'s, the total number of min-cuts are $2^n \in 2^{\Theta(|V|)}$. Hence, we get an exponential number of min-cuts. Note: This is an asymptotically tight bound since the possible number of $(S,T)$ cuts are at most $2^{|V|}$.
{ "domain": "cs.stackexchange", "id": 18407, "tags": "graphs, minimum-cuts" }
Why the current doesn't flow in an open branch?
Question: I know that the current will no flow towards the point A since there is no potential difference between A and the corresponding junction. However, between C and B, there is potential difference, so how can we say that no current flow from C towards B? Answer: When you turn that 10 V battery on, think of electrons leaving the negative pole and electrons entering the positive pole. On it's left-hand-side positive pole, electrons are entering and the whole branch becomes overall more positive (higher potential). Soon, though, the potential is so high, that no more electrons wants to leave. No more are entering from the open end, so the "void" of missing electrons soon "holds on" to remaining electrons. When this potential is high enough to hold back against the positive battery pole (when the potential equals the battery pole potential), then electrons stop moving. The current flow stops. This will always happen in open circuits. You need a closed loop to have a steady current, because you can't have any points on the wires being depleted (or accumulating). Any such places will only grow/decrease in potential while being depleted/accumulated until a potential is established to balance out the battery.
{ "domain": "physics.stackexchange", "id": 49645, "tags": "electric-circuits, electric-current, electrical-resistance, voltage, batteries" }
how to label 3d model for segmentation task
Question: I'm working on 3d meshes dataset, i have to label it to train my deep learning model for a segmentation task like the picture shows. I spent days looking for a tool to label my 3d data but unfortunately i found nothing.. What tool i can use to label my data (3d mesh, .obj files) for segmentation task? Answer: I found a way to do manual annotation/labeling for 3D objects using blender and it is difficult to explain only by text, so I recorded a video explaining it with the code a wrote. You can find that here: https://github.com/hamzam0n/3D_objects_annotation
{ "domain": "datascience.stackexchange", "id": 11706, "tags": "deep-learning, image-preprocessing, image-segmentation, image, 3d-object-detection" }
Checking for pangrams in C
Question: This will test if a user entered an pangram (every letter in alphabet used at least once), however with 4 for loops there's got to be a better algorithmic approach or with the language of C itself. pangram.c #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> typedef enum { true, false } bool; typedef struct node{ char letter; bool exists; } node; int main(int argc, char *argv[]){ int SIZE = 500; char input[SIZE]; printf("Enter your pangram: "); fgets(input, SIZE, stdin); // 26 letters node alphabet[26]; int i = 0; for(char c='a'; c<='z'; ++c, i++){ alphabet[i].letter = c; alphabet[i].exists = false; } for(int i=0; i<SIZE; i++){ for(int j=0; j<27; j++){ if(isalpha(input[i]) && input[i] == alphabet[j].letter){ alphabet[j].exists = true; } } } for(int i=0; i<27; i++){ if(alphabet[i].exists==false){ printf(" no pangram, missing letter.\n"); return 1; } } printf("you've entered a pangram.\n"); return 0; } command line: >> gcc -o pangram pangram.c -std=c99; ./pangram Enter your pangram: this should fail no pangram, missing letter. >> gcc -o pangram pangram.c -std=c99; ./pangram Enter your pangram: the quick brown fox jumps over the lazy dog you've entered a pangram. Answer: This is a good challenge. Your code is clear and easy to read. Some things can be improved, in addition to those mentioned in Roland's answer. Choose your main() As we're not using argc and argv, we can use the simpler int main() that takes no arguments. Alternatively (and this makes for easier testing), you could use command-line arguments, and only ask for input if none were given: int main(int argc, char *argv[]) { if (argc < 2) { char input[500]; printf("Enter your pangram: "); fflush(stdout); if (!fgets(input, sizeof input, stdin)) { perror("fgets"); return 1; } return test_pangram(input); } else { int failures = 0; for (int i = 1; i < argc; ++i) { failures += test_pangram(argv[i]); } return failures; } } I've separated the action of the program into a new function test_pangram() so we can call it from both branches of this. Note that I've called fflush() between writing output and reading input. This ensures that the prompt is visible to the user in time. A bug This is wrong: /* BUG */ for(int i=0; i<SIZE; i++){ /* code that uses input[i] */ } When we read input using fgets() it wrote a null-terminated string to input - everything after the NUL character is uninitialized and using it is undefined behaviour. It's quite possible that the unspecified values we read from there could cause a false-positive result (if they fill in the characters missing from the actual input). We need to stop the loop when input[i] is '\0': for(int i=0; input[i]; i++){ /* code that uses input[i] */ } Assumptions about letters This code makes a critical assumption: node alphabet[26]; int i = 0; for(char c='a'; c<='z'; ++c, i++){ alphabet[i].letter = c; alphabet[i].exists = false; } The assumption is that the letters a...z have contiguous character codes. But C doesn't guarantee this, and there are systems where 'z'-'a' is not 25. You're probably using ASCII, or Latin-1, or UTF-8, as your encoding, where your assumption turns out lucky, but if your code is compiled for an EBCDIC-based machine (for example), you will write beyond the end of alphabet during this loop. That's not a Good Thing. A safer way to approach this is to do the processing in the opposite order: instead of looking up each character as you see it, we can simply keep a note of each different character seen (letter or otherwise), and afterwards check that all the letters are marked. That requires a bit more storage, but it will be a bit more efficient: int test_pangram(const char *input) { char seen[UCHAR_MAX+1] = { 0 }; for (const char *p = input; *p; ++p) { unsigned char c = (unsigned char)*p; seen[c] = 1; } for (unsigned int i = 0; i < sizeof seen; ++i) { if (!seen[i] && islower(i)) { /* missing a required letter */ return 1; } } return 0; } There are a few things to note here: I use sizeof seen so I can get the compiler to provide the right value where it's needed. I've used a pointer p rather than indexing into input - it's exactly equivalent, but shorter and more idiomatic C. Characters all need to be converted to unsigned char before being used with the <ctype.h> functions - this is one of the annoying constraints of those functions. Because I've used isalpha(), we stand a better chance of making this work in locales other than English - e.g. Danish, where æ, ø, å and ü are letters, too. Consider uppercase characters Traditionally, pangrams ignore the case of characters. You should be able to modify the program so that uppercase characters count towards seen. Possibly the simplest way to do this is to count both upper and lower versions of each character (toupper() and tolower() just return their inputs for the non-alphabetic characters). Then remove the islower(i) test from the second loop. Modified program Here's my take on this problem, with the changes I've proposed: #include <ctype.h> #include <limits.h> #include <stdio.h> /* return true if it's a pangram */ int test_pangram(const char *input) { char seen[UCHAR_MAX+1] = { 0 }; for (const char *p = input; *p; ++p) { unsigned char c = (unsigned char)*p; seen[toupper(c)] = 1; seen[tolower(c)] = 1; } for (unsigned int i = 0; i < sizeof seen; ++i) { if (!seen[i] && isalpha(i)) { printf("Not a pangram - missing '%c'.\n", (char)i); return 0; } } printf("You've entered a pangram.\n"); return 1; } int main(int argc, char *argv[]) { if (argc < 2) { char input[500]; printf("Enter your pangram: "); fflush(stdout); if (!fgets(input, sizeof input, stdin)) { perror("fgets"); return 1; } return !test_pangram(input); } else { int failures = 0; for (int i = 1; i < argc; ++i) { failures += !test_pangram(argv[i]); } return failures; } }
{ "domain": "codereview.stackexchange", "id": 29569, "tags": "algorithm, c, strings" }
Velocity in the lift equation
Question: What exactly is the nature of the velocity in the lift equation? I have read that it is the velocity of the aircraft, and I think I have read that it is the relative velocity of the air to the wing/airfoil. If I were holding a wing over my head and running at 5 mph into a breeze of 5 mph, would the velocity for the lift equation in this instance be 10 mph? Answer: The velocity is the free-stream velocity which is the velocity the body sees in a body-fixed coordinate system. So, if you are moving forward at 5mph and there is a 5mph wind in your face, then in the body-fixed coordinate system, the velocity is 10mph and this is the free-stream velocity.
{ "domain": "physics.stackexchange", "id": 63391, "tags": "velocity, aerodynamics, air, lift" }
Calculate number of max and min outliers from data.frame
Question: I am working on a problem where I need to get specific information for min and max outliers. This is in relation to the ggplot library. I will be getting all my information from ggplot_build object. The data that is used will look something like this: cleandata <- data.frame(middle=c(1, 4, 7), xmiddle=c(2, 9, 1)) cleandata$outliers <- list(c(-3, 1.5, 6), 5, 8) flipped <- TRUE Or to have actual example data yourself this code would work: boxplot = ggplot(mpg, aes(class, hwy)) + geom_boxplot(varwidth = TRUE) boxplot_b = ggplot_build(boxplot ) flipped <- boxplot_b [["data"]][[1]][["flipped_aes"]] == length(boxplot_b [["data"]][[1]][["flipped_aes"]]) cleandata = boxplot_b [["data"]][[1]] Although any boxplot will work with a little change of code listed. I have this bit of code that will get the min and max outliers in two vectors. maxoutliers = c() minoutliers = c() for (box in seq_along(cleandata$outliers)) { outliers = cleandata$outliers[[box]] if (flipped) { middle = cleandata$xmiddle[box] } else { middle = cleandata$middle[box] } maxoutliers[length(maxoutliers)+1] = outliers[outliers > middle] |> length() minoutliers[length(minoutliers)+1] = outliers[outliers < middle] |> length() } flipped is whether the boxplot is horizontal or not. And cleandata is the data frame you can see above. I just feel like there is a cleaner way to do this but I can’t seem to think of a way. Answer: R is a vectorized language, and code is often nicer when we keep things as vectors instead of looping through their elements. For instance, we could replace your code selecting the "middle" element for each row of your data with: middle <- if (flipped) cleandata$xmiddle else cleandata$middle Now, middle is a vector containing the correct "middle" value for each row of your data. At this point, you want to compute the number of elements in each of your outliers vectors that are above or below the corresponding middle value for that row. You do this by computing outliers[outliers > middle] |> length() and outliers[outliers < middle] |> length() and then concatenating those results one element at a time into vectors you are building. Building a vector this way is actually a big no-no in R -- it needs to reallocate the whole output vector each iteration of your loop and can be painfully slow for large loops (for more discussion of this topic, see Circle 2 of The R Inferno). At the end of the day, you want to loop through each pair of middle/outliers and do your calculations, storing the result into a properly-sized vector. Looping through multiple lists at once (akin to zip in python) and outputting to a properly sized output can be accomplished with mapply in R: minoutliers <- mapply(function(x, y) sum(x < y), cleandata$outliers, middle) maxoutliers <- mapply(function(x, y) sum(x > y), cleandata$outliers, middle) Notice that keeping things vectors as long as possible has given us one final advantage -- our code is much shorter (just 3 lines).
{ "domain": "codereview.stackexchange", "id": 44188, "tags": "r" }
In the solution of this problem, why choose the positive square root?
Question: I was solving the following problem: I made it but I got confused by something: I've obtained more solutions than I should. I went to see the solution in hope of clearing it up, the solution is: Now here is where I got confused: QUESTION: They assumed that $q_1 + q_2 \geq 0$, was that made out of mathematical convenience or choosing $q_1 + q_2 \geq 0$ has some physical meaning? It's not clear to me why choose the positive square root here. Answer: It says right in the problem statement that the total charge is positive. Of the initial charges on the spheres, with a positive net charge, what was [...]
{ "domain": "physics.stackexchange", "id": 75894, "tags": "electrostatics, electric-fields, charge, coulombs-law" }
Organising classes that return lists in C#
Question: Historically in my classes I've simply had a number of methods which would return DataSets based on data returned from a stored procedure. Recently however I've moved to giving my classes properties and returning data via lists as shown in the class below. public class Contribution { public int MemberNumber { get; } public DateTime DateDue { get; } public DateTime DateReceived { get; } public string TransactionType { get; } public string ContributionType { get; } public decimal ContributionAmount { get; } public decimal ContributionExpenses { get; } public decimal SocialTax { get; } public decimal Insurance { get; } public decimal AdminFee { get; } public decimal BrokerFee { get; } public decimal Investable { get; } public Contribution(int memberNumber, DateTime dateDue, DateTime dateReceived, string transactionType, string contributionType, decimal contributionAmount, decimal contributionExpenses, decimal socialTax, decimal insurance, decimal adminFee, decimal brokerFee, decimal investable) { MemberNumber = memberNumber; DateDue = dateDue; DateReceived = dateReceived; TransactionType = transactionType; ContributionType = contributionType; ContributionAmount = contributionAmount; ContributionExpenses = contributionExpenses; SocialTax = socialTax; Insurance = insurance; AdminFee = adminFee; BrokerFee = brokerFee; Investable = investable; } public static List<Contribution> GetContributions(Member member, DateTime startDate, DateTime endDate) { var contributions = new List<Contribution>(); string[] adminCodes = {"AADMIN", "EADMIN", "RADMIN"}; string[] brokerCodes = {"ABROK", "EBROK", "RBROK"}; var insuranceCodes = Classes.Member.Insurance.GetCodes(member); var products = Product.GetProducts(member); using (var connection = new SqlConnection(Common.GetConnectionString())) { var cmd = new SqlCommand("GetMemberContributions", connection) {CommandType = CommandType.StoredProcedure}; cmd.Parameters.Add("@MemberNumber", SqlDbType.Int).Value = member.MemberNumber; cmd.Parameters.Add("@StartDate", SqlDbType.DateTime).Value = startDate; cmd.Parameters.Add("@EndDate", SqlDbType.DateTime).Value = endDate; connection.Open(); var ds = new DataSet(); var da = new SqlDataAdapter(cmd); da.Fill(ds); if (ds.Tables[0].Rows.Count == 0) return contributions; foreach (DataRow row in ds.Tables[0].Rows) { DateTime.TryParse(row["Due"].ToString().Trim(), out DateTime dateDue); DateTime.TryParse(row["Received"].ToString().Trim(), out DateTime dateReceived); decimal.TryParse(row["Amount"].ToString().Trim(), out decimal amount); decimal.TryParse(row["Expenses"].ToString().Trim(), out decimal expenses); var transactionType = row["TransactionType"].ToString().Trim(); var contributionType = row["ContributionType"].ToString().Trim(); decimal socialTax = 0; decimal insurance = 0; decimal adminFee = 0; decimal brokerFee = 0; decimal investable = 0; if (transactionType == "TAX") socialTax = amount; if (transactionType == "FEE") { if (adminCodes.Contains(contributionType)) adminFee = amount; if (brokerCodes.Contains(contributionType)) brokerFee = amount; } if (insuranceCodes.Find(i => i.Code == contributionType) != null) insurance = amount; var x = contributionType.Substring(1, contributionType.Length - 1); //remove the leading A, E, R to match contribution type to product code if (products.Find(i => i.Code == x) != null) investable = amount; var contribution = new Contribution( Convert.ToInt32(row["Member"]), dateDue, dateReceived, transactionType, contributionType, amount, expenses, socialTax, insurance, adminFee, brokerFee, investable ); contributions.Add(contribution); } } return contributions; } } An answer given to the previous version of my question advised that the GetContributions method should not live within the above class. However my original question was how best to include another method that returned a total of contributions per type. I currently have this second method in the below class but I don't believe this is the best approach as I would end up with a new class for each method that returned a different data structure. public class ContributionTotal { public string ContributionType { get; } public string ContributionDescription { get; } public decimal Total { get; } public DateTime LastContributionDate { get; } public decimal LastContributionAmount { get; } public ContributionTotal(string contributionType, string contributionDescription, decimal total, DateTime lastContributionDate, decimal lastContributionAmount) { ContributionType = contributionType; ContributionDescription = contributionDescription; Total = total; LastContributionDate = lastContributionDate; LastContributionAmount = lastContributionAmount; } public static List<ContributionTotal> GetContributionTotals(Member member) { var contributionTotals = new List<ContributionTotal>(); using (var connection = new SqlConnection(Common.GetConnectionString())) { var cmd = new SqlCommand("GetMemberTotalContributions", connection) {CommandType = CommandType.StoredProcedure}; cmd.Parameters.AddWithValue("@MemberNumber", member.MemberNumber); cmd.Parameters.AddWithValue("@SchemeCode", member.SchemeCode); connection.Open(); var ds = new DataSet(); var da = new SqlDataAdapter(cmd); da.Fill(ds); if (ds.Tables[0].Rows.Count == 0) return contributionTotals; //calculate latest contribution date for each contribution type var avcLastContributionDate = DateTime.MinValue; var employeeLastContributionDate = DateTime.MinValue; var employerLastContributionDate = DateTime.MinValue; foreach (DataRow row in ds.Tables[0].Rows) { var contributionType = row["pmc_cont"].ToString().Substring(0, 1); //Should return either A, E or R for AVC, Employee or Employer if (!DateTime.TryParse(row["LastDate"].ToString().Trim(), out DateTime lastDate)) continue; if (lastDate > avcLastContributionDate && contributionType == "A") avcLastContributionDate = lastDate; if (lastDate > employeeLastContributionDate && contributionType == "E") employeeLastContributionDate = lastDate; if (lastDate > employerLastContributionDate && contributionType == "R") employerLastContributionDate = lastDate; } decimal avcLastContributionAmount = 0; decimal avcTotal = 0; decimal employeeLastContributionAmount = 0; decimal employeeTotal = 0; decimal employerLastContributionAmount = 0; decimal employerTotal = 0; foreach (DataRow row in ds.Tables[0].Rows) { var contributionType = row["ContributionType"].ToString().Substring(0, 1); //Should return either A, E or R for AVC, Employee or Employer if (!DateTime.TryParse(row["LastDate"].ToString().Trim(), out DateTime lastDate)) continue; if (!decimal.TryParse(row["LastAmount"].ToString().Trim(), out decimal lastAmount)) continue; if (!decimal.TryParse(row["Total"].ToString().Trim(), out decimal total)) continue; if (avcLastContributionDate == lastDate && contributionType == "A") { avcLastContributionAmount += lastAmount; avcTotal += total; } if (employeeLastContributionDate == lastDate && contributionType == "E") { employeeLastContributionAmount += lastAmount; employeeTotal += total; } if (employerLastContributionDate == lastDate && contributionType == "R") { employerLastContributionAmount += lastAmount; employerTotal += total; } } if(avcTotal > 0) contributionTotals.Add(new ContributionTotal("A", "Employee Voluntary", avcTotal, avcLastContributionDate, avcLastContributionAmount)); if (employeeTotal > 0) contributionTotals.Add(new ContributionTotal("E", "Employee Regular", employeeTotal, employeeLastContributionDate, employeeLastContributionAmount)); if (employerTotal > 0) contributionTotals.Add(new ContributionTotal("R", "Employer Regular", employerTotal, employerLastContributionDate, employerLastContributionAmount)); return contributionTotals; } } } The methods mentioned above are called from the code behind of my ASP.NET web application as shown below private void GetContributionHistory() { var member = (Member)Session["Member"]; var contributions = Contribution.GetContributions(member, ContributionHistoryStartDate, ContributionHistoryEndDate); rptContributionHistory.DataSource = contributions; rptContributionHistory.DataBind(); } private void GetTotalContributions() { var member = (Member)Session["Member"]; var totalContributions = ContributionTotal.GetContributionTotals(member); rptContributionTotals.DataSource = totalContributions; rptContributionTotals.DataBind(); var total = totalContributions.Sum(totalContribution => totalContribution.Total); ltTotalContributions.Text = Common.FormatCurrency(total); ltContributionsSinceJoining.Text = Common.FormatCurrency(total); } Answer: Well, in my opinion transaction should definitely NOT be responsible for getting a list of itself... Not only it makes little sense from domain perspective but it also violates SRP. Another major concern is that this design clearly encourages having classes with lots of hidden static dependencies. This problem alone is good enough reason to avoid it.
{ "domain": "codereview.stackexchange", "id": 26804, "tags": "c#, object-oriented" }
Why is the center of mass frame always used in rigid body dynamics?
Question: In most of the cases the center of mass is chosen for rigid body motion description, but this is not an obliged choice, since the motion of any point $P$ of the rigid body can be seen as the combination of a traslation of another point $Q$ and a rotation about an axis passing through $Q$. I'm trying to understand what are the main reason why the center of mass is chosen as the origin for the frame of reference in rigid body dynamics. I thought about these main reasons: Center of mass theorem: $\sum F^{(external)}=M a_{CM}$. Nevertheless this concerns traslation motion only and the traslational velocities of the points of the rigid body are all the same, so in principle I could write $\sum F^{(external)}=Ma_{P}$, where $P$ is a random point of the rigid body. Does that makes sense? Koenig theorems (kinetic energy and angular momentum) Parallel axis theorem The last two, as far as I understood, are valid only if the center of mass frame is used and in no other case. Is it correct? Are these the main reason why the center of mass frame is used in rigid body dynamics, or are there other reason behind this choice? Answer: You don't have to, but it makes the equations easier to deal with because you don't have to account for the moment of acceleration terms. See the 2nd part this this answer about deriving Newton's laws on an abitrary point not the center of mass. So finally the equations of motion of a rigid body, as described by a frame A not on the center of gravity C is (rather messy) $$ \boxed{ \begin{aligned} \sum \vec{F} &= m \vec{a}_A - m \vec{c}\times \vec{\alpha} + m \vec{\omega}\times\vec{\omega}\times\vec{c} \\ \sum \vec{M}_A &= I_C \vec{\alpha} + m \vec{c} \times \vec{a}_A - m \vec{c} \times \vec{c} \times \vec{\alpha} +\vec{\omega} \times I_C \vec{\omega} + m \vec{c} \times \left( \vec{\omega} \times \vec{\omega} \times \vec{c} \right) \end{aligned} } $$ The sum of the forces part equates to mass times acceleration of the center of mass. If the COM is not used, these extra terms appear to account for the change. To help you the laws of motion can be summarized as follows: Linear momentum is defined as mass times the velocity of the center of mass $$\vec{p} = m \vec{v}_{C}$$ Angular momentum at the center of mass is defined as rotational inertia at the center of mass times angular velocity $$\vec{L}_C = I_C \vec{\omega}$$ The net forces acting on a body equal the time derivative of linear momentum $$ \sum \vec{F} = \frac{{\rm d}}{{\rm d}t} \vec{p} = m \vec{a}_C$$ The net torques acting on a rigid body about the center of mass equal the time derivative of angular momentum at the center of mass $$\sum \vec{\tau}_C = \frac{{\rm d}}{{\rm d}t} \vec{L}_C = I_C \vec{\alpha} + \vec{\omega} \times I_C \vec{\omega}$$ To transfer these quantities to a different location A with $\vec{r}=\vec{r}_C -\vec{r}_A$ use the following rules $$\begin{aligned} \vec{v}_A & = \vec{v}_C + \vec{r} \times \vec{\omega} \\ \vec{a}_A & = \vec{a}_C + \vec{r} \times \vec{\alpha} + \vec{\omega} \times \left( \vec{r} \times \vec{\omega} \right) \\ \vec{L}_A & = \vec{L}_C + \vec{r} \times \vec{p} \\ \sum \vec{\tau}_A & = \sum \vec{\tau}_C + \vec{r} \times \sum \vec{F} \\ \end{aligned}$$ whereas forces, linear momenta, angular velocity and angular acceleration are shared with the entire rigid body and thus do not change from point to point. To the above you can add the vector form of the parallel axis theorem with $$ I_A = I_C - m [\vec{r}\times] [\vec{r}\times]$$ where $[\vec{r}\times]$ is the 3×3 skew symmetric matrix for the cross product operator $\begin{pmatrix}x\\y\\z\end{pmatrix}\times = \begin{vmatrix}0&-z&y\\z&0&-x\\-y&x&0\end{vmatrix}$ This comes out of the momentum transformation from C to A, but it is not the complete picture. To see what happens you have to look at the following 6×6 spatial inertia matrix: $$\begin{aligned}\vec{p} & =m\vec{v}_{C}=m\left(\vec{v}_{A}-\vec{r}\times\vec{\omega}\right)\\ \vec{L}_{A} & =I_{C}\vec{\omega}+m\,\vec{r}\times\left(\vec{v}_{A}-\vec{r}\times\vec{\omega}\right)\\ \begin{pmatrix}\vec{p}\\ \vec{L}_{A} \end{pmatrix} & =\begin{vmatrix}m & -m\,\vec{r}\times\\ m\,\vec{r}\times & I_{C}-m\,\vec{r}\times\,\vec{r}\times \end{vmatrix}\begin{pmatrix}\vec{v}_{A}\\ \vec{\omega} \end{pmatrix} \end{aligned}$$
{ "domain": "physics.stackexchange", "id": 30047, "tags": "angular-momentum, reference-frames, moment-of-inertia, rigid-body-dynamics" }
ROS Answers SE migration: AttributeError
Question: hi i am trying to use the split command so that i can split the voice input but getting an error " AttributeError: 'NoneType' object has no attribute 'split' " code snippet is def talkback(self, msg): command = self.get_command(msg.data) # Print the recognized words on the screen rospy.loginfo("Command: " + msg.data) #rospy.loginfo(msg.data) #some_str = command #some_wrd = 'time' if 'time' in command.split(): msg.data = strftime("%H:%M:%S ") self.soundhandle.say(msg.data, self.voice) elif 'name' in command.split(): self.soundhandle.say("my name is atom", self.voice) else: return Originally posted by karan4515 on ROS Answers with karma: 73 on 2012-11-23 Post score: 0 Answer: The variable command is probably empty, i.e. set to None. Originally posted by Lorenz with karma: 22731 on 2012-11-23 This answer was ACCEPTED on the original site Post score: 1 Original comments Comment by karan4515 on 2012-11-23: hey thanks for the help. i have changed the code a bit and now it work fine for time but for name it don't any help
{ "domain": "robotics.stackexchange", "id": 11866, "tags": "python" }
Memory issues with Find Strings Problem on InterviewStreet
Question: Here is the code I wrote for the problem at http://www.interviewstreet.com/recruit/challenges/solve/view/4e1491425cf10/4efa210eb70ac where we need to to print the substring at a particular index from the lexicographicaly-sorted union of sets of substrings of the given set of strings... import itertools N = int(raw_input()) S = set() for n in xrange(N): W = raw_input() L = len(W) for l in xrange(1,L+1): S=S.union(set(itertools.combinations(W, l))) print set(itertools.combinations(W, l)) print S M = int(raw_input()) S = sorted(list(S)) print S for m in xrange(M): Q = int(raw_input()) try: print "".join(S[Q-1]) except: print "INVALID" but it gives me a Memory Error meaning that my code takes up more than 256Mb during execution. I think the culprit is S=S.union(set(itertools.combinations(W, l))), but can't really think of a more efficient method for harvesting a unique set of substrings from the given set of strings... Can you suggest an optimal alternative? Answer: To successfully pass all test cases you need to implement something more sophisticated like suffix tree. That will allow you to solve this task in O(n) time using O(n) space.
{ "domain": "codereview.stackexchange", "id": 1171, "tags": "python, optimization, strings, memory-management" }
Is the Keppe Motor "real"?
Question: Its makers say that it's a highly efficient motor because it resonates with (what they call) "Essential Energy", which is free energy that is everywhere in space. (I think that’s just a different name for Dark Energy which somehow they are managing to disturb with the coils of the motor, and when it disturbs back, a bit of power is generated in the coil). I’ve listened to a radio interview of the makers, and they sad that a small motor powered by a 9v battery ran for about 2 hours with enough torque that they couldn’t stop it with their own hands. Is that what is really happening? Is it revolutionary? Or just bull… just a motor that consumes less energy since its coils are turned off half of the time? Also, strange things happen on the proximities of a running motor (a similar motor will start running even though it has no power, but it will run slower than the first one). Caused by the same thing that wireless cell phone chargers use to work? Answer: A total lack of anything in the peer review literature is a warning sign. A website that explains the operating principle of the motor as arising from disinverted Aristotlean metaphysics is something else entirely.
{ "domain": "physics.stackexchange", "id": 23955, "tags": "electromagnetism, dark-energy" }
importing csv data in python
Question: I have a csv file with around 130 columns and 6000 rows what is the best way to import them into python, so that I can later use them in a classification algorithm(columns are the labels and rows are individual samples) Answer: Use pandas library: import pandas as pd pd.read_csv('foo.csv') Pandas identify the headers automatically and is a great tool for data wrangling. 10 Minutes intro to pandas
{ "domain": "datascience.stackexchange", "id": 1114, "tags": "machine-learning, python, dataset, csv" }
Dynarray implementation with iterator
Question: So here is an implementation of a dynarray. Many people might not know about it, so here is a reference. Note that I am not trying to write a 100% standard conforming implementation. Also, this is for a library, so resist the urge to scold me on using a leading underscore for two of my variables. #include <cstddef> #include <iterator> #include <stdexcept> #include <initializer_list> template<typename T> class dynarray { public: //TYPE ALIASES using value_type = T; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using reference = T&; using const_reference = const T&; using pointer = T*; using const_pointer = const T*; private: //ITERATOR template<typename U> class dynarray_iter : public std::iterator<std::random_access_iterator_tag, U> { private: U* pos = nullptr; public: constexpr explicit dynarray_iter(U* position) : pos(position) {} constexpr dynarray_iter() = default; constexpr dynarray_iter(const dynarray_iter&) = default; dynarray_iter& operator=(const dynarray_iter&) = default; //INCREMENT/DECREMENT OPERATORS dynarray_iter& operator++() { ++pos; return *this; } dynarray_iter& operator--() { --pos; return *this; } dynarray_iter operator++(int) { dynarray_iter temp(*this); operator++(); return temp; } dynarray_iter operator--(int) { dynarray_iter temp(*this); operator--(); return temp; } //ARITHMETIC OPERATORS dynarray_iter operator+(difference_type off) const { return dynarray_iter(pos + off); } dynarray_iter operator-(difference_type off) const { return dynarray_iter(pos - off); } dynarray_iter& operator+=(difference_type off) { pos += off; return *this; } dynarray_iter& operator-=(difference_type off) { pos -= off; return *this; } difference_type operator-(const dynarray_iter& rhs) const { return pos - rhs.pos; } friend dynarray_iter operator+(difference_type off, const dynarray_iter& it) { return dynarray_iter(it + off); } U& operator*() { return *pos; } U* operator->() { return pos; } U& operator[](difference_type n) const { return pos[n]; } operator dynarray_iter<const T>() { return dynarray_iter<const T>(pos); } //COMPARISON OPERATORS constexpr bool operator==(const dynarray_iter& rhs) const noexcept { return pos == rhs.pos; } constexpr bool operator!=(const dynarray_iter& rhs) const noexcept { return pos != rhs.pos; } constexpr bool operator>(const dynarray_iter& rhs) const noexcept { return pos > rhs.pos; } constexpr bool operator<(const dynarray_iter& rhs) const noexcept { return pos < rhs.pos; } constexpr bool operator>=(const dynarray_iter& rhs) const noexcept { return pos >= rhs.pos; } constexpr bool operator<=(const dynarray_iter& rhs) const noexcept { return pos <= rhs.pos; } }; public: using iterator = dynarray_iter<T>; using const_iterator = dynarray_iter<const T>; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; private: T* _data = nullptr; std::size_t _size = 0; public: //CONSTRUCTORS template<typename InputIt> dynarray(InputIt first, InputIt last) { _data = new T[std::distance(first, last)]; std::size_t i = 0; for (; first != last; ++first, ++i) { _data[i] = *first; } _size = ++i; } dynarray(std::size_t count, const T& fill_val = 0) { _data = new T[count]; for (std::size_t i = 0; i < count; ++i) { _data[i] = fill_val; } _size = count; } dynarray(std::initializer_list<T> ilist) : dynarray(ilist.begin(), ilist.end()) {} //COPY/MOVE CONSTRUCTORS AND ASSIGNMENT dynarray(const dynarray& rhs) { _data = new T[rhs.size()]; for (std::size_t i = 0; i < _size; ++i) { _data[i] = rhs._data[i]; } _size = rhs.size(); } dynarray(dynarray&& rhs) noexcept { swap(rhs); } dynarray& operator=(const dynarray& rhs) { dynarray temp(rhs.begin(), rhs.end()); swap(temp); return *this; } dynarray& operator=(dynarray&& rhs) noexcept { //clear() swap(rhs); return *this; } ~dynarray() { delete[] _data; } //ACCESS FUNCTIONS T& front() { return _data[0]; } T& back() { return _data[_size - 1]; } const T& front() const { return _data[0]; } const T& back() const { return _data[_size - 1]; } T& operator[](std::size_t i) noexcept { return _data[i]; } const T& operator[](std::size_t i) const noexcept { return _data[i]; } T& at(std::size_t i) { if (!(i < _size)) { throw std::out_of_range("Index out of bounds!"); } return _data[i]; } const T& at(std::size_t i) const { if (!(i < _size)) { throw std::out_of_range("Index out of bounds!"); } return _data[i]; } T* data() noexcept { return _data; } const T* data() const noexcept { return _data; } //CAPACITY FUNCTIONS std::size_t size() const noexcept { return _size; } bool empty() const noexcept { return _size; } //ITERATORS iterator begin() noexcept { return iterator(_data); } iterator end() noexcept { return iterator(_data + _size); } const_iterator begin() const noexcept { return const_iterator(_data); } const_iterator end() const noexcept { return const_iterator(_data + _size); } const_iterator cbegin() const noexcept { return const_iterator(_data); } const_iterator cend() const noexcept { return const_iterator(_data + _size); } //REVERSE ITERATORS reverse_iterator rbegin() noexcept { return reverse_iterator(end()); } reverse_iterator rend() noexcept { return reverse_iterator(begin()); } const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator rend() const noexcept { return const_reverse_iterator(begin()); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(cend()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(cbegin()); } //OTHER FUNCTIONS AND ALGORITHMS void swap(dynarray& rhs) noexcept { using std::swap; swap(_data, rhs._data); swap(_size, rhs._size); } //FILL void fill(const T& val) { for (size_t i = 0; i < _size; ++i) { _data[i] = val; } } }; Answer: Include the appropriate headers You need to include <algorithm> if you're going to be using std::swap. Now that we have that header included, we can use it to reduce the size of some of the functions you've implemented. Use the standard when you can Many of your functions can be simplified now that we've included <algorithm>. For example, your fill function. void fill(const T& val) { std::fill(_data, _data + _size, val); } I would also remove that unnecessary //FILL comment you have as it is clear from the function name what you're doing. Your "fill constructor" can also be simplified: dynarray(std::size_t count, const T& fill_val) { _data = new T[count]; fill(fill_val); _size = count; } I also removed the default-value from the constructor as I think that if we're using a fill constructor, we should be providing it with a value to fill it with. Your "iterator constructor" can be simplified to: template<typename InputIt> dynarray(InputIt first, InputIt last) { _size = std::distance(first, last); _data = new T[_size]; std::copy(first, last, _data_); } Copy constructor: dynarray(const dynarray& rhs) { _data = new T[rhs.size()]; std::copy(rhs.begin(), rhs.end(), _data); _size = rhs.size(); } Wrong interface According to the link you provided, a dynarray is: neither copy-, nor move-assignable Therefore, you should be delete-ing your entire copy, move, and assignment operator functions. Technically, your implementation isn't correct but you've addressed that in your post. Memory management As it stands, your class leaks memory each time it is copied. In your copy c-tor, you never delete the memory you're holding on to before allocating a new piece. I would look into using some smart pointers to avoid having to worry about this issue(std::unique_ptr). If you do switch to a smart pointer allocator, then you don't even need to provide a destructor as cleanup is done for you by the smart pointer. Example: // assume _data is of type std::unique_ptr<T[]> dynarray(std::size_t count, const T& fill_val) { _data = std::make_unique<T[]>(count); fill(fill_val); _size = count; } Then in your copy c-tor, you can do this: dynarray(const dynarray& rhs) { _data = std::make_unique<T[]>(rhs.size()); // no leak std::copy(rhs.begin(), rhs.end(), _data.get()); _size = rhs.size(); } And your swap function can be: void swap(dynarray& rhs) noexcept { _data.swap(rhs._data); std::swap(_size, rhs._size); } You'll have to adjust the rest of your interface to take into account your new unique_ptr implementation but your implementation is now leak-free. You can simply this logic: T& at(std::size_t i) { if (!(i < _size)) { throw std::out_of_range("Index out of bounds!"); } return _data[i]; } to: T& at(std::size_t i) { if (i >= _size) { throw std::out_of_range("Index out of bounds!"); } return _data[i]; } For this function signature: std::size_t size() const noexcept { return _size; } you have size_type defined as std::size_t. Use it. size_type size() const noexcept { return _size; }
{ "domain": "codereview.stackexchange", "id": 17806, "tags": "c++, c++11, array" }
An accelerating and shrinking train in special relativity
Question: Suppose when a train is at rest, it has a length of $L$. Let the position of the back of the train at any time be $A$, and let the position of the front of the train at any time be $B$. Now assume a stationary observer on the Earth, O, observes point $A$ to be accelerating at a constant rate, $k$. Now as the train accelerates, O will observe the train to continually shrink, thanks to length contraction. Now since $A$ is measured to accelerate at a constant rate, the position of $B$ will depend on A's acceleration, and the rate of shrinkage. So the question is, calculate the acceleration of point $B$, as measured by O, given the acceleration of point $A$, and the length of the train, $L$. Answer: Suppose when a train is at rest, it has a length of $L$. Let the position of the back of the train at any time be $A$, and let the position of the front of the train at any time be $B$. In other words, by definition, $B$ and $A$ initially find equal ping durations between each other; $T_{ABA} == T_{BAB} := T$, where $L := \frac{c}{2} T$. Now assume [...] point $A$ to be accelerating at a constant rate, $k$. The prescription of "constant acceleration" is conveniently modelled as "constant proper acceleration" corresponding to hyperbolic motion against participants (such as "O") who were initially at rest wrt. $B$ and $A$ and each other (and who remain at rest to each other, as a inertial frame, allowing them to measure, among each other, the relevant distances and durations): $x_A[ t_O ] - x_A[ t_{O\text{start}} ] := \frac{c^2}{k} \left( \sqrt{ \left(\frac{k}{c} t_O\right)^2 + 1 } - 1 \right)$, where the relation between the duration $t$ of members of the inertial frame (incl. participant "O"), from starting $A$ until the passage of $A$ at some particular member of the inertial frame, and the correponding duration $\tau_A$ of $A$, from being sent off until passing the particular member of the inertial frame as $\frac{k}{c} t_O = \text{Sinh}[ \frac{k}{c} \tau_A ]$; and therefore $x_A[ t_O ] - x_A[ t_{O\text{start}} ] := \frac{c^2}{k} \left( \text{Cosh}[ \frac{k}{c} \tau_A ] - 1 \right)$. [...] calculate the acceleration of point $B$, as measured by O, given the acceleration of point $A$, and the length of the train, $L$. The prescription of the length of the train being and remaining "given" is sensibly modelled as the ping duration remaining constant; at least for pings of $A$ to $B$ and echoed back to $A$, (if not the other way around as well); i.e. $\tau_{A\text{echo reception}} := \tau_{A\text{signal statement}} + T$. The exchange of pings is considered exchange of light signals; therefore for the corresponding distances and durations determined by the members of the inertial frame holds: $c := \frac{(x_B[ t_{O\text{reflection}} ] - x_A[ t_{O\text{signal}} ]) + (x_B[ t_{O\text{reflection}} ] - x_A[ t_{O\text{reception}} ])}{t_{O\text{reception}} - t_{O\text{signal}}}$, i.e. $\text{Sinh}[ \frac{k}{c} (\tau_{A\text{sign}} + T) ] =$ $2 \frac{k}{c^2} \left(x_B[ t_{O\text{refl}} ] - x_A[ t_{O\text{start}} ]\right) - \text{Cosh}[ \frac{k}{c} \tau_{A\text{sign}} ] - \text{Cosh}[ \frac{k}{c} (\tau_{A\text{sign}} + T ) ] + 2$. Also: $c := \frac{(x_B[ t_{O\text{refl}} ] - x_A[ t_{O\text{sign}} ])}{t_{O\text{refl}} - t_{O\text{sign}}}$, i.e. $\frac{k}{c} t_{O\text{refl}} - \text{Sinh}[ \frac{k}{c} \tau_{A\text{sign}} ] = \frac{k}{c^2} \left(x_B[ t_{O\text{refl}} ] - x_A[ t_{O\text{start}} ]\right) - \text{Cosh}[ \frac{k}{c} \tau_{A\text{sign}} ] + 1$. Solving for $x_B[ t_{O\text{refl}} ]$ (along with $\tau_{A\text{sign}}$) results in $x_B[ t_{O\text{refl}} ] - x_A[ t_{O\text{start}} ] = \frac{c^2}{k} \left( \sqrt{\left(\frac{k}{c} t_{O\text{refl}}\right)^2 + e^{(\frac{k}{c} T)} } - 1\right)$, i.e. $x_B[ t_{O\text{refl}} ] - x_A[ t_{O\text{start}} ] = \frac{c^2}{k} \left( \sqrt{\left(\frac{k}{c} t_{O\text{refl}}\right)^2 + e^{(2 \frac{k}{c^2} L)} } - 1\right)$. This corresponds to hyperbolic motion of $B$ with proper acceleration $k \, e^{(\frac{-k}{c^2} L)}$. However, this solution doesn't hold for arbitrarily small/early $t_{O\text{refl}}$, but only for its values corresponding to $\tau_{A\text{sign}} \ge 0$, i.e. for ping signals which $A$ had stated at or after having started to accelerate. This applies for $t_{O\text{refl}} \ge \frac{1}{2} \left( e^{(2 \frac{k}{c^2} L)} - 1\right)$. Determining even earlier motion of $B$ (corresponding to pings stated by $A$ before starting to accelerate and with echoes received by $A$ after the start) may be more complicated ... but at least numerically possible (and sensible). But it doesn't appear in turn that the ping duration of $B$ (from stating the signal to observing the echo from $A$) remains constant and equal to $T$. Now as the train accelerates, O will observe the train to continually shrink, thanks to length contraction. Well ... Using the above equations of hyperbolic motion, of $A$ corresponding to the setup prescription, and of $B$ obtained accordingly as solution for containt ping duration $T_{ABA} := T$, it is possible to express the distance between any pair of members of the inertial frame (with O) whose indications of having been passed by $A$ and by $B$, respectively, were simultaneous: $x_B[ t_{O\text{refl}} ] - x_A[ t_{O\text{refl}} ] = \frac{c^2}{k} \left( \sqrt{\left(\frac{k}{c} t_{O\text{refl}}\right)^2 + e^{(2 \frac{k}{c^2} L)} } - \sqrt{ \left(\frac{k}{c} t_{O\text{refl}}\right)^2 + 1 } \right)$. This quantity is always positive, but is monotonously falling as a function of $t_{O\text{refl}}$. In particular, for $e^{(2 \frac{k}{c^2} L)} - 1 \ll 1$, $e^{(2 \frac{k}{c^2} L)} \lessapprox 1 + 2 \frac{k}{c^2} L$: $x_B[ t_{O\text{refl}} ] - x_A[ t_{O\text{refl}} ] \approx \frac{\frac{k}{c^2} L}{\sqrt{ \left(\frac{k}{c} t_{O\text{refl}}\right)^2 + \, 1 }} := \frac{k}{c^2} \frac{L}{\gamma[ t_{O\text{refl}} ]}$. Of course, this relation holds because the train does not itself shrink, but maintains the "given length" $L$ at least as far as the ping duration $T_{ABA}$ remains constant.
{ "domain": "physics.stackexchange", "id": 7552, "tags": "special-relativity" }