Q:

Add webview into linearlayout android

I want to add view into my main view....
my main.xml file...
<LinearLayout
        android:id="@+id/dynamicview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1.28"
        android:gravity="center_vertical"
        android:orientation="vertical" >

</LinearLayout>

I have another layout file call complete.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

I want to add this web view into linearlayout....it means I want to inflate webview into my mainactivity...
I used the following method...
LinearLayout dynamic=(LinearLayout)findViewById(R.id.dynamicview);
LayoutInflater inflater = (LayoutInflater)    getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View v = (FrameLayout) inflater.inflate(R.layout.complete, null);
        v.setBackgroundColor(Color.GREEN);
        v.getRootView();
        dynamic.addView(v);
        v.setVisibility(View.VISIBLE);

but this doesn't work. if this is correct then color must be change...but nothing happened. pls help me.. I'm stuck with this...
thanks

A:

Try this:
LinearLayout dynamic=(LinearLayout)findViewById(R.id.dynamicview);
LayoutInflater inflater = (LayoutInflater)    getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View v = (FrameLayout) inflater.inflate(R.layout.complete, null);

WebView wv = (WebView)v.findViewById(R.id.webView1);
wv.setBackgroundColor(Color.GREEN);
        v.getRootView();
        dynamic.addView(v);
        v.setVisibility(View.VISIBLE);

You were trying to change the colour of the FrameLayout which has been filled by WebView therefore the green colour won't be visible. Instead, you have to change the colour of the WebView.


Q:

AudiManager changing from Bluetooth to EAR_PIECE does not work

I have a button that should go from EARPIECE to SPEAKER to BLUETOOTH and so on.
This is my code:
 fun setSpeakerValue(value: SIPManager.AUDIO) {
        speaker = value
        when (value) {
            SIPManager.AUDIO.EAR_PIECE -> {
                Log.i("Speaker", "Speaker1 EARPIECE")
                binding.callItemIconSpeaker.setImageResource(R.drawable.speaker_off)
                if (SIPManager.isBluetoothConnected()) {
                    audioManager?.isBluetoothScoOn = false
                    audioManager?.stopBluetoothSco()
                }
                audioManager?.mode = AudioManager.MODE_NORMAL
                audioManager?.isSpeakerphoneOn = false
            }
            SIPManager.AUDIO.SPEAKER -> {
                Log.i("Speaker", "Speaker1 SPEAKER")
                binding.callItemIconSpeaker.setImageResource(R.drawable.speaker_on)
                if (SIPManager.isBluetoothConnected()) {
                    audioManager?.isBluetoothScoOn = false
                    audioManager?.stopBluetoothSco()
                }
                audioManager?.mode = AudioManager.MODE_IN_COMMUNICATION
                audioManager?.isSpeakerphoneOn = true
            }
            SIPManager.AUDIO.BLUETOOTH -> {
                Log.i("Speaker", "Speaker1 BLUETOOTH")
                binding.callItemIconSpeaker.setImageResource(android.R.drawable.stat_sys_data_bluetooth)
                audioManager?.mode = AudioManager.MODE_NORMAL
                audioManager?.isSpeakerphoneOn = false
                audioManager?.startBluetoothSco()
                audioManager?.isBluetoothScoOn = true
            }
        }
    }

But wheneven I ste to earpiece, I stopBluetoothSCO, I set isSpeakerOn to false, but after that, I start hearing in the blueooth instead of the earpiece of the phone. What am I doing wrong?

A:

Got it to work using the answer from here:
How to switch audio output from Phone, Phone Speaker, earphones or Bluetooth device
 //For BT
        mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
        mAudioManager.startBluetoothSco();
        mAudioManager.setBluetoothScoOn(true);
    } else if(true) {
        //For phone ear piece
        mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
        mAudioManager.stopBluetoothSco();
        mAudioManager.setBluetoothScoOn(false);
        mAudioManager.setSpeakerphoneOn(false);
    } else {
        //For phone speaker(loudspeaker)
        mAudioManager.setMode(AudioManager.MODE_NORMAL);
        mAudioManager.stopBluetoothSco();
        mAudioManager.setBluetoothScoOn(false);
        mAudioManager.setSpeakerphoneOn(true);
    }


Q:

Can this be done with SQLAhclemy / Python?

I'm trying to create a database in SQL, with python. Was wondering if it would be possible to group things together like the below image? (I know we can do this in Excel. But I was wondering if it would be possible to do it in SQL?)

If it is not possible to do this in SQL, What do you suggest I can do that would provide similar results?

A:

Yes, it is possible to achieve that with SQL. All you have to do is create a table like this:
CREATE TABLE data (
    names TEXT,
    counter INT,
    ratio1_2012 INT,
    ratio2_2012 INT,
    ratio3_2012 INT,
    ratio4_2012 INT,
    ratio1_2013 INT,
    ...
);

Of course, this is not a very "pretty" solution and so it might be better to have one table per year:
CREATE TABLE data2012 (
    names TEXT,
    counter INT,
    ratio1 INT,
    ...
)

...

In the end, which approach you want to take depends on how much data you have and how much of a concern is space vs query execution speed to you. If you have two tables, you have a lot of duplicated data (all names for instance).
Visually, either method works fine you just have to adapt the frontend code in the necessary way.


Q:

Speed up CSS3 translating effect

I have a div translating forward and backwards infinitely. So, I want to change div's "speed" randomly. For increasing and decreasing speed I'm trying to change animation-duration property, but after this:
$("#rectangle").css('-webkit-animation-duration', randomValue + 's');

nothing happens.
Div has to behave, like it's just increasing/decreasing speed
EDIT: So, maybe anyone can give an advice how it could be made, if my way doesn't work properly?

A:

I plotted the general idea I was thinking of in this Fiddle..
I think you missed something related to the prefixes and the browsers.. as you can see the example I've written is working, kind of buggy too.
As you can see all I had to do is to invoke same code but with prefixes for firefox and webkit:
$("div").css("-webkit-animation-duration", lastTime + "ms").css("animation-duration", lastTime + "ms");

You will have to be careful with the animation duration.. because you changing the duration in a time the animation is still running will reposition the element depending on where it should be at that keyframe for that period..
Example.. if the animation is 2 seconds.. and it is 90% done.. changing the duration to 4 seconds will make it 90% of the 50% (2 / 4 seconds) done.. and that's the reason for the buggy animation you have seen in the fiddle.
I hope this helps..


Q:

Update bootstrap to version 3 Razor view

I'm using bootstrap upgrade service for upgrading from Bootstrap 2.x to 3.x
http://upgrade-bootstrap.bootply.com/
But I have a problem converting the razor syntax. For example I have:

        Action

And service returns:

Action

Look what happens to Url.Action function. This is only small example. I have a lot of files and a lot of code.
Is there any other way of converting razor views to bootstrap 3.x?

A:

I'm the author of http://upgrade-bootstrap.bootply.com/
The problem you're seeing is because the service uses jQuery to manipulate the DOM and structure of your HTML. A headless browser is being used, and this changes the actual HTML content upon conversion.
I've added a new switch ("Modify nav and modal structure") to prevent this from happening, but as a result the structure of any  modals and navs will not be converted to Bootstrap 3.
So, if you want to keep the Razor content the same, just uncheck the "Modify nav and modal structure" checkbox before you "Convert to Bootstrap 3" and it should work for you.


Q:

Events tab randomly appears and disappears in VS 2008

I know it's a minor annoyance.. but it's still an annoyance and it baffles me.. About 3 months ago I was using VS 2008 and when I went to the "Properties" tab there was the little lightning bolt for events(in design mode). Then it suddenly went away.. about a week later I discovered that if I didn't have the properties tab "stickied", then the events thing would be there, but not when its stickied.
This morning all of this was working fine. Now today I went to add an event, and suddenly the little lightning bolt icon is no longer there. I can not see any option disabling and it disappeared without me doing any reconfiguration.. Even without restarting VS. And I have tried restarting VS to no avail..
What am I missing here? Is this a highly annoying bug in VS 2008(its up to date) or am I missing some configuration?
Update I'm attaching a bounty to this question to see if I can get something a bit more helpful. In short it seems like the event tab will appear and disappear on a month or two cycle. And it's not a context problem. I have my cursor inside of a button for instance and I can edit all the properties of the button yet the events tab does not show up... More confusing is that yet again, this was working a few weeks ago
alt text http://img714.imageshack.us/img714/6301/eventsx.png

A:

The Events tab is driven by the designer.  If the designer is active, or the source view is active but the designer is synced, you should see the Events tab.  Once you change the source view content, the designer will be out of sync and won't show the Events tab anymore.  You can get the Events tab to show up again by switching to the designer and back.
You can tell whether the designer is synced by looking at the type information in the Property Grid.  If it is synced, you'll see the full .NET class name (e.g. for a Button, you'll see something like Button1 System.Web.UI.WebControls.Button), and if it's not synced, you'll just see an XML element (e.g. Button1 <BUTTON>).  Also, the list of properties available for the element and how they are arranged in the Property Grid will change according to whether it's using the type properties, or the schema properties.


Q:

Power in a uniform circular motion

I've a circular motion and I want to find the power that the motion is generating. The formula's I got:
$$\text{P}\left(t\right)=\text{W}'\left(t\right)=\text{E}'\left(t\right)$$
Where $\text{P}$ is the power, $\text{W}$ is work and $\text{E}$ is energy.
But I don't know how to continue with known formula's? The wheel (that spin in a circular motion, has a certain velocity and revolutions per minut, but I want to keep them as a variable)
Thanks in advance for any help.
EDIT
What I now have:
$$\text{E}=\text{K}=\frac{\text{I}\times\omega^2}{2}=\frac{\text{I}\times\left(2\pi\times\frac{\text{n}}{\text{t}_\text{n}}\right)^2}{2}=\frac{\left(\text{m}\times\text{r}^2\right)\times\left(2\pi\times\frac{\text{n}}{\text{t}_\text{n}}\right)^2}{2}=\frac{2\pi^2\text{m}\text{n}^2\text{r}^2}{\text{t}_\text{n}^2}$$
Where $\text{n}$ is the number of turns of the wheel and $\text{t}_\text{n}$ is the time (number of seconds) it takes for the wheel to spin $\text{n}$ times.
The wheel I use:
See the picture in the article

A:

The wheel I use:

