text:
0
Research Papers: Flows in Complex Systems

# Hydrodynamic Characterization of a Nozzle Check Valve by Numerical Simulation

[+] Author and Article Information
Stefano Sibilla1

Dipartimento di Ingegneria Idraulica e Ambientale, Università di Pavia, via Ferrata 1, 27100 Pavia, Italystefano.sibilla@unipv.it

Mario Gallati

Dipartimento di Ingegneria Idraulica e Ambientale, Università di Pavia, via Ferrata 1, 27100 Pavia, Italy

1

Corresponding author.

J. Fluids Eng 130(12), 121101 (Oct 23, 2008) (12 pages) doi:10.1115/1.3001065 History: Received July 28, 2006; Revised March 14, 2008; Published October 23, 2008

## Abstract

The ability to obtain correct estimates of the hydraulic characteristics of a nozzle check valve by finite-volume numerical simulation is discussed. The evaluation of the numerical results is performed by comparison of the computed pressure drops inside the valve with experimental measurements obtained on an industrial check valve. It is shown that, even with high mesh refinement, the obtained result is highly dependent on the choice of the turbulence model. The renormalization group theory (RNG) $k-ε$ model proves to be the more accurate to describe the flow inside the valve, which is characterized by repeated flow decelerations and accelerations and by boundary layer development under adverse pressure gradient. Pressure-drop and flow coefficients computed by adopting the RNG model agree well with the experimental values at different positions of the plug. The opening transient of the valve is also analyzed by an unsteady flow simulation where the motion of the plug is taken into account. The characteristic curve of the valve obtained in steady flow conditions is finally compared with the transient opening characteristic, highlighting a temporary increase in the pressure drop, which occurs because of a large unsteady separation region downstream of the plug.

<>

## Figures

Figure 1

Experimental setup: (a) nozzle check valve geometry; (b) sketch of the test section with upstream and downstream pressure probes P1 and P2

Figure 2

Computational mesh, full valve opening: coarse mesh (a) and fine mesh (b)

Figure 3

Effect of the inflow boundary condition: axial velocity profiles at the inlet (left) and in the throat section upstream of the plug (right). Uniform flow (solid), 1/7 power profile (dashed); logarithmic profile (dash-dot).

Figure 4

Dependency of the valve pressure-drop coefficient on the turbulence model and on the mesh refinement

Figure 5

Turbulent kinetic energy field. Simulation with (a) standard and (b) RNG k-ε models. Isolines range (a) from 0 to 0.36V2, step 0.03V2; (b) from 0 to 0.12V2, step 0.01V2.

Figure 6

Pressure profile along the external valve wall: comparison between different k-ε turbulence models

Figure 7

Axial velocity profiles of three sections shown by dashed lines in Fig. 5: simulation with different k-ε turbulence models

Figure 8

Turbulent kinetic energy profiles of three sections shown by dashed lines in Fig. 5: simulation with Chen’s and RNG k-ε turbulence models

Figure 9

Flow field in the fully open valve configuration. (a) Pressure: isolines range from −5ρV02 to 2ρV02, step (1/2)ρV02. (b) Velocity magnitude: isolines range from 0 to 3V0, step 0.25V0.

Figure 10

Velocity vector field in the wake region of the fully open check valve. The vector length is uniform to highlight flow direction and recirculation regions.

Figure 11

Check valve characteristic curves: (a) pressure-drop coefficient; (b) flow coefficient. The symbols indicate results corresponding to the plug positions analyzed by numerical simulation; the lines indicate experimental results obtained by increasing the flow rate from zero to the maximum value (solid) and then decreasing again to zero (dashed).

Figure 12

Pressure field in steady flow at different plug positions. (a) 50% travel; (b) 10% travel; detail of the plug region in the circle. Isolines range from −5ρV02 to 2ρV02, step (1/2)ρV02.

Figure 13

Velocity magnitude field in steady flow at different plug positions. (a) 50% travel; (b) 10% travel. Isolines range from 0 to 3V0, step 0.25V0.

Figure 14

Velocity vector field in steady flow at different plug positions. (a) 50% travel; (b) 10% travel. The vector length is uniform to highlight flow direction and recirculation regions.

Figure 15

Computational mesh for ALE simulation: detail at t=2.12R/V0 (50% open, i.e., after 200 time steps)

Figure 16

Time history for plug travel and flow rate in the opening transient simulation

Figure 17

Velocity magnitude fields during plug opening. (a) t=0.25to, (b) t=0.5to, (c) t=0.75to, (d) t=to, (e) t=1.15to, and (f) t=1.4to. Isolines range from 0 to 3V0, step 0.25V0.

Figure 18

Check valve characteristic curves during plug opening: (a) pressure-drop coefficient; (b) flow coefficient. Transient simulation (symbols) compared with steady-state simulations (dashed) and with experimental results obtained by increasing the flow rate from zero to the maximum value (solid).

## Errata

Some tools below are only available to our subscribers or users with an online account.

### Related Content

Customize your page view by dragging and repositioning the boxes below.

Related Journal Articles
Related Proceedings Articles
Related eBook Content
Topic Collections

• TELEPHONE: 1-800-843-2763 (Toll-free in the USA)
• EMAIL: asmedigitalcollection@asme.org


text:
# [ASP] Dealing w/ MSSQL bit datatype

This topic is 4733 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I have a field in one of the databases I'm working with in the bit datatype. So either the field is a 0 or 1. Now I have to read these values to an ASP page to display. It works fine whenever I read the bit value of 1, but whenever I come across a bit value of 0, I get a MS SQL error:
error '80020009'
Exception occurred.

/marketing/product/report.asp, line 129
Line 129 is part of this 'if' statement:
        If rs2("LicenseRequired") <> true then '<---Line 129
Response.Write "False"
Else
End If
I'm not sure how to go about checking a bit value, any help? Thanks!

##### Share on other sites
Nevermind, figured the issue out.

do tell.

##### Share on other sites
Turns out there were missing records, these people can't manage their databases for crap. =/

• 9
• 13
• 41
• 15
• 14

format: plain


text:
# Applying the Sommerfeld model

1. Oct 20, 2014

### CAF123

1. The problem statement, all variables and given/known data
a) From the graph attached (see also Philips book) deduce the Fermi energy for copper using the Sommerfeld model
b) Estimate $v_s$ in copper, where $v_s$ is the speed of the low temperature phonon vibration.

2. Relevant equations
Sommerfeld model, $c_v = \pi^2/2 (k_B T/\epsilon_f) k_B$ per electron in sample.

3. The attempt at a solution
So I rewrite the equation above like $$c_v/T = \pi^2/2 (k_B /\epsilon_f)k_B.$$ From the sketch $C/T = A + BT^2$ so at $T=0, C/T = A$ in the given units. Sub this in gives $$\epsilon_f = \frac{\pi^2}{2} \left(\frac{(k_B)^2 (m^2 kg s^{-2}K^{-1})^2}{A \, mJ \, mol^{-1} deg^{-2})}\right) = \frac{\pi^2}{2} \left(\frac{(k_B)^2 J \text{mol}}{A}\right)$$ by cancelling out the units. Then there are avagadro number of atoms in a mole and copper has one conduction electron per atom, so the Fermi energy I get is $\epsilon_f \times 6.02 \times 10^23 \approx 3.75 eV$. The value I found from another source is about 7eV so the numbers are comparable but I was wondering if my method was right?

Thanks

#### Attached Files:

• ###### Graph1.jpg
File size:
24.2 KB
Views:
72
2. Oct 25, 2014


text:
# Tag Info

36

Here is my pitch to use LibraryLink, which is a really nice new technology in version 8. I am not going to pretend this is easy by any stretch of the imagination, because it involves a decent amount of knowledge of both Mathematica and C compilers. In this particular case I am using Visual Studio C++ Express plus the Microsoft Windows SDK 7.1. For the ...

35

There are two performance problems here. The first is relatively minor: MultinormalDistribution[μ, Σ] is evaluated in each slave kernel, returned to the master kernel, and sent back to the slave kernels as part of the RandomVariate call. In your example, this is a packed array of about 80KB in size: not large, yet not small either, and this behaviour may ...

32

On Windows, C/C++ functions that have been compiled into DLLs can be accessed reasonably easily using NETLink. Let's say we have the following C++ DLL definition: #include "stdafx.h" BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID reserved) { return TRUE; } extern "C" __declspec(dllexport) void helloMma(double a, double b, int n, double ...

28

MathLink can be used to establish communication between two kernels on different machines using TCP/IP. A basic example that illustrates the technique can be found in the Mathematica documentation. The basic sequence of events is like this: The server creates an endpoint using LinkCreate. The client connects using LinkConnect. When one side wants to send ...

24