A 100 % accurate calculation of the inertia moment of this type of wheel is hard to do but getting a reasonable estimate is perfectly doable.
To do so we can use the simple principle that like masses, inertia moments are additive and subtractable. Thus by breaking the wheel up into constituent parts and calculating the inertia moment of each part, we can then sum to get a total $I$.
We can use this list of inertia moments for great help.
Part 1: these flanges can be considered flat discs with a central disc cut out of them:
$$I_1=m\Big(\frac{R^2}{2}-\frac{r^2}{2}\Big),$$
where $R$ is the large radius and $r$ the smaller one. $m$ is the mass of the flange.
Part 2: the spokes.
Each spoke contributes approx.:
$$I_2\approx \frac{mL^2}{3},$$
with $L$ the length of a spoke and $m$ it's mass.
Part 3: the scoops.
Treat each scopp approx. as a point mass, so each contributes:
$$I_3=\frac{mr^2}{2},$$
with $r$ the distance of a scoop from the centre of the wheel and $m$ the mass of a scoop.
Part 4: the central axle.
Assuming it's a hollow cylinder:
$$I_4=mr^2,$$
where $m$ is its mass and $r$ its radius.
Part 5: looks like a cylinder that is between the flanges and holds the scoops in place.
$$I_5=mr^2,$$
where $m$ is its mass and $r$ its radius.
Total $I$:
Add up all the above, using the right number of parts for each section.

It might be easier to actually measure $I$. Consider the following diagram:

A rope is attached to the top of the wheel and a mass $m$ dangles off it. At $t=0$ the mass is released.
The mass $m$ causes torque $\tau$ and thus angular acceleration $\alpha$, acc. Newton's second law (applied to pure rotation):
$$\tau=I\alpha$$
With $\tau=mgR$,
$$mgR=I\alpha$$
So,
$$\alpha =\frac{mgR}{I}$$
Using this equation of motion it can further be deduced that:
$$I= \frac{mgR}{\pi}t^2,$$
where $t$ is the time for the weight to hit the floor.


Q:

how to make edittext move from left to right or vice versa in animation type

i have done validation for edittext onclick of button and if it is empty will show a toast saying particular field empty and in addition want edittext to get it moved from left to right and vice versa as an animated form and will help to make app attractive Is it possible?? if so please help me thanks in advance

A:

Create and Write following into anim/shake.xml:
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0" android:toXDelta="10" android:duration="1000"
    android:interpolator="@anim/cycle_7" />

Create and Write following into anim/cycle_7.xml:
<cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android" android:cycles="7" />

now Use Animation class to animate any view by passing in argument. Call this method by passing any view
public void onShake(View v, String your_msg) {
    Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
    findViewById(R.id.pw).startAnimation(shake);
    Toast.makeText(this, your_msg, Toast.LENGTH_SHORT).show();
}


Q:

How could I include my business partners / investors in the open source product development?

In my company we are developing a large open source piece of software. To do this we have hired many developers. To pay these developers we have gotten business partners and investors to help cover the cost.
However these people are not the most tech savvy people and it is often hard to explain to them what they are investing in!
My question:
Is there any way to make open source projects more interactive for business partners or investors?
For example: would it be recommended to teach them some coding to show them what they are investing in?

A:

Trying to teach your investors how to program is likely a waste of time. They are not inclined to learn it, they don't have the time to learn it, and it is unlikely to help them make a business decision (People who can code a bit are often worse managers than those who can not code at all, because they often believe to know far more than they actually do).
The open source culture and its productivity might be fascinating to us programmers, but businesspeople are not interested in this. They are only interested in:

How much will it cost me?
How will it make me money?
How much money will it make me?
When will it start to make me money?
What is the risk it won't make me money?

When you want to convince businesspeople to fund your project, you need to present them a business case which answers these questions and explains why it is more profitable to open source this project than to develop it under a proprietary license.


Q:

Complex subfigure grid

I would like to arrange four subfigures into a 2-by-2 grid, where the grid element heights vary; something like this:
|------|  |----------|
|------|  |----------|
|------|  |----------|
|------|       c)
|------|
|------|  |----------|
|------|  |----------|
   a)     |----------|
          |----------|
|------|  |----------|
|------|  |----------|
|------|  |----------|
   b)          d)

Is this possible? I tried to adapt this solution for a similar question, but could not get it to work for my complex requirements.

Update
Following some very useful answers, I realise I did not precisely specify my requirements. In particular, the sum of the heights for each column are not equal. I thus want to align the bases of each column, like this:
|------|
|------|  |----------|
|------|  |----------|
|------|  |----------|
|------|       c)
|------|
|------|  |----------|
   a)     |----------|
          |----------|
|------|  |----------|
|------|  |----------|
|------|  |----------|
   b)          d)

A:

This layout is quite easy to obtain with \valign.
The command \subcaptionpartial has the syntax
\subcaptionpartial[<list entry>]{<subcaption>}{<image>}

and, as in \subcaptionbox, the \label should go in the first mandatory argument. If missing, the optional argument is taken to be the same as the first mandatory argument, as usual for \caption.
\documentclass{article}
\usepackage{graphicx}
\usepackage{subcaption}
\usepackage{xparse}

\NewDocumentEnvironment{subcaptioncolumns}{}
 {\def\\{\unskip\unskip\cr\noalign{\hspace{1em}}}\valign\bgroup\vfil##\cr}
 {\unskip\unskip\crcr\egroup}
\NewDocumentCommand{\subcaptionpartial}{O{#2}mm}{%
  \hbox{\subcaptionbox[#1]{#2}{#3}}\medskip
}

\begin{document}

\begin{figure}
\centering

\begin{subcaptioncolumns}
\subcaptionpartial{\label{one}}{%
  \includegraphics[width=4cm,height=6cm]{example-image}%
}
\subcaptionpartial{\label{two}}{%
  \includegraphics[width=4cm,height=3cm]{example-image}%
}
\\
\subcaptionpartial{\label{three}}{%
  \includegraphics[width=4cm,height=4cm]{example-image}%
}
\subcaptionpartial{\label{four}}{%
  \includegraphics[width=4cm,height=4cm]{example-image}%
}
\end{subcaptioncolumns}

\caption{Whatever}\label{full}

\end{figure}

\end{document}

A:

Applying the linked solution is actually quite straight-forward – just add the desired heights:
\documentclass{article}
\usepackage[demo]{graphicx}
\usepackage{subcaption}

\begin{document}
\begin{figure}[ht]
  \centering
  \parbox{\textwidth}{
    \parbox{.3\textwidth}{%
      \subcaptionbox{}{\includegraphics[width=\hsize, height=4cm]{imageA}}
      \vskip1em
      \subcaptionbox{}{\includegraphics[width=\hsize, height=2cm]{imageB}}
    }
    \hskip1em
    \parbox{.3\textwidth}{%
      \subcaptionbox{}{\includegraphics[width=\hsize, height=2cm]{imageC}}
      \vskip1em
      \subcaptionbox{}{\includegraphics[width=\hsize, height=4cm]{imageD}}
    }
  }
\end{figure}
\end{document}

Edit: If the bases of the columns shall be aligned, this can be achieved by specifying the vertical alignment of the parboxes:
\documentclass{article}
\usepackage[demo]{graphicx}
\usepackage{subcaption}

\begin{document}
\begin{figure}[ht]
  \centering
  \parbox{\textwidth}{
    \parbox[b]{.3\textwidth}{%
      \subcaptionbox{}{\includegraphics[width=\hsize, height=4cm]{imageA}}
      \vskip1em
      \subcaptionbox{}{\includegraphics[width=\hsize, height=2cm]{imageB}}
    }
    \hskip1em
    \parbox[b]{.3\textwidth}{%
      \subcaptionbox{}{\includegraphics[width=\hsize, height=2cm]{imageC}}
      \vskip1em
      \subcaptionbox{}{\includegraphics[width=\hsize, height=4cm]{imageD}}
    }
  }
\end{figure}
\end{document}


Q:

Encoding and Decoding Strings using UnsafeMutablePointer in Swift

I'm having trouble converting strings to and from UnsafeMutablePointers. The following code doesn't work, returning the wrong string.
// func rfcommChannelData(rfcommChannel: IOBluetoothRFCOMMChannel!, data dataPointer: UnsafeMutablePointer<Void>, length dataLength: Int)
func receivingData(data dataPointer: UnsafeMutablePointer<Void>, length dataLength: Int) {
    let data = NSData(bytes: dataPointer, length: dataLength)
    println("str = \(NSString(data: data, encoding: NSASCIIStringEncoding))")
}

// - (IOReturn)writeSync:(void *)data length:(UInt16)length;
func sendingData(data: UnsafeMutablePointer<Void>, length: UInt16) {
    receivingData(data: data, length: Int(length))
}

var str: NSString = "Hello, playground"
var data = str.dataUsingEncoding(NSASCIIStringEncoding)!
var bytes = data.bytes

sendingData(&bytes, UInt16(data.length))

A link to the playground file is here. If anyone has experience using UnsafeMutablePointers in Swift for strings, I would very much appreciate some guidance as I have made no progress in the last few days. Thanks again!

A:

With
var bytes = data.bytes
sendingData(&bytes, UInt16(data.length))

you pass the address of the variable bytes itself to the function, so what you see is the bytes that are used to represent that pointer.
What you probably want is
let str = "Hello, playground"
let data = str.dataUsingEncoding(NSASCIIStringEncoding)!
sendingData(UnsafeMutablePointer(data.bytes), UInt16(data.length))

to pass the pointer to the data bytes.
You should also consider
to use NSUTF8StringEncoding instead, because a conversion to
NSASCIIStringEncoding can fail.


Q:

Frame stacking effect in After Effects

If I have a locked-off camera filming an athlete moving through the frame, how could I stack the frames so that every new frame of movement was layered on top of the next?  Assuming the background remains static throughout, is there a clever way to do it without tonnes of rotoscoping?
For example, here's a (famous) sequence of a horse running:

And here's the kind of effect I'd like to be able to achieve, without keying/rotoscoping etc:

Note that I made this with a simple luma key, because the background is mostly white.

A:

Think about what you're asking. When you did the horse you used a luma key to isolate just the horse. If the horse was running through trees or down a racetrack what would you want to happen to the trees and other stuff in the background? Would they go over the horse from the layer underneath? If so, how are you going to see the layer underneath?
There's no way of overlaying frames without the front layer being partially transparent - either transparent in part of the frame (masks or roto), transparent depending on their pixel values (transfer mode, or key) or with an overall opacity of less than 100%. If it's not transparent then you can't see the background, it's that simple.
If you can, shoot against a green screen and key out your foreground. This will let you layer it up to create a visual echo as you show in your example. That's the best way to do this, even though it's "cheating".
If chroma keying is not possible, and if only part of your frame is moving, you might be able to use a difference matte. Get an empty shot of your background and use that to matte out only the parts of the frame that have changed. This will work best with locked-off shots.
Failing that, have a play with various transfer modes. They're basically pixel level keys that work depending on the value of the foreground and background colour. I worked with a visual artist who produced some lovely dance videos using time-delayed layering kind of technique. She filmed the dancers against black, and rather than pulling a key we just used the lighten transfer mode - which is basically a way of keying parts of your image that are darker than the layers below (we were using hundred of layers in each comp, I did some scripting work to make the whole process a lot easier).
Otherwise, if transfer modes, chroma / luma keys or difference keys don't work, put on a pot of tea, turn up the music and get stuck in to the roto.


Q:

Indexed Thread on dataset and list

I currently have a dataset, and I would like to add a column based on another list.
For example:
ds = Dataset[{<|"name" -> "bob"|>, <|"name" -> "joe"|>}];
ages = {1,2};

I want to get
Dataset[{<|"name" -> "bob", "age"->1|>, <|"name" -> "joe", "age"->2|>}];

I was thinking of using MapIndex, but I don't really know how to make reform the results into a dataset again, and it seems wasteful.
How can I do this?

A:

ds[MapIndexed[Append[#1, "age" -> ages[[First@#2]]] &]]

{<|"name" -> "bob", "age" -> 1|>, <|"name" -> "joe", "age" -> 2|>}

Note 10.0.2 throws a warning - who knows what's going on in that private type system:

 First::normal: Nonatomic expression expected at position 1 in \
First[TypeSystem`ZSignatures`PackagePrivate`i]


Q:

How to get current sandbox size or app size

I would like to get the total size of my app or the sandbox size. Is there any official way to get this? Thanks.

A:

If you just want to know app size without any kind of coding then there is a way. As Apple applies their own logic to give only supported assets to the device which downloads your app, app size varies between devices.
Follow below steps:

Archive and upload your latest build to AppStore
Login to https://itunesconnect.apple.com
Go to your app's "Activity" tab and wait until its finished "Processing"
Then click on your latest uploaded build number and find App Store File Sizes link
Then you are able to see estimated app size on different devices like below

And if you only want to see app size on particular device then you can see that in TestFlight App, undar App Details menu


Q:

Are there any examples of vector functions where the magnitude of the displacement vector is always equal to the magnitude of the velocity vector?

For example, let the displacement vector be:$$r(t)=\begin{bmatrix}f(t)\\g(t)\\h(t)\\\end{bmatrix}$$and let the velocity vector be:$$v(t)=\begin{bmatrix}x(t)\\y(t)\\z(t)\\\end{bmatrix}$$Are there any such vector functions where $\begin{vmatrix}r(t)\\\end{vmatrix}=\begin{vmatrix}v(t)\\\end{vmatrix}$ for all $\{t:t\in R, t>0\}$?
If not, could somebody explain why such functions cannot or do not exist?
I know this might sound like a straightforward question but I have no idea and am genuinely curious.

A:

Consider for instance a circular path ,
$$r (t)=\begin{bmatrix} \cos t\\ \sin t\\0\end{bmatrix},\ \ \ \ \ t\geq0. $$


Q:

Kotlin Goal Oriented Action Planning

I've implemented Goal Oriented Action Planning (GOAP) in Kotlin.
Goal Oriented Action Planning is an algorithm originally devised by J Orkin for the game F.E.A.R. and performs a state space search using A* in order to formulate a plan of actions to get from an initial state to a goal state.
I've commented the code comprehensively and written some tests.
I'm looking for a code review to make sure my naming is good, my comments are good and that overall it makes sense.
import org.junit.Test
import java.lang.Math.*
import java.util.*
import kotlin.collections.HashSet
import kotlin.test.assertFalse
import kotlin.test.assertTrue

/**
 * This set of algorithms is an example of a Goal Oriented Action Planner (aka GOAP)
 *
 * Goal Oriented Action Planning (GOAP) is a method of planning developed by J Orkin for the game F.E.A.R.
 * It can be conceptualized in a few ways - I like to think of it as dynamically calculated FSM
 * as you do not need to explicitly write the state transition table and it is instead calculated at run time
 * by searching through states given a set of actions. In other words GOAP is a state space search algorithm that outputs plans.
 * You can read more about GOAP here: http://alumni.media.mit.edu/~jorkin/goap.html
 *
 * First there is an implementation of A* which is the basis for the state space search
 * I have also implemented simple Cartesian graph search to show the extensibility of the A* implementation
 *
 * The idea with GOAP is that you would have many agents in an environment, and each agent has sensors that update a state that the agent maintains
 * The agents will then be able to formulate a plan of actions, given a goal state and their current state by using the GOAP algorith
 * This plan would then be actuated by actuators which in turn would then affect the environment, causing the sensors to update the agents state
 * This process continues in a feedback loop so the agents should be able to act autonomously within any given environment.
 *
 * In other words, this solution can be used for games, robotics or even abstract problem domains such as shipping systems
 * Where plans must be formulated based on dynamically changing conditions
 *
 * The plans generated by this particular implementation of GOAP are totally ordered
 * In future, work will be undertaken to modify this solution so that it can generate partially ordered plans
 * But that is a much more challenging problem to solve as partially ordered plans would require a completely different approach than A*
 */

/**
 * Searches for the shortest path [from] -> [to] and returns a [Stack] of [AStarNode] representing the path (i.e. this is A*)
 * By applying [heuristic] and [cost] for each evaluated open node to calculate the f cost to the goal
 * This is non greedy BFS so long as [heuristic] is admissible (i.e. never overestimates)
 * For example, in the case of 2D geometric search, the [heuristic] can be considered admissible if it measures euclidean distance
 * In addition [from] and [to] should be part of either an oriented or bi directional graph which can be navigated via calling [neighbours] on a given [AStarNode]
 */
fun<T> path(from: AStarNode<T>,
            to: AStarNode<T>,
            heuristic: ((AStarNode<T>, AStarNode<T>) -> Int),
            cost: ((AStarNode<T>, AStarNode<T>) -> Int)) : Stack<AStarNode<T>> {

    /**
     * Reconstructs a path, represented as a [Stack] of [AStarNode]
     * By updating a pointer to a node until the pointer points at null
     */
    fun reconstructPath(from: AStarNode<T>) : Stack<AStarNode<T>> {
        val path = mutableListOf<AStarNode<T>>()
        var current: AStarNode<T>? = from
        path.add(current!!)
        while (current?.from !== null) {
            path.add(current.from!!)
            current = current.from
        }
        path.reverse()
        return Stack<AStarNode<T>>().apply {
            path.forEach { this.push(it) }
        }
    }

    // Use a priority queue for maintaining the open boundary of the search
    // This means the search will always expand the optimal edge of the border
    val openQueue = PriorityQueue<AStarNode<T>>()

    // Use a hash set for the closed nodes to increase performance on big graphs
    val closedSet = HashSet<AStarNode<T>>()

    // The g cost of the initial node is by definition 0
    from.g = 0

    // The heuristic cost of the initial node is the heuristic function applied to it and the goal
    from.f = heuristic(from, to)

    // Of course, the initial node is the only node on the open border of the search before searching
    openQueue.offer(from)

    // Begin the search
    // While there are still nodes to explore on the open border
    while (!openQueue.isEmpty()) {
        // Get the highest priority node
        val current = openQueue.poll()

        // Check if we've reached the goal node
        if (current == to)
            return reconstructPath(current)

        // Ok, we still need to search
        // Add the node to the closed set so we don't evaluate it again
        closedSet.add(current)

        // For each neighbour of the node calculate it's g cost and update it's from pointer
        current.neighbours().forEach { neighbour ->
            // If the neighbour is in the closed set ignore it
            if (closedSet.contains(neighbour))
                return@forEach

            // Calc a new g score
            val tentativeG = current.g + cost(current, neighbour)

            // Push the neighbour into the open border if it's not already there
            // If it is already there and has a lower g cost then ignore it
            if (!openQueue.contains(neighbour)) {
                openQueue.offer(neighbour)
            } else if (tentativeG >= neighbour.g) {
                return@forEach
            }

            // We've found a shorter path
            // Update the neighbours from pointer and costs
            neighbour.from = current
            neighbour.g = tentativeG
            neighbour.f = neighbour.g + heuristic(neighbour, to)
        }
    }

    // The open border was exhaustively checked, no path exists!
    throw IllegalArgumentException("No path can be found from $from to $to")
}

/**
 * Parameterized type which wraps some [data] along with a pointer to the [from] node and [g] and [f] costs used in A* search
 * The type argument [T] means that A* can be performed for any type as long as there is an admissable heuristic calculable for the type [T]
 */
abstract class AStarNode<T>(val data: T?,
                            var from: AStarNode<T>? = null,
                            var g: Int = Int.MAX_VALUE,
                            var f: Int = Int.MAX_VALUE) : Comparable<AStarNode<T>> {

    /**
     * Returns a [Collection] of neighbour nodes
     * In the case of euclidean nodes this is simply the connected nodes on the graph
     * In the case of non euclidean nodes this could be a function of any number of things
     * For instance, in a state space search, this could return any states which were transition to from valid actions
     */
    abstract fun neighbours() : Collection<AStarNode<T>>

    /**
     * Implemented so these can be used in a priority queue
     */
    override fun compareTo(other: AStarNode<T>): Int {
        return when {
            this.f < other.f -> -1
            this.f > other.f -> 1
            else -> 0
        }
    }
}

/**
 * An implementation of [AStarNode] for cartesian space search
 * A cartesian space search takes place on a 2D plane through a oriented or bi-direction graph of points in space
 * A point in cartesian space is defined by an [x] and a [y] value and, in this case, also has an associated [label]
 */
class CartesianNode(val x: Int,
                    val y: Int,
                    label: String,
                    private val neighbours: MutableCollection<CartesianNode> = mutableListOf()) : AStarNode<String>(label) {

    /**
     * Distance to another node is euclidean and worked out using pythagorean theorem
     */
    fun distanceTo(other: CartesianNode) : Int {
        val dx = abs(this.x - other.x).toDouble()
        val dy = abs(this.y - other.y).toDouble()
        return round(sqrt(dx * dx) + sqrt(dy * dy)).toInt()
    }

    /**
     * Used to add an [other] neighbour
     */
    fun addNeighbour(other: CartesianNode) {
        this.neighbours.add(other)
    }

    /**
     * Implement the neighbours functionality by simply returning an immutable copy of the neighbours list
     */
    override fun neighbours(): Collection<AStarNode<String>> {
        return this.neighbours.toList()
    }

    /**
     * A cartesian node is equal to another one if the coordinates are the same
     */
    override fun equals(other: Any?): Boolean {
        return if (other !is CartesianNode) {
            false
        } else {
            this.x == other.x && this.y == other.y
        }
    }

    /**
     * Implement hash code so this can be used in a hash set
     */
    override fun hashCode(): Int {
        var hash = 7
        hash = 31 * hash + g
        hash = 31 * hash + f
        hash = 31 * hash + data.hashCode()
        return hash
    }
}

/**
 * Wraps [findPath] providing functions for the heuristic and cost in cartesian space
 */
class CartesianPathfinder {
    fun findPath(from: CartesianNode, to: CartesianNode) = path(from, to, { x, y ->
        (x as CartesianNode).distanceTo(y as CartesianNode)
    }, { x, y ->
        (x as CartesianNode).distanceTo(y as CartesianNode)
    })
}

/**
 * An implementation of [AStarNode] for state space search
 * A state space search occurs in an abstract space where points within that space represent states
 * and edges between the point represent actions taken to reach a state from a state
 * A point in state space search is defined by a [worldState] and keep a reference to an [actionPool] of possible [GoapAction]
 * These also keep a reference to the [actionTaken] to reach the state
 */
class GoapNode(val worldState: WorldState,
               private val actionPool: Collection<GoapAction>,
               actionTaken: GoapAction? = null) : AStarNode<GoapAction>(actionTaken) {

    /**
     * Implementation of neighbours for state space search
     * Neighbours in this case are other states which can be reached by applying all possible valid actions to this state
     */
    override fun neighbours(): Collection<AStarNode<GoapAction>> {
        // For all actions in the action pool
        // If they are valid, apply the action to this state, otherwise ignore it
        return actionPool.mapNotNull { action ->
            if (action.isValid(worldState)) {
                GoapNode(worldState.applyAction(action), actionPool, action)
            } else {
                null
            }
        }
    }

    /**
     * Goap nodes are equal if the amount of differences between the states is 0
     */
    override fun equals(other: Any?): Boolean {
        return if (other !is GoapNode) {
            false
        } else {
            this.worldState.countDifferences(other.worldState) == 0
        }
    }

    /**
     * Implement hash code so that these can be used in a hash set
     */
    override fun hashCode(): Int {
        var hash = 7
        hash = 31 * hash + g
        hash = 31 * hash + f
        hash = 31 * hash + data.hashCode()
        return hash
    }
}

/**
 * An action is defined primarily by [preconditions], [postConditions] and a name
 * An action can be applied to a [WorldState] if the given [WorldState] satisifes the actions [preconditions]
 * The result of applying an action to a [WorldState] is the state of the world will be modified by applying the [postConditions] of the action
 * When performing state space search, the action also has procedural checks performed to validate if it is not only statically valid but also dynamically valid
 * This is achieved by running the [isProcedurallyValid] function at plan time (when working out the neighbours of world states)
 * Actions can be also be determined to be dynamically complete via the [isComplete] function and can be executed in an environment using the [execute] function
 */
data class GoapAction(val name: String,
                      val preconditions: Map<String, Boolean>,
                      val postConditions: Map<String, Boolean>,
                      val cost: Int,
                      val isProcedurallyValid: ((GoapAgent) -> Boolean),
                      val isComplete: ((GoapAgent) -> Boolean),
                      val execute: ((GoapAgent) -> Unit))

/**
 * Returns true if an action is valid [forWorldState]
 */
fun GoapAction.isValid(forWorldState: WorldState) : Boolean {
    return forWorldState.isActionValid(this)
}

/**
 * Define the contract for a planning agent
 * This can be implemented for any number of environments
 * Be it games, robotics or any other abstract domain
 */
interface GoapAgent {
    val blackboard: Blackboard
    fun hasPlan(): Boolean
    fun plan()
    fun onActionCompleted(fromAction: GoapAction)
}

/**
 * A world state is simply a [Map] of facts about the world
 * Facts are binary and have an associated name
 * for instance:
 * HasMoney = false
 * HasReachedTarget = true
 */
data class WorldState(val state: Map<String, Boolean>)

/**
 * Returns a [WorldState] by applying [action] to source [WorldState]
 */
fun WorldState.applyAction(action: GoapAction) : WorldState {
    return WorldState(this.state.toMutableMap().apply {
        this.putAll(action.postConditions)
    })
}

/**
 * Returns the number of differences between the source [WorldState] and the [against] state
 */
fun WorldState.countDifferences(against: WorldState) : Int {
    // Fold the against state into an integer representing the differences
    return against.state.keys.fold(0) { acc, key ->
        acc + when (val prop = this.state[key]) {
            null -> 1
            else -> when (prop == against.state[key]) {
                true -> 0
                else -> 1
            }
        }
    }
}

/**
 * Creates a copy of the source [WorldState] with the updated [value] for the given [variable]
 */
fun WorldState.setStateVariable(variable: String, value: Boolean) : WorldState {
    return WorldState(this.state.toMutableMap().apply { this[variable] = value })
}

/**
 * Returns true if the [action] is valid for the source [WorldState]
 */
fun WorldState.isActionValid(action: GoapAction) : Boolean {
    // Fold the actions preconditions into an integer representing the unsatisfied variables
    // And return true if the unsatisfied variables are 0 else false
    return action.preconditions.keys.fold(0) { acc, key ->
        acc + when (val prop = this.state[key]) {
            null -> 1
            else -> {
                when (prop == action.preconditions[key]) {
                    true -> 0
                    else -> 1
                }
            }
        }
    } == 0
}

/**
 * A blackboard maintains a state of the world and has references to sensors and actuators
 * An agent has a reference to a blackboard, which can be though of as the agents central system for sensing, remember and actuating in an environment
 */
class Blackboard(private val world: WorldState) {
    fun updateState(variable: String, value: Boolean) {
        this.world.setStateVariable(variable, value)
    }
}

/**
 * Wraps [path] providing state search specific heuristic and cost functions
 */
class GoapPlanner {
    fun plan(actionPool: Collection<GoapAction>, fromState: WorldState, toState: WorldState) = Stack<GoapAction>().apply {
        this.addAll(
            path(
                GoapNode(fromState, actionPool, null),
                GoapNode(toState, actionPool, null),
                { a, b ->
                    (a as GoapNode).worldState.countDifferences((b as GoapNode).worldState)
                }, { _, b ->
                    (b as GoapNode).data?.cost ?: 0
                }
            ).mapNotNull { goapNode ->
                goapNode.data
            }
        )
    }
}

/**
 * Provides a clean API to execute plans that an [agent] has formulated
 */
class PlanExecutor(private val agent: GoapAgent,
                   private val plan: Stack<GoapAction>) {

    /**
     * Returns true if the plan is not empty
     */
    fun hasPlan() = plan.isNotEmpty()

    /**
     * Checks if the action on top of the stack is complete
     * If it is, it pops the stack
     * It then performs [execute] on the action on top of the stack
     */
    fun execute() {
        if (this.plan.isNotEmpty()) {
            if (this.plan.peek().isComplete(this.agent)) {
                agent.onActionCompleted(this.plan.pop() as GoapAction)
            } else {
                this.plan.peek().execute(this.agent)
            }
        }
    }
}

/**
 * Set of tests for validating the correctness of the GOAP algorithm
 */
class GoapTests {
    @Test
    fun testSimplePath() {
        // Make a 2 node bi-directional graph
        val a = CartesianNode(0, 0, "a")
        val b = CartesianNode(10, 10, "b")
        a.addNeighbour(b)
        b.addNeighbour(a)

        // Create a cartesian pathfinder
        val pathfinder = CartesianPathfinder()

        // Find a path from a -> b
        val path = pathfinder.findPath(a, b)

        // Assert that the path is of length 2
        // And that it goes a -> b
        assertTrue { path.size == 2 }
        assertTrue { path[0] == a }
        assertTrue { path[1] == b }
    }

    @Test
    fun testComplexPath() {
        // Make a more complicated bi-directional graph
        val a = CartesianNode(0, 0, "a")
        val b = CartesianNode(10, 10, "b")
        val c = CartesianNode(20, 10, "c")
        val d = CartesianNode(20, 20, "d")
        val e = CartesianNode(30, 10, "e")

        // Doubly link all the nodes
        a.addNeighbour(b)
        b.addNeighbour(a)
        b.addNeighbour(c)
        b.addNeighbour(d)
        c.addNeighbour(b)
        c.addNeighbour(e)
        d.addNeighbour(b)
        d.addNeighbour(e)
        e.addNeighbour(c)
        e.addNeighbour(d)

        // Create a cartesian pathfindr
        val pathfinder = CartesianPathfinder()

        // Find a path from a -> e
        val path = pathfinder.findPath(a, e)

        // Assert that the path is of length 4
        // And that the path is a -> b -> c -> e
        assertTrue { path.size == 4 }
        assertTrue { path[0] == a }
        assertTrue { path[1] == b }
        assertTrue { path[2] == c }
        assertTrue { path[3] == e }
    }

    @Test
    fun testSimplePlan() {
        // Create an initial state where HasBread is false
        val initialState = WorldState(mutableMapOf(
            Pair("HasBread", false)
        ))

        // Create a desired state where HasBread is true
        val goalState = WorldState(mutableMapOf(
            Pair("HasBread", true)
        ))

        // Create a pool of actions
        // In this case, there is 1 action "GetBread"
        // That has no preconditions and a single postcondition where HasBread becomes true
        val getBreadAction = GoapAction(
            name = "GetBread",
            preconditions = emptyMap(),
            postConditions = mapOf(Pair("HasBread", true)),
            cost = 5,
            isProcedurallyValid = { true },
            isComplete = { true },
            execute = { })

        val actionPool = listOf(getBreadAction)

        // Create a GOAP planner
        val planner = GoapPlanner()

        // Find a plan of actions that take us from the initial state to the desired state
        val plan = planner.plan(actionPool, initialState, goalState)

        assertTrue { plan.size == 1 }
        assertTrue { plan.peek() == getBreadAction }
    }

    @Test
    fun testComplexPlan() {
        // Create an initial state where all variables are false
        val initialState = WorldState(mutableMapOf())

        // Create a desired state where HasToast is true
        val goalState = WorldState(mutableMapOf(
            Pair("HasToast", true)
        ))

        // Define some more complex actions
        // With preconditions and postconditions
        val workForMoneyAction = GoapAction(
            name = "WorkForMoney",
            preconditions = emptyMap(),
            postConditions = mapOf(Pair("HasMoney", true)),
            cost = 5,
            isProcedurallyValid = { true },
            isComplete = { true },
            execute = { })

        val getBreadAction = GoapAction(
            name = "GetBread",
            preconditions = mapOf(Pair("HasMoney", true)),
            postConditions = mapOf(Pair("HasBread", true), Pair("HasMoney", false)),
            cost = 5,
            isProcedurallyValid = { true },
            isComplete = { true },
            execute = { })

        val makeToastAction = GoapAction(
            name = "MakeToast",
            preconditions = mapOf(Pair("HasBread", true)),
            postConditions = mapOf(Pair("HasToast", true), Pair("HasBread", false)),
            cost = 5,
            isProcedurallyValid = { true },
            isComplete =  { true },
            execute = { })

        // Create the action pool
        val actionPool = listOf(
            workForMoneyAction,
            getBreadAction,
            makeToastAction
        )

        // Create the planner
        val planner = GoapPlanner()

        // Find a plan to take us from the initial state to the desired state of having toast
        val plan = planner.plan(actionPool, initialState, goalState)

        // Assert that the plan is of length 3 and has the correct actions in the correct order
        assertTrue { plan.size == 3 }
        assertTrue { plan.pop() == makeToastAction }
        assertTrue { plan.pop() == getBreadAction }
        assertTrue { plan.pop() == workForMoneyAction }
    }

    @Test
    fun testWorldStateDiffWhenStatesAreSame() {
        val a = WorldState(mutableMapOf(
            Pair("HasBread", true)
        ))

        val b = WorldState(mutableMapOf(
            Pair("HasBread", true)
        ))

        assertTrue { a.countDifferences(b) == 0 }
    }

    @Test
    fun testWorldStateDiffWhenStatesAreDifferent() {
        val a = WorldState(mutableMapOf(
            Pair("HasBread", true)
        ))

        val b = WorldState(mutableMapOf(
            Pair("HasBread", false)
        ))

        assertTrue { a.countDifferences(b) == 1 }
    }

    @Test
    fun testWorldStateDiffForDifferingLengthStateMaps() {
        val a = WorldState(mutableMapOf(
            Pair("HasBread", false),
            Pair("HasMoney", true)
        ))

        val b = WorldState(mutableMapOf(
            Pair("HasBread", true)
        ))

        assertTrue { a.countDifferences(b) == 1 }
    }

    @Test
    fun testActionIsNotValidForWorldState() {
        val forState = WorldState(mutableMapOf(
            Pair("HasMoney", false)
        ))

        val action = GoapAction("GetBread", mapOf(Pair("HasMoney", true)), mapOf(Pair("HasBread", true)), 5, { true }, { true }, { })

        assertFalse { action.isValid(forState) }
    }

    @Test
    fun testActionIsValidForWorldState() {
        val forState = WorldState(mutableMapOf(
            Pair("HasMoney", true)
        ))

        val action = GoapAction("GetBread", mapOf(Pair("HasMoney", true)), mapOf(Pair("HasBread", true)), 5, { true }, { true }, { })

        assertTrue { action.isValid(forState) }
    }

    @Test
    fun testMakeToastIsInvalidForHasBreadFalseWorldState() {
        val makeToast = GoapAction("MakeToast", mapOf(Pair("HasBread", true)), mapOf(Pair("HasToast", true), Pair("HasBread", false)), 5, { true }, { true }, { })

        val forState = WorldState(mutableMapOf(
            Pair("HasToast", false),
            Pair("HasBread", false),
            Pair("HasMoney", true)
        ))

        val isValid = makeToast.isValid(forState)

        assertTrue { !isValid }
    }

    @Test
    fun testApplyAction() {
        val initialState = WorldState(mutableMapOf(
            Pair("HasMoney", true)
        ))

        val action = GoapAction("GetBread", mapOf(Pair("HasMoney", true)), mapOf(Pair("HasBread", true)), 5, { true }, { true }, { })

        val expectedWorldState = WorldState(mutableMapOf(
            Pair("HasMoney", true),
            Pair("HasBread", true)
        ))

        val resultingWorldState = initialState.applyAction(action)

        assertTrue { resultingWorldState == expectedWorldState }
    }

    @Test
    fun testGoapNodeNeighboursSimple() {
        val actionPool = listOf(
            GoapAction("WorkForMoney", emptyMap(), mapOf(Pair("HasMoney", true)), 5, { true }, { true }, { }),
            GoapAction("GetBread", mapOf(Pair("HasMoney", true)), mapOf(Pair("HasBread", true), Pair("HasMoney", false)), 5, { true }, { true }, { }),
            GoapAction("MakeToast", mapOf(Pair("HasBread", true)), mapOf(Pair("HasToast", true), Pair("HasBread", false)), 5, { true }, { true }, { })
        )

        val forState = WorldState(mutableMapOf(
            Pair("HasToast", false),
            Pair("HasBread", false),
            Pair("HasMoney", false)
        ))

        val node = GoapNode(forState, actionPool)

        val neighbours = node.neighbours()

        assertTrue { neighbours.size == 1 }
    }

    @Test
    fun testGoapNodeNeighboursComplex() {
        val actionPool = listOf(
            GoapAction("WorkForMoney", emptyMap(), mapOf(Pair("HasMoney", true)), 5, { true }, { true }, { }),
            GoapAction("GetBread", mapOf(Pair("HasMoney", true)), mapOf(Pair("HasBread", true), Pair("HasMoney", false)), 5, { true }, { true }, { }),
            GoapAction("MakeToast", mapOf(Pair("HasBread", true)), mapOf(Pair("HasToast", true), Pair("HasBread", false)), 5, { true }, { true }, { })
        )

        val forState = WorldState(mutableMapOf(
            Pair("HasToast", false),
            Pair("HasBread", false),
            Pair("HasMoney", true)
        ))

        val node = GoapNode(forState, actionPool)

        val neighbours = node.neighbours()

        assertTrue { neighbours.size == 2 }
    }
}

A:

This is quite a lot to analyze, so I will focus only few examples on semantics, best practices and language features.
Naming
Good:

Have a structure
well understandable
not too long

Arguable:
Some of your parameter and field names are way too short.
abstract class AStarNode<T>(val data: T?,
                            var from: AStarNode<T>? = null,
                            var g: Int = Int.MAX_VALUE,
                            var f: Int = Int.MAX_VALUE) : Comparable<AStarNode<T>> {

g, f
fun distanceTo(other: CartesianNode) : Int {
    val dx = abs(this.x - other.x).toDouble()
    val dy = abs(this.y - other.y).toDouble()
    return round(sqrt(dx * dx) + sqrt(dy * dy)).toInt()
}

dx, dy are arguable, because I can understand them through method name.
Comments
Very many of them - although they are well understandable, I'm a fan when the number of code lines is much bigger than the comment lines.
A best practice is to use comments to describe the reason for something not obvious or complex - not the implementation.
Good:
Very good example of yours, where a comment says WHY and not WHAT:
/**
 * Implemented so these can be used in a priority queue
 */
override fun compareTo(other: AStarNode<T>): Int

Arguable:
Many comments could be left out, because ...

they are obvious
// Begin the search

/**
 * Implement hash code so that these can be used in a hash set
 */
override fun hashCode(): Int {
    var hash = 7
    hash = 31 * hash + g
    hash = 31 * hash + f
    hash = 31 * hash + data.hashCode()
    return hash
}

commenting a setter - I don't see any need here for a comment
// The g cost of the initial node is by definition 0
from.g = 0

tell me something I could have figured out in 2 seconds looking into the code
/**
 * A cartesian node is equal to another one if the coordinates are the same
 */
override fun equals(other: Any?): Boolean {
    return if (other !is CartesianNode) {
        false
    } else {
        this.x == other.x && this.y == other.y
    }
}

/**
 * Returns true if the plan is not empty
 */
fun hasPlan() = plan.isNotEmpty()

If you have to explain in the code how your method works (not necessarily classes), its neither well written, nor has it an understandable name.
// For each neighbour of the node calculate it's g cost and update it's from pointer

I strongly believe that comments can, and often do, pollute source code. The goal should be to write the code so well, that it explains itself.
Language features
Good:
Almost nothing to complain about. You seem to get along with kotlin.
Arguable:
Some things are a bit more complex than they could be, or miss some existing helping functionalities:
override fun compareTo(other: AStarNode<T>): Int {
    return when {
        this.f < other.f -> -1
        this.f > other.f -> 1
        else -> 0
    }
}

can be
override fun compareTo(other: AStarNode<T>): Int = this.f.compareTo(other.f)

override fun hashCode(): Int {
    var hash = 7
    hash = 31 * hash + g
    hash = 31 * hash + f
    hash = 31 * hash + data.hashCode()
    return hash
}

can be
 override fun hashCode(): Int = HashCodeBuilder(13,17)
        .append(g)
        .append(f)
        .append(data)
        .toHashCode()

Code readability
Good:

Very small classes
Well written to the ability of being testable
Good and rare usage of interfaces and inheritance
You wrote tests - this is already a big win

Arguble:
While your classes remain small and beautiful, some of your methods don't follow the same example.
Method inside a method: extract it. A Method usually has to do one thing and not create another one - quite unusual implementation I haven't seen so far:
fun<T> path(from: AStarNode<T>,
        to: AStarNode<T>,
        heuristic: ((AStarNode<T>, AStarNode<T>) -> Int),
        cost: ((AStarNode<T>, AStarNode<T>) -> Int)) : Stack<AStarNode<T>> {

/**
 * Reconstructs a path, represented as a [Stack] of [AStarNode]
 * By updating a pointer to a node until the pointer points at null
 */
fun reconstructPath(from: AStarNode<T>) : Stack<AStarNode<T>> {

Very long method: extract the functionality into other functions / classes. The first method in the example has ~100 lines!
fun<T> path(...)

When the called instance / method has many parameters, it is always better to use named params - like here:
class GoapPlanner {
fun plan(actionPool: Collection<GoapAction>, fromState: WorldState, toState: WorldState) = Stack<GoapAction>().apply {
    this.addAll(
            path(
                    GoapNode(fromState, actionPool, null),
                    GoapNode(toState, actionPool, null),
                    { a, b ->
                        (a as GoapNode).worldState.countDifferences((b as GoapNode).worldState)
                    }, { _, b ->
                (b as GoapNode).data?.cost ?: 0
            }
            ).mapNotNull { goapNode ->
                goapNode.data
            }
    )
}

Tests
Good:

Short
Have comments
Initialisation uses with named params

Arguable:

Much duplication for objects and parameters. Its better to define some fields to be used by other tests, which are not that important, but are needed e.g. for initialisation.
Pair("HasBread", true)

Pair("HasMoney", true)

Weird assertions
assertTrue { !isValid }

Assertions which will tell nothing valuable when they fail
assertTrue { resultingWorldState == expectedWorldState }

The error message would be something like "Expected to be true, but was false". This is worthless! You need to debug to find out WHY they are not equal.
There are plenty of methods and other libraries which offer so much better solutions, like AssertJ. There you could write
assertThat(resultingWorldState).isEqualTo(expectedWorldState)

and when it fails, it would tell you what was expected, what is the result and what is the difference - much more information.
Or here:
    // Assert that the plan is of length 3 and has the correct actions in the correct order
    assertTrue { plan.size == 3 }
    assertTrue { plan.pop() == makeToastAction }
    assertTrue { plan.pop() == getBreadAction }
    assertTrue { plan.pop() == workForMoneyAction }

When any of this fails, you don't know which one (besides the exception on line xy), what was the real value, what is the difference?
Naming
Yes, here we are again. The names of a test are allowed to be longer than usual and should be very explainable. Names like testSimplePath,testComplexPath, testComplexPath, .. tell me nothing!
Companies have often their own patterns and standards on test names, but my advice would be to start every test with the word 'should'. Like: should return true, when property xy is bigger than zero.
A test should be as simple as it can be and as explainable as it is possible. This includes the name where you can define your case in prose. BTW: You can use backticks to have a function name with spaces in between.

Thanks for reading and I hope I could give you some advice which is actually valuable.
The END


Q:

Why I am getting this error "rows inserted or updated at the subscriber cannot be outside the article partition"?

When I insert rows at the subscriber end I get following error
rows inserted or updated at the subscriber cannot be outside the article partition
Why I am getting this error? How to resolve it.

A:

This error occurs when article filtering is being used and an inserted row is outside the Subscriber's partition.  When using filtering, you must ensure that inserts and updates at the Subscriber do not result in rows that fall outside the partition of the Subscriber.
Check your article filtering criteria and adjust your application logic accordingly so that inserted rows are inside a given Subscriber's partition.


Q:

Digital control stability for more than impulse response stability?

I have a digital control system which is described by the transfer function
$$
Y(z) = \frac{-\beta}{z - 1 + k \beta} X(z)
$$
where \$\beta\$ is a real parameter I can adjust to modify the characteristics of the system, and \$k\$ is a positive real constant.
Using the BIBO stability criteria that the poles must be inside the unit circle, this means that for BIBO stability I need
$$
0 < k \beta < 2
$$
which is exactly what I observe when \$x[n]\$ is an impulse response:
$$
x[n] = \begin{cases}0 & n < 0\\
x_0 & n \ge 0\end{cases}
$$
However, I am trying to design my system to handle "arbitrary" inputs. For example, in the above example suppose I have an input which jumps between two values:
$$x[n] =
\begin{cases}
x_0 & n~\text{is even}\\
-x_0 & n~\text{is odd}
\end{cases}
$$
The z-transform for this particular input is
$$
X(z) = x_0 \frac{1 - \frac{\cos(\pi)}{z}}{1 - \frac{2 \cos(\pi)}{z} + \frac{1}{z^2}} =
x_0 \frac{z (z + 1)}{z^2 + 2 z + 1}
$$
If I try to simulate the system with this input, for \$k \beta > 1\$, \$y[n]\$ actually tends towards \$\pm \infty\$ (oscillating), which I would consider unstable, or at the very least unacceptable.
How would I go about analyzing (and designing) a control system when I have to consider other possible input responses than just the basic impulse response? Are there any useful search terms I could use for solving this type of problem?

A:

There might be a problem with your simulation, because for an oscillating input signal (with constant amplitude), the output is also an oscillating signal with constant amplitude, as long as the system is stable, i.e., as long as \$0<k\beta <2\$ is satisfied.
For the given oscillating input signal, the output is given by
$$y[n]=\frac{\beta x_0}{2-k\beta}(-1)^n,\qquad 0<k\beta<2\tag{1}$$
Of course, if the input is switched on at some finite point in time, there will be transients before the output approaches \$(1)\$, but these transients will decay as long as the stability condition \$0<k\beta <2\$ is satisfied.
For values of \$k\beta\$ close to \$2\$ you might be observing the transient, which will increase in amplitude for quite a while, but the output will finally settle at its maximum amplitude \$\beta/(2-k\beta)\$, which can be quite large for values of \$k\beta\$ close to \$2\$.
The figure below shows the output for an oscillating input signal (\$x_0=1\$) starting at \$n=0\$, and for two different values of \$k\beta\$:


Q:

How can I cons the result of two different list filters?

I have a list of Objects of type Leaf(char: Char, weight: Int).I am trying to filter through a List of leaves and insert a new leaf so that the list of Leaves is ordered by weight. The new Leaf gets its values from a list of Pairs that I am iterating through
  def makeOrderedLeafList(freqs: List[(Char, Int)]): List[Leaf] = {

  def orderedLeafList(freqs: List[(Char, Int)], leaves: List[Leaf] ): List[Leaf] = {
    freqs match  {
      //Problem on line below
      case head::tail => orderedLeafList(tail, leaves.filter( _.weight < head._2) :: Leaf(head._1, head._2) :: leaves.filter( _.weight > head._2))
      case _ => leaves
    }
  }
orderedLeafList(freqs,  List())
}

The problem I get on the specified line is Type mismatch, expected List[Huffman.Leaf], actual: List[Product with Serializable] when I try to cons the results of the filters. I should be able to cons the result of a filter should I not? I'm new to scala but have done functional programming.

A:

Use ::: instead of :: to concatenate two lists. :: combines an X with a List[X].
def makeOrderedLeafList(freqs: List[(Char, Int)]): List[Leaf] = {

  def orderedLeafList(freqs: List[(Char, Int)], leaves: List[Leaf] ): List[Leaf] = {
    freqs match  {
      //Problem on line below
      case head::tail => orderedLeafList(tail, leaves.filter( _.weight < head._2) ::: Leaf(head._1, head._2) :: leaves.filter( _.weight > head._2))
      case _ => leaves
    }
  }
  orderedLeafList(freqs,  List())
}

The reason you get that strange error message is that you can actually add a List[Leaf] as a single element to the head of a List[Leaf] and get something like: List(List(leaf1, leaf2), leaf3, leaf4, leaf5). The resulting type is the common supertype of Leaf and List[Leaf], which is Product with Serializable.


Q:

how to restore access to MySQL after deleting all privileges?

Ok, I know I'm stupid. I deleted all privileges to MySQL, I have access to root account on host. Is there any way to add account to mysql?

A:

First of all stop mysql & backup /var/lib/mysql or wherever the data files are on your system.
Then from a clean mysql install elsewhere tar up /var/lib/mysql/mysql and put it on the broken system.
Then re-add your users & permissions.
Of course if you have backed up the mysql database you can do this more quickly.


Q:

How to forbid a specific package to be installed?

Can I configure Ubuntu to never install a specific package even if it is required by another package I install?

A:

As in Debian we can use apt-pinning for version and installation control in Ubuntu too.
To block the installation of a given package we may put the following lines in /etc/apt/preferences
Package: <nameofpackage>
Pin: origin ""
Pin-Priority: -1

By giving a negative priority for this pin we will block the installation of <nameofpackage> from not further specified origin, i.e. our local repository. Of course we can use apt-pinning to pin a certain package version or specific origin.
Before you proceed it is strongly recommended to read the documentation given above and the manpage from apt_preferences because errors in these files are not checked by apt and if they occur may break your package management.
For an alternative, and to prevent updating of a given package see:

How to prevent updating of a specific package?

A:

I have a package that keeps sneaking back in and breaking git
sudo apt-mark hold libgnutls-deb0-28

should prevent that package from being installed

A:

In debian you can block a package, and that package wont upgrade anymore
# echo name_of_package hold | dpkg --set-selections

but I'm not sure that you can forbid


Q:

Launching safari with an image or saving to camera roll issues

I've downloaded an image from a web service and either need to open the image within safari or save it to the camera roll. I've tried to open the image in Safari, but safari doesn't open.
var safari = UIApplication.SharedApplication;
var uri = new NSUrl(path); // where the image is saved to
safari.OpenUrl(uri);

This compiles, but Safari doesn't launch
The code I have for saving to the camera roll is this
PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() =>
{
      using (var pool3 = new NSAutoreleasePool())
      {                                     pool3.InvokeOnMainThread(delegate ()
           {                                                               PHAssetChangeRequest.FromImage((UIImage)UIImage.FromFile(path));
           });
      }
      }, (t, err) =>
      {
           if (!t)
           {
                 using (var pool1 = new NSAutoreleasePool())
                 {
                      pool1.InvokeOnMainThread(delegate () {
                           var alert = new UIAlertView("Error saving file", "An error has occured saving your photo to the camera roll", null, "OK");
                          alert.Show();
                          };
           }
           else
           {
                 using (var pool2 = new NSAutoreleasePool())
                 {
                       pool2.InvokeOnMainThread(delegate (){
                            var alert = new UIAlertView("Image saved", "Your image has been saved to the camera roll", null, "OK");
                            alert.Show();
                            });
                        };
                 }
         });

which crashes and burns (the correct permissions have been set)
I'm at a loss as to why neither of these work as they seem to be correct.

A:

You can't open a local path with safari, that isn't allowed on iOS (apps are sandboxed) so you'll need to use either a remote URL or have your own UIWebView or WKWebView or a SFSafariViewController to display that image in a safari like experience. Here is a blog post in the Xamarin Site about the subject.
Also here is a nice recipe in the Xamarin site to save a photo into the camera roll, you can do your own solution based on it.
Hope this helps!


Q:

How Can I Overwrite a List Variable Using Azure DevOps REST API?

If I want to queue a build using AzureDevops with overwritten variables, I have to pass a parameters string:
{   "definition" : { "id" : [BUILD_ID] },
    "parameters" : str(variables_to_overwrite)
}

where variables_to_overwrite is a dictionary like so:
variables_to_overwrite = {
       "list_1" : str( ['A', 'B', 'C'] )
       "list_2" : str( ['D', 'E'] )
    }

If I don't cast these lists as strings, the build will not queue. I print out params before queuing the build and they look correct:
{'definition': {'id': [BUILD_ID},
 'parameters': '{\'list_1\': "\'[\'A\', \'B\', \'C\']\'", \'list_2\': "\'[\'D\', \'E\']\'}'

but when I have the build print out the arguments it sees, it prints:
'--list_1', "'['A", "B',", "'C"]'", '--list_2', "'['D", "E']'"

As you can see, the single and double quotes have become quite mixed up, which means programs that parse args don't see this as two args, but seven!
I tried force-replacing all the double quotes with single quotes, but when I do that, the build won't queue. I even tried rewriting it like so:
{'definition': {'id': [BUILD_ID},
 'parameters': '{\'list_1\': \'[\'A\', \'B\', \'C\']\', \'list_2\': \'[\'D\', \'E\']\'}'

But when I get back the build result, it has done the same thing of adding in double-quotes mixed up with single quotes (in exactly the same way as previously described).
How can I prevent DevOps from destroying the quote pairing in things like lists and dicts that are passed as parameters? I have tried every permutation I can think of, including manually wrapping it in quotes, replacing quotes, using json.dumps, etc. Nothing works. The only way to get the build to queue is to pass a string, and no matter what quote inputs it gets, whether escaped or not, devOps goes through and replaces all quotes with a single-quote, double-quote pattern.

A:

After lengthy trial and error, I determined that Azure DevOps requires that lists intended for overwriting have this format:
'[]',
'"[\'A\', \'B\']"'

That is to say, single-quote, double-quote, bracket, escaped single quotes inside the list, bracket, double-quote, single-quote. Quote styles cannot be interchanged and the escape character is required. Any deviation will result in the problem described in the question.
This is pretty much impossible to do in Python using str(). However, it can be done using repr().
When defining variables_to_overwrite, do not cast any lists to string (as the question shows). Instead, leave them as lists and then perform the following sort of replacement:
if variables_to_overwrite:
    for key in variables_to_overwrite:
        value = variables_to_overwrite[key]
        if type(value) == list:
            variables_to_overwrite[key] = '"' + repr(value) + '"'   # THIS FORMAT IS CRUCIAL

Finally, define your parameters:
params = {
    "definition": {
        "id": build_id
    },
    "parameters" : str(variables_to_overwrite)   # THIS IS THE ONLY PLACE TO USE STR()
}

This will convert the list into the weird string format Azure DevOps requires and prevent DevOps from mangling the quotes.


Q:

Android Import library error DefaultGroovyMavenDeveloper

I'm a newbie android app developer using android studio, and I am trying to use sticky list headers from https://github.com/emilsjolander/StickyListHeaders. I do this by File -> New -> Import Module and I add the dependency. However I am getting the error
Error:No such property: GROUP for class: org.gradle.api.publication.maven.internal.deployer.DefaultGroovyMavenDeployer

My project build.gradle is:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "testingapp.dylanzammit.com.anothernewproj"
        minSdkVersion 21
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'se.emilsjolander:stickylistheaders:2.7.0'
}

A:

If you want to add the libraries to your project in Android studio, you can do it in three different ways. Please read this link https://stackoverflow.com/a/35369267/5475941. In this post I explained how to import your JAR files in Android studio and I explained all possible ways step by step with screenshots. I hope it helps.


Q:

Which one is better for getting the last row of my table with linq to nhibernate?

Which one is better for getting the last row of my table with linq to nhibernate? Why?
    internal Bill GetLastBill()
    {
        var q = from b in session.Linq<Bill>()
                select b;

        return q.OrderByDescending(x => x.Id).First();
    }

OR
    internal Bill GetLastBill()
    {
        long maxId = session.Linq<Bill>().Max(i => i.Id);

        var q = from b in session.Linq<Bill>()
                where b.Id == maxId
                select b;

        return q.First();
    }

A:

Have you considered:
return session.Linq<Bill>().Last();

MSDN Reference

A:

Of your two choices the first options is better because it does 1 query.   Second option will execute 2 queries.


Q:

How to let ImageView partial overlap with 2 Buttons?

I would like to achieve below result i.e. one imageview in between and overlap with 2 buttons, but I have no luck after few days of trying and searching.
Many thank if you can help on this.

<LinearLayout
    android:id="@+id/fragment_busmain_triplacegroup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/fragment_busmain_tripbtngroup"
    android:layout_centerHorizontal="true"
    android:orientation="vertical"
    android:padding="10dp"
    android:weightSum="2">

    <android.support.design.widget.TextInputLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">

        <EditText
            android:id="@+id/fragment_busmain_departfrom"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="@string/From"></EditText>
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">

        <EditText
            android:id="@+id/fragment_busmain_departto"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="@string/To"></EditText>
    </android.support.design.widget.TextInputLayout>
</LinearLayout>

A:

Try using a RelativeLayout instead and add the ImageView below the first text view and give it a negative margin half its height.
<RelativeLayout
    android:id="@+id/fragment_busmain_triplacegroup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/fragment_busmain_tripbtngroup"
    android:padding="10dp">

    <android.support.design.widget.TextInputLayout
        android:id="@id/from"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/fragment_busmain_departfrom"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="@string/From"/>
    </android.support.design.widget.TextInputLayout>

    <ImageView
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_below="@id/from"
        android:src="@drawable/upDownArrow"
        android:layout_marginBottom="-15dp"/>

    <android.support.design.widget.TextInputLayout
        android:id="@id/to"
        android:layout_below="@id/from"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/fragment_busmain_departto"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="@string/To"></EditText>
    </android.support.design.widget.TextInputLayout>
</RelativeLayout>


Q:

Getting help of R function using help_console function from noamtools R package

I can get help in R 3.1.2 on Yates function from FrF2 package through:
?FrF2::Yates

Now I want to get help in .tex format through help_console function from noamtools R package. I tried this code but not working:
help_console(topic="Yates", format = "latex")

and
help_console(topic="FrF2:Yates", format = "latex")

The noamtools Rpackage can be obtained fromgithub` using the following commands:
library(devtools)
install_github("noamtools", "noamross")
library(noamtools)

A:

The issue here is in the function help from the base package utils. You have two packages that are both exporting a function with the same name. Specifically, DoE.base and FrF2 both export Yates, so help doesn't load an Rd file; instead, it wants you to choose between different files. But help_console doesn't know how to handle this. This can be easily corrected by adding a package argument to help_console that passes a package name down to help. To create achieve this in a particular R session, you can use:
fixInNamespace("help_console", "noamtools")

to load a script editor where you can change the definition of help_console to the following:
function (topic, format = c("text", "html", "latex", "Rd"), lines = NULL,
    before = NULL, after = NULL, package = NULL)
{
    format = match.arg(format)
    if (!is.character(topic))
        topic <- deparse(substitute(topic))
    helpfile = utils:::.getHelpFile(help(topic, package = (package)))
    hs <- capture.output(switch(format, text = tools:::Rd2txt(helpfile),
        html = tools:::Rd2HTML(helpfile), latex = tools:::Rd2latex(helpfile),
        Rd = tools:::prepare_Rd(helpfile)))
    if (!is.null(lines))
        hs <- hs[lines]
    hs <- c(before, hs, after)
    cat(hs, sep = "\n")
    invisible(hs)
}

This will then allow you to separately capture the documentation for each version of the function:
str(capture.output(help_console(topic="Yates", format = "latex", package="FrF2")))
## chr [1:139] "\\HeaderA{utilitiesCat}{ \\textasciitilde{}\\textasciitilde{} Internal utility functions and a user-visible constant for workin"| __truncated__ ...
str(capture.output(help_console(topic="Yates", format = "latex", package="DoE.base")))
## chr [1:65] "\\HeaderA{block.catlg3}{Catalogues for blocking full factorial 2-level and 3-level designs,  and lists of generating columns fo"| __truncated__ ...

In order to get this incorporated into noamtools, I've issued a pull request for this to be changed. You can see it here on GitHub. It has now been merged in the main repo on GitHub, so you can install as you normally would.


Q:

Getting and storing position of PanoramaView before changing VC

I'm trying to learn Google Map API and i'm building an app that have two UIViewController. Root UIViewController loads a Google Street View Panorama as shown below:
@IBOutlet weak var viewStreet: UIView!
var panoView: GMSPanoramaView!

override func viewDidLoad() {
    super.viewDidLoad()

    let panoView = GMSPanoramaView(frame: CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height))
    panoView.delegate = self
    panoView.moveNearCoordinate(CLLocationCoordinate2D(latitude: -33.732, longitude: 150.312))

    viewStreet.addSubview(panoView)
    viewStreet.sendSubviewToBack(panoView)
 }

I have added a UIButton that loads another UIViewController, and I'm willing to add a "Back" button to get back to the first one. Using segues it works fine but  panoView is always loaded at  latitude: -33.732, longitude: 150.312, as i have initializated it. What i'm trying to achieve is getting back to the lat/long of the last panorama loaded before switching to the second VC, for instance:
viewDidLoad -> lat. x1, long. y1;
moving to another panorama -> lat. x2, long. y2;
changing UIViewController;
back to root VC, panorama lat. and long. should be (x2, y2).
Using didMoveToPanorama method i can get panoID every time PanoramaView changes, the problem is storing it when VC changes. May i use NSUserDefaults or is there a better way? Here is code:
 func panoramaView(view: GMSPanoramaView, didMoveToPanorama panorama: GMSPanorama?) {
    panoID = panorama!.panoramaID
}

Note that method didMoveToPanorama:nearCoordinate: can't be used since it is called only when Panorama has moved due to moveNearCoordinate
On a side note, i've edited title cause it was misleading, and improved post with further informations.

A:

I've found an easier way to achieve this:
In Main.storyboard: Show segue to "SecondViewController"
In SecondViewController.swift:
@IBAction func backToPreviousVC(sender: AnyObject) {
    dismissViewControllerAnimated(true, completion: nil)
}

This way viewDidLoad is not called and it get back to the last panorama seen.


Q:

MVC 3 does not render editor template for object

I have an MVC 3 application which should allow the user to display and edit values of different types. The view responsible for doing this does not neccessarily know about the type of the value (it is declared as object), but I want it to render the correct editor template. Right now I have this:
<%: Html.EditorFor(n => attribute.ValueTyped) %>

attribute.ValueTyped is of type object. When ValueTyped is of type bool, MVC renders a check box (which is what it is supposed to do). However, as soon as ValueTyped is of a different type (so far I've tried int, double, string), MVC does not render anything at all.
How do I make MVC render the generic templates for int, double, string or whatever type my ValueTyped contains? Please note: I do not want to generate the text boxes myself, but I'd rather let MVC decide which editor template to use.

A:

You could try to pass the name of the editor template explicitly by passing it as the second argument. Based on your dynamic situation this could look like the following:
<%: Html.EditorFor(m => attr.ValueTyped, attr.ValueTyped.GetType().Name) %>

Of course, your question is quite old - maybe you could update it with the answer you found?


Q:

Is there a practical guide to Team Software Process?

I have seen the Carnegie Mellon site covering TSP.  I am looking for a practical, non-academic guide to application of TSP in the real world.  I would really like to know, how does TSP reduce bugs?

A:

If you aren't familiar with the Personal Software Process (PSP), I'd start with Watts Humphrey's book PSP: A Self-Improvement Guide for Software Engineers. This book is geared for practitioners looking to apply the PSP in their job. It also begins to introduce the Team Software Process (TSP) in the later chapters. A very brief, high level introduction to the PSP can also be found in Introduction to the Personal Software Process, also by Watts Humphrey. Although I don't own them, the canonical books on the Team Software Process are Introduction to the Team Software Process (a high level overview to get started), TSP: Leading a Development Team, and TSP: Coaching Development Teams. Since you've mentioned the TSP website, you've probably already seen the Team Software Process Technical Report along with other reports published by the Software Engineering Institute about the TSP.
The PSP, and by extension, the TSP, reduce defects by introducing a repeatable, quantatively measured process. The TSP calls for a team (or teams) of PSP-trained engineers working together on a larger project. In order to understand how the TSP reduces defects, you need to first employ the PSP to reduce defects on an individual level by gaining insight and making adjustments to the individual process.
At PSP0, you begin making measurements to help understand how you current build software - size, time, number of defects, and so on. The act of simply recording data and analyzing it can provide insights into which life cycle phases are most problematic for the individual, either by individual data elements or some combination of them.
PSP1 doesn't add any quality aspects, but does improve estimation. There might be a quality improvement here since you have a greater understanding of how you use your time and can allocate and utilize time more efficiently. Even though you don't use this data until PSP2, you start tracking it now to have a historical record to start with. Being able to know if you need to spend more time on a particular aspect of the product life cycle or if time is being wasted might help you improve process quality, if not also product quality.
In PSP2, you add reviews in order to prevent and remove defects. You also add process improvement - utilizing your measurements and estimations, as well as recording where defects happen. By taking your time, size, defect, and estimation data, as well as defect injection data newly added, you can answer more questions. Relationships form between program size and defect rates, time spent in reviews versus defect rates, and so on. Using this allows you to act (as an example, if you're spending a long time in reviews, yet many defects are escaping to the next phase, there's a problem with how you conduct reviews).
The Team Software Process takes a team of engineers all utilizing PSP, scales it up, and adds management-level tasks to coordinate their interactions and explore measurements and metrics relevant to a team of software developers rather than just at an individual level. The ability to identify relevant measurements and metrics and then apply them to identify weaknesses in the process is the whole point of both the TSP and PSP.


Q:

Why is Meteor using imports in 1.3 tutorial

Why is Meteor using imports in 1.3 tutorial - it makes it harder to managed than before which I think is totally against the grain for what they wanted to accomplish from the start? Can I run files from 1.2 with 1.3? What are the advantages with the new file system, it's not clear in the tutorial? Thanks!

A:

What are the advantages with the new file system?
In the near term:

Module support gives you the ability to control your file load order. E.g. no more prepending numbers to file names, adding nested lib directories, and using packages where you otherwise wouldn't.

In the long term (meteor 1.4+):

Module support enables a number of future optimizations including code splitting, hot module reloading, and incremental rebuilding. See this discussion for more details.

Can I run files from 1.2 with 1.3?
Yes, the imports directory is optional. You can upgrade to 1.3 without using it. See this answer from Zoltan for more details.


Q:

Reused UIWebView showing previous loaded content for a brief second on iPhone

In one of my apps I reuse a webview. Each time the user enters a certain view on reload cached data to the webview using the method :-

- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)baseURL

and I wait for the callback call

- (void) webViewDidFinishLoad:(UIWebView *)webView.

In the mean time I hide the webview and show a 'loading' label.
Only when I receive webViewDidFinishLoad do I show the webview.
Many times what happens I see the previous data that was loaded to the webview for a brief second before the new data I loaded kicks in.
I already added a delay of 0.2 seconds before showing the webview but it didn't help.
Instead of solving this by adding more time to the delay does anyone know how to solve this issue or maybe clear old data from a webview without release and allocating it every time?

A:

Thanks malaki1974, in my case I wasn't using a modal view.
When I sat with an Apple engineer on WWDC 2010 and asked him this question his answer was simply: "Don't reuse UIWebViews, that's not how they were ment to be used."
Since then I make sure to calls this set of lines before allocating a new UIWebView
[self.myWebView removeFromSuperview];
self.myWebView.delegate = nil;
[self.myWebView stopLoading];
[self.myWebView release];

That solved the issue.

A:

Clear the contents of the webview before you try to load new content
[self loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];


Q:

Why does .NET read values of unaffected properties on reception of INotifyPropertyChanged.PropertyChanged event?

I'm new to data binding and encountered the following oddity today which I fail to understand:
I have a form with two labels (labelA and labelB) and two buttons (buttonA and buttonB).
The form hosts an object (called "formState") with two properties (CountA and CountB).
labelA.Text is data-bound to formState.CountA,
labelB.Text is data-bound to formState.CountB.
When buttonA is pressed, it makes formState raise the PropertyChange event with "CountA" as property name.
When buttonB is pressed, it raises formState.PropertyChange with "CountB" as property name.
I would expect that only labelA gets updated when buttonA is pressed, and only labelB gets updated when buttonB is pressed. However, both labels are updated when I press any button. I can see this because the CountA and CountB properties increment and return a counter each time their values are read. Code below.
Does anyone have an explanation for this behavior?
public partial class Form1 : Form
{
    private FormState formState = new FormState();

    public Form1()
    {
        InitializeComponent();

        labelA.DataBindings.Add(
            new Binding("Text", formState, "CountA"));

        labelB.DataBindings.Add(
            new Binding("Text", formState, "CountB"));
    }

    private void buttonA_Click(object sender, EventArgs e)
    {
        formState.raisePropertyChangedEvent("CountA");
        // both labelA and labelB get updated - why not just labelA?
    }

    private void buttonB_Click(object sender, EventArgs e)
    {
        formState.raisePropertyChangedEvent("CountB");
        // both labelA and labelB get updated - why not just labelB?
    }

    public class FormState : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private int countA = 0;
        private int countB = 0;

        public int CountA
        {
            get { return ++countA; }
        }

        public int CountB
        {
            get { return ++countB; }
        }

        public void raisePropertyChangedEvent(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

A:

It may be a naive consumer of observable objects. Naive consumers of INotifyPropertyChangedObjects may ignore the property name and just reevaluate the whole thing. One might imagine the class looking like:
class NaiveConsumer
{
   void Foo(INotifyPropertyChanged observable)
   {
       observable.PropertyChanged += PropertyChangedHandler;
   }

   void PropertyChangedHandler(object sender, PropertyChangedEventArgs e)
   {
      // Evaluate all properties, even though only 1 prop changed.
      this.NameTextBox.Text = observable.Name;
      this.AgeTextBox.Text = observable.Age;
   }
}


Q:

Overide inline font face?

Im importing an XML feed which has inline styles applied to its divs like:
 face="Verdana"

I want to override this with CSS. Ive tried this:
#containing-div div {
    font-family: arial !important;
}

But its not working. As 'face' is deprecated I'd hoped it would be overridden with the 'font-family' but it appears not to be. Given that I can't change the XML feed (I know I should be able to but just trust me!), how can I override this?
Thanks

A:

Assuming that this:
face="Verdana"

is actually this:
..

(and it must be, right? There's no way it's
)
then you should use this CSS:
#containing-div, #containing-div font {
    font-family: arial;
}

There should be no need for !important. The point is to select the font elements.


Q:

Complex Analysis - Cauchy Principal Value of Improper Integral

I am having some difficulty with a P.V. Cauchy Integral problem, and after working on it for hours, I just cannot seem to find what I might be doing wrong.
Here is the problem:
Evaluate the Cauchy principal value of the given improper integral:
$$\int_{-\infty}^{\infty} \frac{1}{(x^2+4)^2} dx$$
My attempt at the problem is below:
Let $$f(z)=\frac{1}{(z^2+4)^2}=\frac{1}{(z+2i)^2(z-2i)^2}$$
Then:
$$\int_{-R}^{R}\frac{dx}{(x^2+4)^2} + \int_{C_R}\frac{dz}{(z^2+4)^2}=2 \pi i \left ( \operatorname*{Res}_{z=2i}\left ( \frac{1}{(z^2+4)^2} \right ) + \operatorname*{Res}_{z=-2i}\left ( \frac{1}{(z^2+4)^2} \right )\right )$$
$$=2 \pi i \left ( \operatorname*{Res}_{z=2i}\left ( \frac{1/(z+2i)^2}{(z-2i)^2} \right ) + \operatorname*{Res}_{z=-2i}\left ( \frac{1/(z-2i)^2}{(z+2i)^2} \right )\right )$$
Now, let $$\frac{p_1(z)}{q_1(z)}=\frac{1/(z+2i)^2}{(z-2i)^2} \text{and let} \frac{p_2(z)}{q_2(z)}=\frac{1/(z-2i)^2}{(z+2i)^2}$$
Then, we see that
$$p_1(2i)=\frac{1}{(4i)^2}\neq 0$$
$$q_1(2i)=(2i-2i)^2=0$$
$$q_1\prime(2i)=2(2i-2i)=0$$
Since $q_1\prime(2i)$ is not nonzero, we know that $\frac{p_1(z)}{q_1(z)}$ is not a simple pole.
So
$$\operatorname*{Res}_{z=2i}\left ( \frac{1/(z+2i)^2}{(z-2i)^2} \right )=\lim_{z\to2i}\left ( \frac{\mathrm{d} }{\mathrm{d} z} \left ( (z-2i)^2*\frac{1/(z+2i)^2}{(z-2i)^2} \right )\right )$$
$$=\lim_{z\to2i}\left ( \frac{\mathrm{d} }{\mathrm{d} z} \left ( \frac{1}{(z+2i)^2} \right )\right )$$
$$=\lim_{z\to 2i}\left ( -\frac{2}{(z+2i)^3} \right )$$
$$=-\frac{2}{(4i)^3}$$
Similarly,
$$\operatorname*{Res}_{z=-2i}\left ( \frac{p_2(z)}{q_2(z)} \right )=\operatorname*{Res}_{z=-2i}\left ( \frac{1/(z-2i)^2}{(z+2i)^2} \right )=\lim_{z\to-2i}\left ( \frac{\mathrm{d} }{\mathrm{d} z} \left ( (z+2i)^2*\frac{1/(z-2i)^2}{(z+2i)^2} \right )\right )$$
$$=\lim_{z\to-2i}\left ( \frac{\mathrm{d} }{\mathrm{d} z} \left ( \frac{1}{(z-2i)^2} \right )\right )$$
$$=\lim_{z\to -2i}\left ( -\frac{2}{(z-2i)^3} \right )$$
$$=-\frac{2}{(-4i)^3}$$
So finally,
$$\int_{-R}^{R}\frac{dx}{(x^2+4)^2} + \int_{C_R}\frac{dz}{(z^2+4)^2}=2 \pi i \left ( -\frac{2}{(4i)^3}-\frac{2}{(-4i)^3} \right )=0$$
So,
$$\int_{-R}^{R}\frac{dx}{(x^2+4)^2} =0- \int_{C_R}\frac{dz}{(z^2+4)^2}$$
$$=-\left ( \int_{C_1}\frac{1/(z+2i)^2}{(z-2i)^2}dz+\int_{C_2}\frac{1/(z-2i)^2}{(z+2i)^2}dz \right )$$
where $C_1$ contains the point $z=2i$ and $C_2$ contains the point $z=-2i$.
$$=-\left (2\pi i\left ( \frac{1}{(2i+2i)^2} \right )+2\pi i\left ( \frac{1}{(-2i-2i)^2} \right )  \right )$$
$$=-\frac{2\pi i}{(4i)^2}-\frac{2\pi i}{(-4i)^2}$$
$$=\frac{\pi i}{4}$$
The final answer should be $\frac{\pi}{16}$, however, which I cannot seem to get.
Any help is greatly appreciated!

A:

You should get $2\pi i \ Res(f(z)|_{z=2i} = 2\pi i \frac{d}{dz} \frac{1}{(z+2i)^2}|_{z=2i} = 2\pi i \frac{-2}{(4i)^3} = 2\pi i \frac{-2}{-64i} = \frac{\pi}{16}$.


Q:

how can do the join in M:N relationship with linq fluent?

In my database three tables:

TableA(IDTableA,...)
TableAB(IDTableA, IDTableB,...)
TableB(IDTableB,...)

In my entity model I have only two entities:
TableA
{
    long IDTableA;
    ICollection<TableB> TableB;
}

TableB
{
    long IDTableB;
    ICollection<TableA> TableA;
}

I would like to know hou can do the join between the both tables and a condition in the where, something like this:
select TableA.*
from TableA, TableB, TableAB
where TableA.IDTableA = TableAB-IDTableAB
and TableB.IDTableB = TableAB.TableB
and Table.MyField > 10

I know know how can do it with query syntax, but I would like to know the wat to do it with linq fluent.
Thanks.

A:

Answer hint from:
How to join with an or clause in Fluent LINQ
Fluent syntax
var qJoin = context.User.SelectMany(
    u => context.Hierarchy
         .Where(h => u.OrganisationId == h.OrganisationId)
         ,(u, h) => new { u, h });

Query syntax
var qJoin = from u in context.User
         from h in context.Hierarchy
         where u.OrganisationId == h.OrganisationId
         select new { u, h };