IronPython requires .NET 4.0 to run. As of V8, Mathematica launches .NET 2.x by default. See this question for details about how to use .NET 4.0. Having done that, we need to load the IronPython assembly into the .NET framework: Needs["NETLink"] InstallNET[]; $pythonDll = "C:\\Program Files (x86)\\IronPython 2.7.1\\IronPython.dll"; ... 24 Presuming that your c++ code is already written, then I don't know how the code generation feature would be helpful. That said, in order of simplicity, I would have Get, ReadList, Import, and both LibraryLink and MathLink. Get and ReadList are by far the simplest. Provided that your c++ program outputs to stdout (std::cout), then it is simply val = ... 21 I suggest to use MathLink, which you can automate using the CCompilerDriver. This is a safe alternative, since you won't crash the kernel if your code crashes. Once tested, this should not be hard to convert to library link. As an explicit example, consider a function which receives a list of integers and squares it. First, here is a function to create the ... 18 To access the errors, you need to invoke the Front End directly from the kernel. In effect, you end up telling the kernel to tell the FE to tell the kernel to do something, so that the FE can report any errors it finds. The method I use is ClearAll[getFrontEndErrors]; SetAttributes[getFrontEndErrors, HoldAllComplete]; getFrontEndErrors[expr_] := ... 17 Being the fan of Mathematica<->CLR interop that I am, your question has inspired me to try to get IronPython fully working with Mathematica for the last couple of days. I haven't yet had total luck. Part of my problem is that I don't have a Windows Mathematica license, so I can't fully double-check my work. While I'm trying to hunt down Mathematica for ... 16 Note that ListContourPlot3D takes the coordinates to be the position indices by default. If you want to keep the coordinates used in generating the data, then you have to include it. data = Flatten[ Table[{x, y, z, x^2 + y^2 + z^2 + RandomReal[0.1]}, {x, -2, 2, 0.2}, {y, -2, 2, 0.2}, {z, -2, 2, 0.2}], 2]; plot = ListContourPlot3D[data, Contours ... 16 Have a look at this; http://reference.wolfram.com/mathematica/guide/MathLinkCLanguageFunctions.html I haven't used it in C/C++ but it works fine in C# and Java. Basically you create a connection to a Mathematica kernel and then pass it native data types. Works nicely. Here is some sample code in Java that I used when I first did this; import ... 16 Taking user5601's suggestion to do a little demo, I quickly whipped this up as an example of ProcessLink being used to do non-trivial communication between Mathematica and an external program, but with much less ceremony than using ProcessLink or MathLink. Let's take this little Go program: package main import "net/http" import "bufio" import "os" import ... 15 There are a few problems with your code. If you fix those up, as I did, your program will run fine. First off, the reason you see "no source available" when you pause the program is probably that when you break, the program is down inside a MathLink function, and so it is complaining that it doesn't have access to the MathLink library source code. To debug ... 15 Under Linux the WSTP shared libraries that ship with Mathematica 10.0.1 for both 64 and 32 bit (libWSTP64i4.so and libWSTP32i4.so) appear to be broken. Link with the static versions libWSTP64i4.a or libWSTP32i4.a instead. The Windows and OS X versions are OK. 14 See this link. I have found a solution. Works fine to me. Steps: 1-Create a script named runMath with the content: #!/usr/local/bin/MathematicaScript -script value=ToExpression[$ScriptCommandLine[[2]]]; (*The next line prints the script name.*) (*Print[$ScriptCommandLine[[1]]];*) Print[value]; 2-I gave execution privilege to the file. sudo chmod +x ... 14 To call Mathematica from Clojure, you will want to use Clojure's Java interop to access the Wolfram JLink classes to script Mathematica access. Start by launching Clojure with a classpath that includes the JLink.jar, for example with this batch file: @echo off set MATHEMATICA=C:/M/9.0 set JLINKJAR=%MATHEMATICA%/SystemFiles/Links/JLink/JLink.jar java -cp ... 14 To use .NET/Link from a Mono program, you need to make sure that the system can find the MathLink shared library. This generally means adding the appropriate path to an environment variable that the system uses for library lookups. You can do this is in the standard way that is appropriate for your OS/shell program, either in a shell config file or on the ... 14 You will find a complete, step by step description of how to write such a program here. Here's a small test program that adds 42 and 137, written by following the tutorial closely: /* mlcall.c */ #include <mathlink.h> #include <stdio.h> int main(int argc, char *argv[]) { MLENV env; MLINK link; int errno; int packet; env = ... 13 Here is a more general approach. It is based on the 2D method from here. It assumes the polyhedron is not self-intersecting but imposes no requirement of convexity or even connectedness, other than that it be closed and bounded. Strictly speaking, I think this will work for an unbounded polyhedron provided it contains no vertical ray. For ease of exposition ... 12 Yes, it is, but it's cumbersome (at least as of Mathematica 8). The hardest part is that you have to manually do a lot of the juggling required to work with .NET generics and extension methods. For example, let's translate a straightforward solution to Project Euler's Problem #1 ("Add all the natural numbers below one thousand that are multiples of 3 or ... 12 Setting up MathLink connections between kernels acting as peers (as opposed to in a master-slave arrangement) is sparsely documented, and the critical function you need to make this work, i.e. LinkActivate, is undocumented altogether (although, if you clear its ReadProtected attribute, you will see that it is merely a synonym for LinkConnect, which itself is ... 11 Here is a fast method that will "often" work. Roughly, it requires that the convex polygon have no sharp angles between faces. Preprocessing goes as follows. Create triangles from the polygons. So a 5-gon with vertices {a,b,c,d,e} would become the set of triangles {{a,b,c},{a,c,d},{a,d,e}}. For each vertex we average it's star (set of points connected by ... 10 If you want to use port forwarding, you'll need to know that for every MathLink connection, two different ports are used. The full syntax for TCPIP link names looks like this: LinkCreate["8000@1.2.3.4,8001@1.2.3.4", LinkProtocol -> "TCPIP"] 8000 and 8001 are the port numbers while 1.2.3.4 is your IP address. You can pass only a single port number to ... 10 You may want to look at this presentation: Integrating C and Mathematica. In the past, I have found using .NET/Link to be the easiest. You can call C DLL's very easily on Windows, without the need for templates as in MathLink. 10 Let me present an alternative approach. The whole commandline work and link naming and connecting can be simplified. What we need is the location of the LinkSnooper program and the location of your MathLink program and then you can set up everything in exactly one call to Install from Mathematica. I have tried to make the following, where I demonstrate it ... 9 Once again thanks to John Fultz we know a command that returns the complete list of these packets: MathLinkCallFrontEnd[FrontEndNeedCurrentFrontEndSymbolsPacket[]][[1, 1, 4]] Results from Mathematica 7: "" "Null" "CompoundExpression" "List" "Execute" "FrontEndExecute" "KernelExecute" "OpenParallelLinksPacket" "KernelStartupCompleted" ... 9 LibraryLink vs. MathLink The Wolfram Library Link is a way to run code which is placed in a so called shared or dynamic library directly by loading the library into a running MathKernel. One way to send and to receive data are, as you mentioned, the MArgument_* functions. But this is not the only way! As shown in the examples of the LibraryLink Tutorial ... 9 NaN (or Not-a-Number is used in floating point arithmetic to represent values that are undefined or unrepresentable, such as$0/0,\ \infty/\infty\$, etc. Mathematica typically returns Indeterminate for these, but several other languages return NaN. To work with NaNs, you must load the ComputerArithmetic package as <<ComputerArithmetic` prior to calling ...

9

The problem here is that the Gridlines specification error message is not a kernel error message (you'll note that it is not printed with the standard Func::tag format). Instead, this warning text is generated by the front end during the rendering of the graphic. The actual generation of the gridlines values is deferred to the moment when the graphics ...

Only top voted, non community-wiki answers of a minimum length are eligible


text:
July 14, 2020

### Option Greeks. Option hedging using Excel. (Gamma, Vega)

The option greeks are Delta, Gamma, Theta, Vegas and Rho. Learn how to use the options greeks to understand changes in option prices. Important Notice You're leaving Ally Invest. By choosing to continue, you will be taken to , a site operated by a third party. We are not responsible for the products, services, or information you may find or

### THE GREEKS BLACK AND SCHOLES (BS) FORMULA

2016/06/16 · Understanding the Delta on Binary Option is fairly simple. Basically, the risk can be viewed as the “Delta”. Below is an example of how the Delta can be identified using strike prices and risk on Nadex Binary Options. Understanding the Delta on Binary Options.

### Using Cumulative Delta to Identify OTM Binary Option

Binary options are a type of exotic option for which the payoff is determined by whether the final stock price is greater or less than the strike price . A binary call option pays out if , while a binary put option pays out for . In this Demonstration we set the payoff amount to be the strike price .

### Binary option delta formula excel - myotentoope’s diary

With the abundance of binary options trading software available for traders online, it is important to take some time to research a system before making an investment decision. Some systems are extremely highly rated, while others are iffy. Hedge Formula trading system was created by George Dalio, a self-proclaimed financial genius who made his original fortune

### Black-Scholes Option Model - Option Trading Tips

Relationship to vanilla options' Greeks. Since a binary call is a mathematical derivative of a vanilla call with respect to strike, the price of a binary call has the same shape as the delta of a vanilla call, and the delta of a binary call has the same shape as the gamma of a vanilla call. Black–Scholes in practice

### Delta Explained | The Options & Futures Guide

Delta of a call option Tags: options risk management valuation and pricing Description Formula for the calculation of a call option's delta. The delta of an option measures the amplitude of the change of its price in function of the change of the price of its underlying.

### Options on futures delta

Binary Option Theta Formula. Option delta Binary call option delta measures the change in the price of a binary call. BinariesThe delta value for a call option delta formula call option will lease with option to purchase agreement definition range from zero to one.. I've been unable to find a formula for it on Option which is a bit weird?

### Hedge Formula - 7 Binary Options

In fact, the Black–Scholes formula for the price of a vanilla call option (or put option) can be interpreted by decomposing a call option into an asset-or-nothing call option minus a cash-or-nothing call option, and similarly for a put – the binary options are easier to analyze, and correspond to the two terms in the Black–Scholes formula.

### Binary Option Delta Formula - jomdrop.co

2019/03/22 · A binary option is a financial product where the buyer receives a payout or loses their investment, based on if the option expires in the money.Binary options depend on the outcome of a …

### The Greeks — Vega

2019/06/25 · Asset-Or-Nothing Call Option: A derivative security for which there is no payoff unless the underlying asset's price exceeds the strike price. With an asset-or-nothing call option, the payoff is

### Greeks for Binary Options : Delta, Gamma, Rho, Vega Theta

Binary Option Delta Formula. Binary Option Demo Trading. Binary Option Exposed. Binary Option Formula. Binary Option Free Demo Account. Binary Option Hedging. Binary Option How It Works. Binary Option In The Money. Binary Option In Usa. Binary Option Jp. Binary Option Killer Review.

### Binary Call Option Delta Formula

Excel v3 delta managed option in the strike hedging calculator for exemple.regardless of the market, bollinger bands are indispensable in developing trading strategies.download my option pricing spreadsheet for calculating.and forex options youtube, delta formula top binary options system bus z malawi stock market binary option delta in the

### Binary option - Wikipedia

THE GREEKS BLACK AND SCHOLES (BS) FORMULA The equilibrium price of the call option (C; European on a non-dividend paying stock) is shown by Black and The delta of the asset position o⁄sets the delta of the option position. A position with a delta of zero is referred to as being delta neutral.

### Broker’s Edge Calculator | Binary Trading

The Black-Scholes formula for European call option is tested to be the solution of Black-Scholes equation. IV. The value of digital options and share digitals are calculated. The European call and put options are be replicated by digital options and share digitals, thus the prices of call and put options can be derived from the values of digitals.

### Airlines, Including Delta, to Add New Gender Options for

SOLVED] Delta Hedging an Option over Time. Short Strangle is a non-directional, premium selling, delta neutral option strategy that involves. Delta hedging, gamma scalping 74% of retail investor accounts lose money when trading CFDs with this provider.

### Black Scholes Option Calculator

2018/01/16 · Payoff of a binary option on the other hand, is just a fixed amount which is not affected by the difference between the exercise price and the price of the underlying asset. A binary option depends on the relationship between the exercise price and the price of the underlying asset only to determine whether the payoff will occur or not.

### Binary Options Greeks | Binary Trading

Introduction Video – How to Trade Binary Options. Since a binary call is a mathematical derivative of a vanilla with with respect option strike, the price of a option call has option same shape as the delta of a vanilla call, and with delta fraud a binary call has the same binary as the gamma of a vanilla call. Many binary option "brokers

### Options Calculator - Drexel University

2014/01/06 · The most-experienced binary options traders are very fond of the straddle strategy. This technique provides them the choice of both Call and Put options, which share the same expiration period. The call and put options simply indicate that price predicting is either for an increase, or decrease in of the assessment.


text:
トップページ > 談話会・セミナー等 > 分野別セミナー > A computer-assisted band-gap proof for 3D photo...

## 分野別セミナー

### A computer-assisted band-gap proof for 3D photonic crystals

2009-01-06 15:30～2009-01-06 17:00

Michael Plum (University of Karlsruhe)

for Maxwell's equations with periodic electric permittivity. By
Floquet-Bloch theory, the spectrum has band-gap structure, and
the bands are characterized by families of eigenvalue problems
on a periodicity cell, depending on a parameter $k$ varying in
the Brillouin zone $K$. We propose a computer-assisted method
for proving the presence of band-gaps: For $k$ in a finite grid
in $K$, we obtain eigenvalue enclosures by variational methods,
and then capture all $k \in K$ by a perturbation argument.


text:
Q

# (a) Estimate the speed with which electrons emitted from a heated emitter of an evacuated tube impinge on the collector maintained at a potential difference of 500 V with respect to the emitter. Ignore the small initial speeds of the electrons.

Q: 11.20  (a) Estimate the speed with which electrons emitted from a heated emitter of an evacuated tube impinge on the collector maintained at a potential difference of $\dpi{100} 500\hspace{1mm}V$ with respect to the emitter. Ignore the small initial speeds of the electrons. The specific charge of the electron, i.e., its  $e/m$  is given to be  $\dpi{100} 1.76\times 10^1^1\hspace{1mm}kg^-^1$

Views

The kinetic energy of an electron accelerated through Potential Difference V is K=eV where e the electronic charge.

Speed of the electrons after being accelerated through a potential difference of 500 V will be

$\\v=\sqrt{\frac{2K}{m_{e}}}\\ v=\sqrt{\frac{2eV}{m_{e}}}\\ v=\sqrt{2\times 1.76\times 10^{11}\times 500}\\ v=1.366\times 10^{7}ms^{-1}$        Specific charge is e/me=1.366$\times$1011C/kg

Exams
Articles
Questions


text:
In 1927 Royal V. Heath marketed a magic effect called “The Di-Ciphering Trick” based on a math trick developed by Ed Balducci (1906-1988); a New York City magician and civil engineer by day. Royal Vale Heath (1883-1960) was a New York City broker, American Magician and puzzle enthusiast. Tricks with serial numbers, Magic Squares and dice were his specialty.
Heath performed and wrote actively and wrote a popular book on mathematical recreations named Mathemagic: Magic, Puzzles and Games with Numbers. Heath was a rich stockbroker who carried himself as a pompous fool. He performed tedious mathematical tricks that put his audience to sleep. Heath is one of the reasons Martin Gardner had a career writing about recreational math. See Magical Mathematics: The Mathematical Ideas that Animate Great Magic Tricks by Graham, Ron; Diaconis, Persi for a story about Gardner and Heath along with some great mathemagic.

The “Di-Ciphering” trick consists of 5 dice cubes bearing a different 3 digit number on each face – 30 numbers in all. A spectator would roll the dice and the magician would quickly announce the sum of all the numbers.

Let’s look at the dice used for the trick:
5 unique set of 6 sided dice which have the following numbers on each of the sides. None of the numbers are repeated on a dice or any other dice.
1: [483, 285, 780, 186, 384, 681]
2: [642, 147, 840, 741, 543, 345]
3: [558, 855, 657, 459, 954, 756]
4: [168, 663, 960, 366, 564, 267]
5: [971, 377, 179, 872, 773, 278]

An example roll of the dice is:
186 147 459 168 179
with a sum of 1139.

The method used to quickly calculate the sum of the 5 die of 3 digit numbers is:
Add the last digit of all of the numbers -> 6 + 7 + 9 + 8 +9 = 39
39 is the last 2 digits of the sum.
To find the first two digits of the sum take 50 – 39 = 11.
Thus the sum is 1139.

This will work with any roll of the dice.
Since there are 5 dice with 6 possible numbers we have
$5^{6} = 7,776$
possible sums.

Why does this method work?
What is special about the numbers on the dice?

Let’s look at some of the 7,776 sums (a small sample) and look at the numbers on the dice as well to see if we can find any patterns.

 D1 D2 D3 D4 D5 Sum 483 642 558 168 971 2822 285 147 855 663 377 2327 780 840 657 960 179 3416 186 741 459 366 872 2624 384 543 954 564 773 3218 681 345 756 267 278 2327
 FIRST DIGIT Sum 4 6 5 1 9 25 2 1 8 6 3 20 7 8 6 9 1 31 1 7 4 3 8 23 3 5 9 5 7 29 6 3 7 2 2 20
 LAST DIGIT Sum 3 2 8 8 1 22 5 7 5 3 7 27 0 0 7 0 9 16 6 1 9 6 2 24 4 3 4 4 3 18 1 5 6 7 8 27
 FIRST + LAST Sum 7 8 13 9 10 47 7 8 13 9 10 47 7 8 13 9 10 47 7 8 13 9 10 47 7 8 13 9 10 47 7 8 13 9 10 47

Observations:

• Sum of middle digit of the numbers (one from each dice) always add to n0 – this needs to occur for the last two digits of sum of the numbers to be sum of last digits.
• Middle digit of:
D1 = 8, D2 = 4, D3 = 5, D4 = 6, D5 = 7
thus 8 + 4 + 5 + 6 + 7 = 30
• Therefore sum of last digits will be last two digits of the sum of numbers from each of the 5 dice.
• All combinations of sums of 5 dice need to have first 2 digits plus last 2 digits always add to 50.
• Sum of first and last digit for each dice:
D1 = 7, D2 = 8, D3 = 13, D4 = 9, D5 = 10
This sum is 47
• Sum of first digit plus 3 (since middle digits always add to 30) + sum of last digits for each combination of dice = 50.
• So we can determine sum of all the dice on the roll by adding last digits for the left 2 digits of the sum then subtract from 50 to get the leading two digits of the sum.
• Sum of digits of the total is always 14

We know there can be 7,776 possible totals when we roll the dice.
How many are unique. Below is the output of a program which generated all of the possible totals of the 5 dice, sorted and then duplicates removed. From this we see there are 35 unique totals.

 Unique Sums D1 D2 D3 D4 D5 Sum 186 147 459 168 179 1139 285 147 459 168 179 1238 285 147 558 168 179 1337 483 147 459 168 179 1436 483 147 558 168 179 1535 483 147 558 168 278 1634 483 147 558 168 377 1733 483 147 558 366 278 1832 483 642 459 168 179 1931 483 642 558 168 179 2030 483 642 558 168 278 2129 483 642 558 168 377 2228 483 642 558 366 278 2327 483 642 558 366 377 2426 483 642 558 663 179 2525 483 642 558 168 773 2624 483 642 558 168 872 2723 483 642 558 168 971 2822 483 642 558 960 278 2921 483 642 558 960 377 3020 483 642 558 663 773 3119 483 642 558 663 872 3218 483 642 558 663 971 3317 483 642 558 960 773 3416 483 642 558 960 872 3515 483 642 558 960 971 3614 483 642 855 960 773 3713 483 642 855 960 872 3812 483 642 855 960 971 3911 483 642 954 960 971 4010 483 840 855 960 971 4109 483 840 954 960 971 4208 780 642 954 960 971 4307 780 840 855 960 971 4406 780 840 954 960 971 4505

A different trick using these dice was given in the book Practical Mental Magic by Theodore Annemann.
The Trick:
Let someone shake and roll the 5 dice. You line them up in a row, and turning your back ask the person assisting to add up the figures and get the total. Then ask him how many figures are in the total. He replies that there are four, and you tell him to look at the first two and the last two. Now toss him a book (can be any book of your choosing including dictionary or phone book), and have him open it at the page represented by the higher of the two numbers. Then, taking the other number, he counts to that word on the page and remembers it. You take out a pocket notebook, jot something down on a page, tear it out, crumple it and hand it to another person. The word is now disclosed, and your written divination is found to be correct.

Preparation and Routine: The use of the dice make the test appear very fair. There is never a thought that in the moment of putting the dice in line, or in instructing the spectator what to do, you have learned the total by the short cut process possible with this trick. The opinion they have is that there can be hundreds of variations. If there is a question about the digits on the dice you can mention that they are used for some money game (without going into that part further) as an excuse for their being numbered with three digits to a side.

As further preparation for the trick we need to look at all of the unique somes in a slightly different manner. We are interested in the first two digits and last two digits of the sums as pairs with the highest of the pairs being first.
Below is the result of taking the unique sums, separating out the first 2 digits and last 2 digits, arrange sum as highest of pairs followed by the other set of digits. For example if the sum is 2426 since last 2 digits 26 are larger than the first two digits 24 we would rearrange and write the sum as 2624. Doing that for all of the 35 unique sums we end up with this list:

2525, 2624, 2723, 2822, 2921, 3020, 3119, 3218, 3317, 3416, 3515, 3614, 3713, 3812, 3911, 4010, 4109, 4208, 4307, 4406, 4505

On the inside cover of your notebook, you have the list of the 21 words—from the book you intend using—followed by the 21 possible totals. It’s an easy matter to steal a glance at the prepared list as you open your note book to jot down your written word.
For example for these 3 sums we look on the page the the nth word on the page and write in out our notebook before the performance:

 Page Word# Word 32 18 available 34 16 dog 39 11 teacher

Further investigations:

1. Can use your imagination to find other tricks using the unique properties of the dice.
2. Are there other number which will also work?

Python program to find all of the sums, unique sums and pairs for book trick:


text:
# Euclid 5

Calculate the length of remain sides of a right triangle ABC if a = 7 cm and height vc = 5 cm.

Result

b =  7.14 cm
c =  10 cm

#### Solution:

$c = c_1 +c_2 \ \\ c_1^2 = a^2 -v^2 \ \\ c_1 = \sqrt{ 7^2 - 5^2 } = 4.9 \ cm \ \\ v^2 = c_1 c_2 \ \\ c_2 = v^2/c_1 = 5^2 / 4.9 = 5.1 \ cm \ \\ \ \\ c = c_1 + c_2 = 10 \ \text{cm} \ \\ \ \\ c^2 = a^2+b^2 \ \\ b = \sqrt{ c^2 - a^2 } = 7.14 \ cm$

Try calculation via our triangle calculator.

Our examples were largely sent or created by pupils and students themselves. Therefore, we would be pleased if you could send us any errors you found, spelling mistakes, or rephasing the example. Thank you!

Leave us a comment of this math problem and its solution (i.e. if it is still somewhat unclear...):

Be the first to comment!

Tips to related online calculators
Pythagorean theorem is the base for the right triangle calculator.

## Next similar math problems:

1. Euclid2
In right triangle ABC with right angle at C is given side a=27 and height v=12. Calculate the perimeter of the triangle.
2. Euclidean distance
Calculate the Euclidean distance between shops A, B and C, where: A 45 0.05 B 60 0.05 C 52 0.09 Wherein the first figure is the weight in grams of bread and second figure is price in USD.
3. Triangle - is RT?
Triangle has a circumference of 90 cm. Side b is 1 cm longer than c, side c is 31 cm longer than side a. Calculate the length of sides and determine whether triangle is a right triangle.
4. Triangle IRT
In isosceles right triangle ABC with right angle at vertex C is coordinates: A (-1, 2); C (-5, -2) Calculate the length of segment AB.
5. Tetrahedron
Calculate height and volume of a regular tetrahedron whose edge has a length 18 cm.
6. Isosceles IV
In an isosceles triangle ABC is |AC| = |BC| = 13 and |AB| = 10. Calculate the radius of the inscribed (r) and described (R) circle.
7. ABS CN
Calculate the absolute value of complex number -15-29i.
8. Centre of mass
The vertices of triangle ABC are from the line p distances 3 cm, 4 cm and 8 cm. Calculate distance from the center of gravity of the triangle to line p.
9. Triangle ABC
In a triangle ABC with the side BC of length 2 cm The middle point of AB. Points L and M split AC side into three equal lines. KLM is isosceles triangle with a right angle at the point K. Determine the lengths of the sides AB, AC triangle ABC.
10. Spruce height
How tall was spruce that was cut at an altitude of 8m above the ground and the top landed at a distance of 15m from the heel of the tree?
11. Right 24
Right isosceles triangle has an altitude x drawn from the right angle to the hypotenuse dividing it into 2 unequal segments. The length of one segment is 5 cm. What is the area of the triangle? Thank you.


text:
# Nonsingular derivative

What does a "nonsingular derivative" mean. It comes in the following context: "If f: R^2 --> R^2 is a function with a nonsingular derivative everywhere, is f bijective?"

What does the derivative of a function $f:\mathbb{R}^n \rightarrow \mathbb{R}^m$ look like? Do you know what it means for a matrix to be nonsingular (hint: see morphism's post!)?


text:
+0

# chem 12

0
355
1

If the rate of reaction is 5 x 10-9 mol/s, how many grams of magnesium will be used up in 5 min?

Guest Apr 14, 2017
#1
+7519
0

If the rate of reaction is 5 x 10-9 mol/s, how many grams of magnesium will be used up in 5 min?

$$\large 5\times10^{-9}\frac{mol}{s}\times\frac{24.305g\ Mg}{mol}\times 5min \times\frac{60s}{min}=3.64575\cdot 10^{-5}g\ Mg$$

!

asinus  Apr 14, 2017


text:
## Introduction

This post is a thorough walk-through of how to create a “hello world” application using x86 assembly language in the Windows environment. I’ll walk you through how to compile and run a bare minimum, hello-world-like, Windows assembly language program.

We might start by asking…why? Why would anyone want to do this? Why not program in C, C++, C#, Java, etc?

I can only think of one reason: as a learning experience to better understand what’s going on under the hood. (Otherwise, in practice, it’s a really bad idea: assembly language is extremely hard both to write and to read, and usually has nearly-impossible-to-avoid subtle bugs scattered throughout the code.)

My assumption is that most people don’t know x86 assembly language, so I’ll explain everything.

## Hello, world

First, I’ll show you how to compile and run a minimal Microsoft Windows GUI application—an application that simply opens a blank window, with a button, that pops up an alert box when you click the button—written in assembly language. We’ll do this using the Windows API—Microsoft’s standard, native Windows programming API, and we’ll use the Microsoft Macro Assembler (MASM) .

Then, I’ll explain the code. With Windows native programming, writing a simple application actually a non-trivial task. Even in C and C++, writing simple Windows applications is daunting for a beginner.

Here’s what the application should look like:

Let’s look at the entire code:

Pretty simple, right? Yeah, not really…

I’ll explain the entire thing below, but first, let’s run it.

## Install MASM32

In order to run the code, you’ll need to install MASM. When programming in assembly language, you don’t compile your code, you assemble it. And MASM, or Microsoft Macro Assembler, is the name of the assembler software suite we’ll be using; there are other assemblers out there, but this one is endorsed by Microsoft and is probably the most widely used assembler for Windows.

Steps:

2. Run install.exe
3. Follow the prompts, accepting all default values

When you’re done, MASM32 should be installed in the folder C:\masm32.

### Build and run the program

The simplest way to quickly assemble and run the program is to use QEditor, which is included with the MASM32 package.

Run C:\masm32\qeditor.exe. It should look like this:

To load the code into QEditor, download HelloWorld.asm to a temporary directory, then, in QEditor, click File -> Open, and open HelloWorld.asm:

To build the program, choose Project -> Build All. Then, to run the program from the editor, choose Project -> Run Program:

Building the program should produce HelloWorld.exe in the same folder as the HelloWorld.asm:

When you run the program, you should see:

Click on “Click me” to see some behavior:

You might want to stop here and try playing around with the code. Next, I’ll try to explain every line of code in the toy program.

## The Source Code: Meta-Directives

In MASM, the word Directives is technically used to refer to nearly any special keyword recognized by the assembler. In my “hello world” code, there are a few particular directives which I’ve dubbed “Meta-Directives”: these are “header-like” directives which tell the assembler about how to assemble our program.

.386 means that, in order to run our program, you’ll need an Intel 80386-compatible processor. Since the 80386 processor is the oldest processor that Windows supports, this is the most compatible choice we could possibly make here. Other options are .486, .586, .686, etc.

.MODEL FLAT,STDCALL means two things:

1. We’ll be using a “flat” memory model. (And we have no choice: this is actually the only option here accepted by Windows!) The name “flat” for memory model is only of historical interest: with older processors (i.e., 16-bit), accessing more than 2^16 bytes of memory in a program had several difficulties, so there was a (convoluted) mechanism where one divided the memory into “memory segments”, and accessed memory as offsets from one of several memory segment pointer registers. When 32-bit came in, this was simplified by essentially “flattening” these segments into one big memory segment, thus the name.
2. We’ll also be using the STDCALL strategy for handling how parameters are passed on the stack from caller to callee for procedure calls; the only other strategy is the C strategy. The difference is that, with STDCALL, the caller pushes the parameters onto the stack before calling the procedure, and the callee pops them off the stack just before it returns. With the C strategy, the caller pushes the parameters to the stack before calling the procedure, then after the procedure returns, the stack is popped. The C strategy has the advantage of enabling variable-argument-length procedures, while STDCALL has the advantage of producing smaller executable sizes.

OPTION CASEMAP:NONE means that symbol names (i.e., procedures, labels, variables, etc—we’ll cover these later) are case sensitive. The word casemap refers to “mapping” between lowercase and uppercase; in our case, we don’t want a casemap. (Without this directive, you will actually get errors when attempting to call Win32 API procedures.)

## Includes

The INCLUDE directive (remember that directives and themselves are always case-insensitive—it’s the symbol names that are case-sensitive) will tell the assembler to include a copy of the specified file; it will be as if the file was copy-pasted as-is into our source code at this line. This is the standard mechanism used to reference other source code files, headers, etc. In this case, I’ve included windows.inc, user32.inc, and kernel32.inc, which are the primary Windows API header files which MASM provides out of the box. (You can use this directive to include any file you want—provide a relative or absolute file path, and the file’s contents will be included in your source code.)

The INCLUDELIB directive tells the linker that the specified library (i.e., .lib file, also known as a module, or a statically-linked library) should be linked into the final executable. Again, MASM provides a set of libraries by default for the Windows API. (You could also create and include your own libraries.)

## .DATA, .CONST, .DATA?

The .DATA?, .DATA, and .CONST directives behave differently than the others I’ve just described: these each begin new memory segments. Think of them as regions in RAM that will be accessible to your program at runtime. They differ in that:

• .DATA? is where you define global variables whose value you don’t care about at program initialization
• .DATA is where you define global variables whose initial values you want to specify
• .CONST is where you define global, constant, variables whose values can never change at runtime

To define a variable in any one of these sections, the general syntax is:

NAME    TYPE    VALUE

(Separated by spaces.)

The name can be any alphanumeric string.

The most common primitive types are:

• BYTE - An unsigned 1-byte integer (also used for strings) (also aliased as DB)
• SBYTE - A signed 1-byte integer
• WORD - An unsigned 2-byte integer (alias DW)
• SWORD - A signed 2-byte integer
• SDWORD - A signed 4-byte integer
• DWORD - An unsigned 4-byte integer (alias DD)
• QWORD - An unsigned 8-byte integer (alias DQ)
• SQWORD - A signed 8-byte integer
• REAL4 - A 4-byte floatint point number
• REAL8 - An 8-byte floatint point number

So, for example, to define an 64-bit unsigned integer named “id” with the value 0:

id QWORD 0

Arrays are also supported. If you define an array of something, they’ll simply be defined sequentially in memory. The syntax is like this:

ids QWORD 1,2,3,4,5

The above would place five 64-bit unsigned integers in a row: 1, 2, 3, 4, then 5.

Interestingly, to define a string, you simply define an array of bytes and each character will be mapped to a byte (usually with a null terminator):

ids BYTE 'h', 'e', 'l', 'l', 'o', 0

The shorthand for this is:

ids BYTE "hello"

(Characters are always one byte; unfortunately, Unicode isn’t directly supported.)

There is also, similar to C, the ability to compose types using STRUCT and UNION.

In MASM, defining a struct itself might look like this:

PRETEND STRUCT
firstField    DWORD      ?
secondField   DWORD      ?
thirdField    DWORD      ?
fourthField   DWORD      ?
PRETEND ENDS

Declaring an instance of the struct might look like:

MyPretendStructure    PRETEND    < 10, 20, 30, 40, 50 >

Finally, the .CODE directive is also, technically, a memory segment. Except, instead of defining “data” to go within it, you define executable code. When your program starts, it will point to code that you’ve placed at the beginning of this section.

In order to understand what goes in the .CODE section, you’ll need to understand what CPU registers are and what CPU instructions are.

## CPU Registers and Instructions

In the 80386 CPU, there are a well-defined set of registers:

• General Purpose Registers: eax, ebx, ecx, edx
• Index Registers: esi, edi
• Segment Registers: cs, ds, es, fs, gs, ss
• Instruction Pointer Register: eip
• Stack Pointer Registers: ebp, esp
• Flags: eflags

Registers are the fastest type of memory, and are embedded inside the CPU. For now, just know that most of them have a special purpose; except for the general purpose registers, which you can freely manipulate any way you like.

There are hundreds of CPU instructions. These are hardware-based procedures that manipulate registers (or RAM) in various ways. Most of them only accept 0 to 3 arguments (but there are exceptions). Sometimes arguments must be registers, sometimes integers, etc. Some instructions accept either (i.e., are overloaded). Below, I list a few of the the most common instructions:

Instruction First Argument Second Argument Description
mov dest src Copy the value of src into dest
add dest src Store the result of dest + src into dest
sub dest src Store the result of dest - src into dest
xor dest src Store the result of the bitwise dest XOR src into dest
and dest src Store the result of the bitwise dest AND src into dest
or dest src Store the result of the bitwise dest OR src into dest
not dest   Flip all the bits of dest
cmp src dest Compare src and dest (described below)

You can do a lot with just the above instructions. As a quick example, after running the following snippet, the eax register will be equal to 42:

Notice how in the previous code snippet, each argument to each instruction is either a register, or a raw numeric value. Notice how most instructions which result in an output value usually store their output back into the register passed as their first argument.

Importantly, you can almost always substitute a data pointer (i.e., the memory address of something in a data segment) in place of a register. For example, a variable defined in one of the .DATA/.DATA?/.CONST sections, like this:

After the above code is finished, eax will equal 11.

The next instruction I’ll introduce is jmp:

Instruction First Argument Description
jmp addr Copy the memory address addr into EIP

The jmp instruction performs a “goto”. It takes a single argument: an instruction pointer (i.e., the memory address of something in the .CODE memory segment). Usually, this will be in the form of a label. A label is simply a name given to a (code) memory address, which is simply a pointer to somewhere in your code, for example, start: in our “Hello, world” program.

Under the hood, there is a CPU register named EIP. The EIP register is the “instruction pointer” register: it is a special-purpose register which points to the next assembly language instruction which should be run after the currently-executing one. The jmp instruction works by taking an address as an argument, and storing the specified address into the EIP register, effectively jumping to that address.

The following code demonstrates how to use jmp. The output (stored in eax) will be 42:

## Conditionals

The instructions I’ve listed so far don’t yet allow us to do something which is vital to computer programming: conditionals. For this, we introduce the cmp instruction, which compares a register against a value. Interestingly, it does several comparisons at once.

For example, if you call cmp eax, ecx, it will calculate, all at the same time, whether eax<ecx, eax≤ecx, eax=ecx, eax≥ecx, eax>ecx, etc. It does this by storing all of these results in multiple different bits of the eflags register (which is sort of a warehouse of single-bit flags). After you do this, you can conditionally jump to an address using one of several instructions:

Instruction First Argument Description
je addr jmp to addr if arg1 = arg2
jne addr jmp to addr if arg1 != arg2
jg addr jmp to addr if arg1 > arg2
jge addr jmp to addr if arg1 >= arg2
jl addr jmp to addr if arg1 < arg2
jle addr jmp to addr if arg1 <= arg2

For example, after the following code finishes, eax will equal 100:

## The stack

This count_to_100 sort of seems like…a procedure! Except, it doesn’t take any arguments. If we wanted to create “procedures” that take arguments, we’d need to take advantage of the stack. “The stack” is simply a dedicated region of memory in the active process where we can “push” and “pop” data using following two extremely important instructions:

Instruction First Argument Description
push src “push” the value of src onto the stack
pop dest “pop” the stack, storing the result in dest

The src argument can be a value, register, or memory address. The dest can be a register or memory address. For example, let’s say we want to create a procedure that adds five numbers, then returns the result. We could code it like this:

Then, we could call it like so:

At the end of our program, eax would equal 10+20+30+40+50=150. This works for this small program, but for larger programs, it has a major flaw: when add5 is finished, it doesn’t return back to where we were before we called it; it simply moves on to whatever code we’ve defined just after we define add5! The solution to this is to use the call and ret macros, which solve this problem for us:

We can now call it more than once, for example:

In fact, the way that call and ret work under the hood is that, when call is invoked, it pushes the EIP register to the stack before jmp-ing, and when ret is called, it pops the stack back into the EIP register.

Note that returning values through the eax register is the de-facto standard.

## Procedures and macros

Basic assembly syntax is fairly primitive, but recall that MASM is a macro assembly language: this means it’s assembly language with macros. A macro is very similar to the traditional idea of a procedure (or function) from your other favorite programming language, except that the output of the macro occurs at assembly time rather than at runtime.

In the C programming language, you can define macros, too, with #define: for example, if you wrote #define PLUS_FIVE(x) (x+5), and you called PLUS_FIVE(10), the value would compile as 15as soon as you compiled your code, rather than at runtime. This is more of a common practice in assembly language than high-order languages, as is a big reason why assembly language can be so fast.

You can define a macro like this:

I could then use the above like this:

This would result in the following code being produced:

MASM provides several fundamental macros out of the box. For example, PROC, ENDP, and INVOKE, which respectively begin, end, and invoke a procedure. We can use these to simplify our previous code:

A few other important macros are the .IF, .ELSEIF, .ELSE, and .ENDIF macros. These perform conditionals in way familiar to anyone who’s ever used any other imperative programming language. For example, the following two are equivalent:

This should make it clear that macros allow you to keep your code a little bit cleaner without sacrificing the raw speed and flexibility you get out of assembly language.

Let’s get back to our HelloWorld program.

## .CODE

This section is where the important stuff begins.

When you assemble your program, you’ll need to provide an “entry point” into your executable. You do this with a label, which, as we’ve already discussed, are those things that you can jmp to (memory addresses that point to code). The standard is to name the entry point label start:

The first thing that the HelloWorld program (and indeed any Windows API program) does is call GetModuleHandle, which returns our application’s “Windows handle” (i.e., an integer given to us by the OS that uniquely identifies our Windows application). We do that with invoke GetModuleHandle, 0: this calls a procedure named GetModuleHandle, and passes 0 as its only argument.

The only reason we’re able to invoke GetModuleHandle is that a prototype for the GetModuleHandle procedure is included within kernel32.inc, which we’ve included in this file. If you’ve used C or C++, an assembly language prototype is similar to a pre-declaration you’d see an a .h file. The prototype for GetModuleHandle looks like:

GetModuleHandle PROTO STDCALL :DWORD

This prototype declaration says: “hey, I promise that in some library that you’re linked to, I’ve defined a label named GetModuleHandle, and if you want to invoke it, you should use the STDCALL argument-passing strategy, and pass it one argument, and that argument is a 4-byte unsigned integer.” We then store this pointer in our MyWindowClass global variable with MyWindowClass.hInstance, eax.

The line mov MyWindowClass.hInstance, eax means that the return value of the most recently called procedure should be stored in the MyWindowClass.hInstance variable.

To reiterate, the following code will invoke GetModuleHandle, store the result in a variable, then invoke WinMain, then invoke ExitProcess.

That’s the entirety of the “top-level” code. But notice how, above, we’re calling WinMain. Let’s look into it.

## WinMain

Since this is a Windows GUI application, we want a “window” to be visible when our program starts. The Windows API requires us to do three things before we can create an instance of a window:

• Define a variable of type WNDLCASSEX which will represent our window class (we named it MyWindowClass)
• Register our window class with the OS
• Create the window (as an instance of the window class)

As far as populating the MyWindowClass variable: we’ve done this partially in our .DATA section. But, in the .DATA section, we were only able to provide static values. Some fields, like the application’s icon and mouse cursor, we need to do at runtime, because we’ll need to call some procedures to get the data. In the code shown above, we invoke LoadIcon and LoadCursor (both being part of the Windows API) to load the standard window icon and a mouse cursor into memory, and we store pointers to these memory allocations in the MainWindowClass structure.

Once our MyWindowClass structure is populated, we can invoke RegisterClassEx. This tells the operating system to make our MyWindowClass an eligible to create instances of.

When we call CreateWindowEx, our window will be created, which means it will officially open up on our screen. I’ll skip explaining the list of arguments I’ve provided, but you can read about them in the official CreateWindowEx documentation. It has a return value: a “window handle”, which is a pointer to the instance of our window—we’ll store this in the variable MyWindowHandle.

When the window is created, it won’t actually be visible yet (we’ll do that in a second). And, even if it did, it would just be a completely blank window. A blank window is boring, so we’ll put a button in our window that says “Click me”:

With the above code, we’ve created an instance of the built-in window class named “BUTTON”, made it a child of our main window, and placed it at coordinates x=10, y=10, with width=75, height=35. Now, we can make the window visible:

ShowWindow tells the operating system that the window is now visible, while UpdateWindow forces the window to re-paint itself; after both of these, the window will immediately show on the screen.

The next step is to invoke the Windows event loop. This is a standard Windows API pattern which we’re simply implementing in assembly language. When you click on the screen, resize the window, minimize, maximize, close, or do anything else with the window, it will be sent to the window in the form of a Windows message, which will be processed in the following loop:

The above code first jumps directly to GetMsg, which invokes GetMessage, which polls the operating system for a message. It returns a boolean value: 1 means a message was found, and 0 means there are no more message and the application should exit. If it returns 0, the cmp and jne instructions will jump to MessageLoop, which attempts to process the message (I’ll explain in a second). Also, if GetMessage was successful, it will store a pointer to the message in MessageStruct.

Calling TranslateMessage and DispatchMessage will cause the message to be sent to our WndProc, which we’ll discuss next.

# WndProc

While WinMain is the procedure that is called when the application starts, WndProc is the procedure that is called every time a message occurs. Let’s review the outer skeleton of our definition of WndProc:

This means we’re defining a procedure which takes three arguments: hWnd, uMsg, wParam, and lParam.

The uMsg variable represents the type of message received. A few examples are:

• WM_MOUSEMOVE - This means the user moved their mouse
• WM_LBUTTONDOWN - This means the user pressed the left mouse button down
• WM_RBUTTONDOWN - This means the user pressed the right mouse button down
• WM_CHAR - This means the user typed a character on the keyboard
• WM_DESTROY - This means the user tried to close the window
• WM_COMMAND - This does several things (see below)

The two types of messages we care about in our program are WM_DESTROY and WM_COMMAND.

When a WM_DESTROY message is received, it means the user has requested to close the window (i.e., by clicking the “X” button in the top-right corner). If we want, we could actually refuse the request. But, being polite programmers, the appropriate response is to call PostQuitMessage:

What PostQuitMessage does is actually post another message, WM_QUIT, to our message queue: WM_QUIT is a special message which will result in the next GetMessage call returning 0, which will our message loop, which will end our program.

When a WM_COMMAND message is received , it could mean any number of things. One thing is could mean is that the user clicked the “Click me” button. And, if this is the case, then, according to the official Windows API documentation for buttons:

1. uMsg will be equal to WM_COMMAND, and
2. The lowest 16 bits of eax will be equal to BN_CLICKED, and
3. A pointer to which button was clicked will be in lParam

Thus, we can handle a button click with, essentially, the following:

The MessageBox procedure is a built-in Windows API procedure which will launch an “OK/CANCEL”-style dialog box, which is common in Windows programs. In this case, we want the message displayed on the dialog to be the string given in data variable PopupTitle, and we want the title bar to display the string given in PopupTitle. The MB_OK constant says that we simply want the dialog to have an “OK” button. The popup will look like this:

Finally, our message handler procedure also has a final .else clause which handles “other” message types:

Calling DefWindowProc (“default window procedure”) allows Windows to perform default handling for all sorts of message types which we don’t want to worry about.


text:
# How to Calculate Percent Difference

••• SARINYAPINNGAM/iStock/GettyImages
Print

The everyday world is filled with so much data given in the form of percents (or percentages) that you may never stop to think much about them.

You may understand what is meant by "60 percent of Americans sing off-key." If true, it means that 60 out of every 100, or 3 in every 5, Americans cannot properly carry a tune. But what about percent differences between two data points, or between the same data point at different times?

Percent difference calculations are straightforward but can be tricky when you fail to correctly identify the starting value. This often happens when conveniently round numbers make drawing incorrect inferences especially appealing. For example, if someone told you that his income increased last week by 10 percent because it rose from $90 to$100, you should have a rebuttal prepared.

## What Is Percentage Change?

To find the percent difference between a final value and an initial value, which can also be called percent charge, you first subtract the initial value from the final value, then divide this by the initial value. After you multiply the result by 100 to convert the decimal value into a percentage, you have your final answer.

In the language of math:

Percent\hspace{1mm}change = \dfrac{Final - Initial}{Initial} × 100

Note that percent change can be negative or zero. Use the information in the words of the problem carefully so that you keep initial values and final values straight.

## Percent Difference Calculation: Clothing Sale

A particular kind of blue jeans has become popular so rapidly that their price has shot up from $39 per pair six weeks ago to$99. What is the percent price increase?

From above, you have [(99 − 39)/39] × 100 = (60/39) × 100 = 153.85 percent.

This shows that even though "per cent" means "for each 100," situations exist in which percentages can greatly exceed 100.

• The % symbol is usually reserved for formal scientific and mathematical documents and papers. In everyday use, "percent" is preferred.

As a bonus question, assume the price increased by the same percentage each week over the six-week period. What is the value of this percentage?

You may be tempted to notice that the price increased by $60 over six weeks, a steady percentage increase translates to a neat$10 per week. However, this is the right basic approach, but the wrong math. Instead, divide the total percentage increase, not the magnitude of the numerical change, by 6:

153.85 / 6 = 25.64 percent per week.

## Percent Difference Calculation: Mile Run

Say your physical education teacher has all of the students in her classes complete a one-mile run for time at the start of the academic year. The students complete this "diagnostic" run in an average time of 10 minutes. At the end of the spring, she has the members of the class again run an all-out mile, and this time the class average is seven minutes even. What is the percentage improvement (i.e., reduction in time)?

This time, the equation of interest is [(7 − 10)/10] × 100 = −3/10 × 100 = −30 percent.

(The negative sign here is desirable, but this is not always the case.)

Now, assume the school year ends, and some of the students keep exercising over the summer while others discontinue physical activity. On returning to school, this group of students runs a third mile test, and the average of these "slackers" is back up to 10 minutes. What is the percentage decrease in performance compared to the previous spring?

Now the equation is [(10 − 7)/7] × 100 = −3/7 × 100 = 42.9 percent.

Because the initial value for the second part of the problem is 7 rather than 10, the same absolute difference of three minutes creates a larger percentage difference.

## Percent Difference Calculation: A Wage Increase

Returning to your friend's boast about his wage increase, you're now prepared to tell him the news is even better than he thought, from the standpoint of percentage differences. Can you calculate the percent increase when moving from 90 to 100?


text:
[RESOLVED]Diff - differential
12-05-2016, 02:30 PM (This post was last modified: 12-08-2016 02:52 PM by jrozsas.)
Post: #1
 jrozsas Member Posts: 158 Joined: Nov 2014
[RESOLVED]Diff - differential
Hi,
How can I solve this differential calculation in HP Prime?
z= 3x^2 - xy +y^2
Considering that (x, y) goes from (2,1) to (1.96,0.95).

I've made several attempts, but I can not enter the data correctly.

In this other POST (http://www.hpmuseum.org/forum/thread-7346.html), something similar happened, but Tim was able to enter the data correctly in LIMIT

Leo

12-05-2016, 09:24 PM (This post was last modified: 12-05-2016 09:43 PM by Han.)
Post: #2
 Han Senior Member Posts: 1,817 Joined: Dec 2013
RE: Diff - differential
Your equation z=3x^2-xy+y^2 is not a differential equation. Are there differentials in there that you left out, perhaps?

The diff() command computes the derivative (or partial derivative) of an expression. Usually it takes two parameters: an expression, and a variable of differentiation.

For example: diff(x^2*y^3,x) returns 2x*y^3 whereas diff(x^2*y^3,y) returns 3x^2*y^2.

If you do not specify a variable, then the default variable 'x' is used. For example, diff(x^2*y^3) returns 2x*y^3. So in your second attempt, it is not clear what you meant by the diff(diff(..)) operation since you did not specify a variable. Did you mean to compute $$\frac{\partial^2}{\partial x^2} (3x^2-xy+y^2)$$ or did you intend to have something else?

In particular, if you have questions on how to use a command, consider using the built-in help:

1) type the command
2) with the cursor on the typed command name, press the help button

Usually, the help also provides examples of how to use the commands. For desolve, the help says:

Code:
Syntax: desolve(Eq,[TimeVar],Var) Returns the solution to a differential equation. Examples: desolve(y''+y=0,y) → G_0*cos(x)+G_1*sin(x) desolve((y''+y=sin(x)) and (y(0)=1) and (y'(0)=2),y)

Graph 3D | QPI | SolveSys
12-06-2016, 12:03 PM (This post was last modified: 12-06-2016 12:04 PM by jrozsas.)
Post: #3
 jrozsas Member Posts: 158 Joined: Nov 2014
RE: Diff - differential
I can not understand. The equation z= 3x^2 - xy +y^2 (where(x, y) from (2,1) to (1.96,0.95)) can not be solved with desolve?

Leo

12-06-2016, 12:26 PM (This post was last modified: 12-06-2016 12:37 PM by Han.)
Post: #4
 Han Senior Member Posts: 1,817 Joined: Dec 2013
RE: Diff - differential
Usually a "derivative" is involved when solving a differential equation. For example, $$y = G_0 \cos(x) + G_1 \sin(x)$$ is a general solution to the equation $$\frac{d^2}{dx^2} y(x) + y(x) = 0$$. The equation $$\frac{d^2}{dx^2} y(x) + y(x) = 0$$ can also be written as $$y''(x) + y(x) = 0$$. So in this example, the differential equation $$y''(x) + y(x) = 0$$ involves the second derivative: $$y''(x)$$. To solve the equation $$y''(x) + y(x) = 0$$ we use:

desolve(y''(x)+y(x) = 0, y)

However, the equation you provided: $$z = 3x^2-xy+y^2$$ does not involve any (partial) derivative or differential.

Por lo general, un "derivado" está involucrado cuando se resuelve una ecuación diferencial. Por ejemplo, $$y = G_0 \cos (x) + G_1 \sin (x)$$ es una solución general a la ecuación $$\frac {d^2} {dx^2} y (x) + y(x) = 0$$. La ecuación $$\frac {d^2} {dx^2} y (x) + y(x) = 0$$ también se puede escribir como $$y '' (x) + y (x) = 0$$. Así, en este ejemplo, la ecuación diferencial $$y '' (x) + y (x) = 0$$ implica la segunda derivada: $$y '' (x)$$. Para resolver la ecuación $$y '' (x) + y (x) = 0$$ utilizamos:

Desolve (y '' (x) + y (x) = 0, y)

Sin embargo, la ecuación que proporcionó: $$z = 3x ^ 2-xy + y ^ 2$$ no implica ninguna derivada (parcial) o diferencial.

Graph 3D | QPI | SolveSys
12-06-2016, 12:27 PM
Post: #5
 roadrunner Member Posts: 293 Joined: Jun 2015
RE: Diff - differential
Leo,

Is this what you are trying to do?

12-06-2016, 12:36 PM
Post: #6
 Han Senior Member Posts: 1,817 Joined: Dec 2013
RE: Diff - differential
Are you trying to compute:
$\int_{1.96}^2 \int_{0.95}^1 \left( 3x^2-xy+y^2\right) \ dx\ dy$
Is that what you mean?

Graph 3D | QPI | SolveSys
12-06-2016, 01:41 PM (This post was last modified: 12-06-2016 01:42 PM by jrozsas.)
Post: #7
 jrozsas Member Posts: 158 Joined: Nov 2014
RE: Diff - differential

Is this what you are trying to do?

YESSSSSSS!!!!! Great!
Thank you all for your help!

Leo

12-06-2016, 01:50 PM
Post: #8
 jrozsas Member Posts: 158 Joined: Nov 2014
RE: Diff - differential
(12-06-2016 12:36 PM)Han Wrote:  Are you trying to compute:
$\int_{1.96}^2 \int_{0.95}^1 \left( 3x^2-xy+y^2\right) \ dx\ dy$
Is that what you mean?

No, but roadrunner sent the screen that solved the doubt. Thank you!

Leo

 « Next Oldest | Next Newest »

User(s) browsing this thread: 1 Guest(s)


text:
# Tag Info

1

As Andres Salas said, your kinetic energy should be the negative of the potential energy at the surface. Also, you're using the wrong formula for the potential energy in the crater. $-GMm/r$ is correct only when $r\ge R$.

1

The answer is quite simple. You can't see it because you've forgotten that you make an unphysical simplification when considering "tied to an immovable wall" type situations. What's unphysical about the situation is quite simple : there's no such thing as an immovable wall. Let's say the rocket is tied to the earth. To say where the lost chemical potential ...

0

The rocket motor generates thrust by acelerating the exhaust gases that it emits. The force on the rocket is equal to the change in momentum of the exhaust gases per second, i.e. the exhaust velocity times the exhaust mass per second. For the rocket travelling in space the energy generated from burning the fuel goes partly into the kinetic energy of the ...

0

If you assume that the fluid is incompressible, I'm relatively sure that it could be shown that 100% efficiency is theoretically possible. You could use a variety of mental models to do this. I would prefer to think about conventional hydraulics lifting some weight. If you match the weight to the pressure, then you could raise an external object some (m g h) ...

0

Turbines (impellers) have fins that work more like aircraft wings and sails than the buckets of a old water wheel. They have have very high lift/drag ratios which translate the high efficiency. It is friction and heat loss that kill efficiency not the work of the turbine (how much it spins).

2

Newton's third law. For the force the magnet exerts on the metal, there must be an equal an opposite force on the magnet exerted by the metal. Since both form one system (metal + truck + magnet), the net force on the system is zero, and it won't move.

1

If your electron is in a pure state then it's an eigenfunction, $\psi_e$, of the Hamiltonian describing it, $H_e$. The measuring system will also, in principle at least, be described by some wavefunction, $\psi_m$. If the two don't interact then the total wavefunction will just be a product: $$\Psi = \psi_e\psi_m$$ and the system won't change with time. ...

2

When you measure the position of an electron that is in a pure energy state, what happens the energy becomes non-deterministic. An electron in a pure energy state is in a bound state. To "measure it" you have to excite it or , if it is in an already excited state measure the photon of its deexcitation. You cannot measure its position, while bound, to ...

1

If you're looking for a general solution to the schrodinger equation then yes, it is possible for the atom to be in a superposition of energy states. This does not violate conservation of energy. Can you see why? It is a subtle point. To start you off -- how do you measure the position of the electron in the first place? You must hit it with something. This ...

0

It is incorrect to state that The magnet is only braked by the friction of the axis and the air. It is not clear to me exactly what you're proposing, but whenever you deliver electrical energy to some external system you will slow down the rotation of the coil. This is usually through an inductive torque caused on the rotating coil by the currents that ...

0

It seems to me the obvious answer is that it agrees with all the experiments. I am an experimentalist after all, (the neutrino is perhaps the best "missing energy" story.)

0

Chemical reactions satisfy mass conservation and energy conservation independently. Mass conservation implies the mass of the system remaining unchanged (zero change) as the reaction proceeds. Small changes - however small - are deemed to violate the law of conservation of mass. This has nothing to do with our ability to measure very small values of mass ...

2

When the universe expands, it is important to understand that how its energy content evolves depends on the form of energy involved. If all that energy is locked up in the form of mass energy, then the density of that matter will decrease proportionally to the relative increase of any arbitrary volume of the universe (i.e. if expansion doubles the size of ...

6

Temperature means energy. The heat energy is still here. It's just that the "object" (the Universe) grown bigger so this energy had to spread through it. The more energy in a single point, the hotter it is. That's why they say it got cooler. It's like the expanding gas from your spray deodorant is cold when it leaves the can, but it was at room temperature ...

0

(Not an answer as such, more an extended comment and suggestion). You wrote "On the other hand, the 1-D elastic collision problem can't be solved with Conservation of Momentum alone - Conservation of Energy is also required. " Actually the 1D elastic collision problem can be solved with (i) Conservation of Momentum (COM) (ii) application of symmetry (iii) ...

1

The efficiency of large hydroelectric generators can be very high - up to 95% in ideal cases - however the efficiency of small installations is a lot lower and in particular it's hard to get efficient electricity generation if the flow rate is low, which is likely to be the case for your friend. But lets see what the potential is. You don't say what the ...

1

You may doubt that energy is conserved, but it is a direct consequence of Noether's theorem together with the assumption of time translation invariance, and this latter assumption is perhaps a bit more palatable/fundamental. That is, it is mathematically true that if the outcome of an experiment doesn't depend on when we perform it, the quantity we call ...

3

Let's assume that an experiment is performed that seems to indicate a violation of the conservation of energy principle. Now, I suppose that it's logically possible that the experiment actually and unambiguously falsifies the principle in which case we must conclude that the principle is approximate and we must seek a deeper principle to guide our ...

4

I will try to give a short introduction into the ideas of scientific truth as I understand them. In mathematics, the world is beautifully simple. We have axioms that the set to be true, and from these we can deduce a plethora of statements to be undoubtedly true - given that the axioms are true. There may be undecidable statements about which we cannot say ...

0

It cannot be demostrated, but it can be checked. This year I've done an experiment which verifies (indirectly) this principle. It is really easy: I take an iron ball, and I shoot it to a pendulum. As a result, the pendulum goes up, and I can measure the deviation angle after the collision. With a sensor, I'm also able to measure the initial speed of the ...

3

I will make my comments into an answer: If we are talking of the classical domain, energy is conserved but can change forms. Inelastic scattering has a strict definition and is usually used describing two body scattering processes. In two body impact situations conservation of input energy in the output products would require that the target has some ...

0

If you are able to reduce friction to a minimum, but not to zero, may be able to run your machine for a long time, but not perpetually. Any energy loss must eventually be offset by the introduction of extra energy into the system. If you're really interested in running forever, there's no such thing as an insignificant energy loss.

9

Yes, when you fire a pistol the hammer hits the bullet with a relatively small initial kinetic energy but the kinetic energy of the hammer and bullet after the collision is considerably higher. This may seem a silly example, but I think it actually highlights the important principle involved. In general when two bodies undergo an inelastic collision part of ...

0

Dark energy due to a cosmological constant does not get diluted by metric expansion of space. However, this does not violate energy conservation as the increase in energy will be cancelled by gravitational potential energy. The problem with general relativity is (some would say arguably) not energy conservation, but energy localization: In a rotating frame ...

2

The cosmological constant is a constant energy density per unit volume of space, so as the universe expands this does indeed create energy as it creates new space. In this sense conservation of energy is violated. Actually this is less surprising than you might think. Conservation of energy is linked to a symmery called time shift symmetry by Noether's ...

1

Actually, energy is often not Conserved in general Relativity. For are more in deep explanation see: http://math.ucr.edu/home/baez/physics/Relativity/GR/energy_gr.html But just notice that Dark Energy might not necessarily end up being the cosmological constant, but a new force field, so its behavior might differ from that of an actual cosmological ...

0

The answer to the second question is actually quite straightforward: by computing $\partial_t E$ and using what given in the Gross-Pitaevskii for $\dot{\psi}$ and $\dot{\psi^*}$ one can check that all the terms cancel out so that $\partial_tE=0$. To derive the expression for the energy one could also start considering a lagrangian giving the ...

1

In general, the elasticity of a collision is dependent on the properties of the colliding objects. In a perfectly elastic collision, no kinetic energy is dissipated, which means the collision creates no heat, no sound, etc. In a perfectly inelastic collision, the maximum possible amount of kinetic energy is dissipated as heat, sound, etc. This corresponds ...

Top 50 recent answers are included


text:
## continuously tough [screenshots]

Posted in Books, Kids, Statistics, University life with tags , , , , , on December 27, 2022 by xi'an

As I was looking to a pointer on continuous random variables for an X validated question, I came across those two “definitions”…

## unbalanced sampling

Posted in pictures, R, Statistics with tags , , , , , , , on May 17, 2021 by xi'an

A question from X validated on sampling from an unknown density f when given both a sample from the density f restricted to a (known) interval A , say, and a sample from f restricted to the complement of A, say. Or at least on producing an estimate of the mass of A under f, p(A)

The problem sounds impossible to solve without an ability to compute the density value at a given value, since  any convex combination αf¹+(1-α)f² would return the same two samples. Assuming continuity of the density f at the boundary point a between A and its complement, a desperate solution for p(A)/1-p(A) is to take the ratio of the density estimates at the value a, which turns out not so poor an approximation if seemingly biased. This was surprising to me as kernel density estimates are notoriously bad at boundary points.

If f(x) can be computed [up to a constant] at an arbitrary x, it is obviously feasible to simulate from f and approximate p(A). But the problem is then moot as a resolution would not even need the initial samples. If exploiting those to construct a single kernel density estimate, this estimate can be used as a proposal in an MCMC algorithm. Surprisingly (?), using instead the empirical cdf as proposal does not work.

## approximate lasso

Posted in pictures, R, Statistics with tags , , , on October 2, 2016 by xi'an

Here is a representation of the precision of a kernel density estimate (second axis) against the true value of the density (first axis), which looks like a lasso of sorts, hence the title. I am not sure this tells much, except that the estimated values are close to the true values and that a given value of f(x) is associated with two different estimates, predictably…

## miXed distributions

Posted in Books, Kids, Statistics, University life with tags , , , , , , , , , on November 3, 2015 by xi'an

A couple of questions on X validated showed the difficulty students have with mixed measures and their density. Actually, my students always react with incredulity to the likelihood of a censored normal sample or to the derivation of a Bayes factor associated with the null (and atomic) hypothesis μ=0…

I attribute this difficulty to a poor understanding of the notion of density and hence to a deficiency in the training in measure theory, since the density f of the distribution F is always relative to a reference measure dμ, i.e.

f(x) = dF/dμ(x)

(Hence Lebesgue’s moustache on the attached poster!) To handle atoms in the distribution requires introducing a dominating measure dμ with atomic components, i.e., usually a sum of the Lebesgue measure and of the counting measure on the appropriate set. Which is not so absolutely obvious: while the first question had {0,1} as atoms, the second question introduced atoms on {-θ,θ}and required a change of variable to consider a counting measure on {-1,1}. I found this second question actually of genuine interest and a great toy example for class and exams.

## density()

Posted in R, Statistics with tags , , , , on June 28, 2011 by xi'an

Following my earlier posts on the revision of Lack of confidence, here is an interesting outcome from the derivation of the exact marginal likelihood in the Laplace case. Computing the posterior probability of a normal model versus a Laplace model in the normal (gold) and the Laplace (chocolate) settings leads to the above histogram(s), which show(s) that the Bayesian solution is discriminating (in a frequentist sense), even for 21 observations. If instead I use R density() over the posterior probabilities, I get this weird and unmotivated flat density in the Laplace case. It looked as if the (frequentist) density of the posterior probability under the alternative was uniform, although there is no reason for this phenomenon!


text:
# unique_ptr usage too unwieldy

I'm creating a MUD and am running into some design issues regarding Items.

Items are stored in an ItemDatabase after being read from a JSON file.

template <typename ItemType>
{
PropertyTree propertyTree;

for (auto& jsonItem : propertyTree)
{
Item *item = new ItemType();
item->fromJson(jsonItem);

database_[item->id()] = item;
}
}

At first, every Database::find() returned a shallow copy of the item, however, this quickly becomes dangerous and erroneous when items have a finite usage, e.g. a life potion that is consumed after one charge.

Therefore, I want to start returning deep copies as std::unique_ptrs because each Item is unique and is possessed by only one entity. This avoids dangerous dangling pointers, if the Item is not maintained or destroyed by the caller:

template <typename DataType>
std::unique_ptr<DataType> EntityDatabase<DataType>::find(EntityId const& entityId)
{
auto found = std::find_if(std::begin(database_), std::end(database_),
[&entityId](Container::value_type const& candidate)
{
return (candidate.second->id() == entityId);
});

if (found != std::end(database_))
return std::unique_ptr<DataType>(new DataType(*found->second));
else
return nullptr;
}

However, the resulting code is worse than hideous. Consider turning an Item into a Weapon:

void Inventory::fromJson(PropertyTree::value_type const& properties)
{
auto jsonInventory = *properties.second.find("Inventory");

auto weaponId = getValue<EntityId>(jsonInventory, "Weapon");
weapon_.reset(static_cast<Weapon*>(ItemDatabase::find(weaponId).release()));

auto armorId  = getValue<EntityId>(jsonInventory, "Armor");
armor_.reset(static_cast<Armor*>(ItemDatabase::find(armorId).release()));

money_ = getValue<Money>(jsonInventory, "Money");

for (auto& item : jsonInventory.second.get_child("Items"))
{
auto itemId = boost::lexical_cast<EntityId, std::string>(item.second.data());
inventory_.push_back(std::move(ItemDatabase::find(itemId)));
}
}

How can I improve the code or the design?

Let me restate the problem, because it wasn't 100% clear to me from what you've written. I personally think you've left out a bit too much code. I'll state my assumptions of what is going on, but ideally this should be clear from what is posted. Firstly, I assume EntityDatabase is a class, not a namespace. Secondly, I assume ItemDatabase is declared as something like:

EntityDatabase<Item> ItemDatabase;

Further, I assume you have some kind of inheritance hierarchy that looks something like:

class Item
{
Item();
virtual ~Item();
//....
}

class Weapon : public Item
{
//...
}

class Armor : public Item
{
//...
}

The problem then is that ItemDatabase.find(...) (I assume it's meant to be ., not ::) will return a std::unique_ptr<Item> when you want a std::unique_ptr<Weapon> or some other derived class of Item.

This seems less a problem of unique_ptr and more the fact that you're kind of abusing polymorphism. Let's assume you didn't return a unique_ptr, just a normal Item*:

template <typename DataType>
DataType* EntityDatabase<DataType>::find(EntityId const& entityId)

The only thing that would change then is that armor_ would be declared as Armor* instead of std::unique_ptr<Armor>, so it would become:

 armor_ = static_cast<Armor*>(ItemDatabase::find(armorId));

Hence, the only things that really change are the calls to release and reset. This is not significantly less ugly than what is already there. If armour_ were declared as std::unique_ptr<Item> then you could of course do the following:

armor_ = std::move(ItemDatabase::find(armorId));

Again, this is all built on a lot of assumptions since there is quite a bit of context missing.

For fixes, I suppose the options are:

• Leave it as is. It's fairly ugly, but not that much uglier than the code you'd have for raw pointers.

• Fix your inheritance hierarchy. The fact that you're having to cast things back and forth suggests that perhaps polymorphism isn't the correct solution here. Does each item need to know its specific type? Is there a virtual function you can add to Item that will fix this? I don't know, there's not enough context from the code you've posted.

• Finally, make a function to limit the uglyness to one spot:

template <typename T, typename U>
void recast(std::unique_ptr<T>& ptr1, std::unique_ptr<U>&& ptr2)
{
static_assert(std::is_base_of<U, T>::value, "U is not a base type of T");
ptr1.reset(static_cast<T*>(ptr2.release()));
}

....
auto armorId  = getValue<EntityId>(jsonInventory, "Armor");
recast(armor_, ItemDatabase::find(armorId));

This is still pretty ugly, but if used often, might be slightly less offensive.

• Thank you for your input! You are correct with almost all assumptions, except that EntityDatabase and, by extension, ItemDatabase are static. My first approach was exactly to declare armor_ as Armor*. I did this because I wanted to constrain the types of items that could act as armor or weapons, even though they are items. I'm inclined to agree that this is an abuse of polymorphism, but aside from declaring Weapon and Armor not a derivative of Item, I didn't and don't know how to otherwise solve it. – IAE Apr 1 '13 at 9:31
• I added some more information based on the assumptions you made and further snippets I thought to be illuminating. – IAE Apr 1 '13 at 9:44
• I think in this case there isn't all that much you can do. Unfortunately, C++ syntax is not concise at the best of times. The code is ugly, true, but it's not too hard to understand what is going on. – Yuushi Apr 3 '13 at 1:58


text:
# Charge on acpacitor

1. Jul 5, 2007

### pardesi

why is there equal charge on both the capacitor when one end of one and the other end the other is connected to a battery

2. Jul 5, 2007

3. Jul 5, 2007

### ice109

hes asking why equal but opposite charges develop on opposite sides of a parellel plate capacitor and the answer is because they have to setup an E field that cancels out the field of the battery

4. Jul 5, 2007

### pardesi

well here i am not using any speciality of the 'capacitor'...i just use 4 plates connect two of them to a battery and place two of the other after connecting them by a perfectly conducting wire in between the two plates....will the charge distribution be $$Q,-Q,Q,-Q$$ respectively ...if yes why

i am trying to proceed on the lines of uniqueness theorem for electric fields...

5. Jul 5, 2007

### ice109

i told you why, because charge travels down a potential gradient and since a cap is an open circuit it will stop at the plate and create a field.

6. Jul 5, 2007

### ranger

This is a very interesting question. You will find this discussion of interest:
http://www.usna.edu/Users/physics/mungan/Scholarship/Capacitors.html

7. Jul 6, 2007

### pardesi

hey thanks for that wonderfuls site.
i got a proof on the line that the there is no charge deposition on the wire and assuming steady state


text:
# If $$x^y=e^{x-y}$$, show that $$\large\frac{dy}{dx}=\frac{logx}{\{log(xe)\}^2}$$

Toolbox:
• $\log m^n=n\log m$


text:
# Numerical methods for $u_t+c u_x= \frac{-c}{x}u$?

I am looking for possible numerical methods to solve the PDE $$u_t+c u_x= \frac{-c}{x}u$$

I am particularly interested in a Finite elements method, although I am also curious if you can expose some other methods.

• It looks like there is an analytic solution here, if that's of interest. Jun 20 at 19:40
• Specifically, you can use the method of characteristics I assume. But you need to state the domain of possible $x$ values, and what you want to happen at $x=0$. Jun 21 at 0:48