Software – Being Brunel http://www.beingbrunel.com The Civil Engineering Blog Sat, 20 Aug 2016 15:22:38 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.10 http://www.beingbrunel.com/wp-content/uploads/2016/05/cropped-being-brunel-512-1-50x50.png Software – Being Brunel http://www.beingbrunel.com 32 32 Python for Engineers: Part 3 http://www.beingbrunel.com/python-engineers-part-3/ http://www.beingbrunel.com/python-engineers-part-3/#respond Mon, 27 Jun 2016 11:30:40 +0000 http://www.beingbrunel.com/?p=4226 Being Brunel | The Civil Engineering Blog

It's about time we did some more Python. Who's excited? In the last couple of posts I've helped you literally get started by setting up a Python environment and then set you down the road of variables and in/output. And we could stop there; it's enough functionality to write pretty much...Read More

The post Python for Engineers: Part 3 appeared first on Being Brunel.

]]>
Being Brunel | The Civil Engineering Blog

It’s about time we did some more Python. Who’s excited? In the last couple of posts I’ve helped you literally get started by setting up a Python environment and then set you down the road of variables and in/output. And we could stop there; it’s enough functionality to write pretty much anything- but it’ll be a long and painful process that none of us will enjoy. So instead let’s continue tooling up.

Touching on Modules

For today’s lesson we’re going to be coping with the effective length of our column, defined as such:

  • L_{braced} = 0.5 L_{clear} \sqrt{ \frac{1 + k_t }{ 0.45 + k_t } \frac{1 + k_b}{ 0.45 + k_b } }
  • L_{unbraced} = L_{clear} \sqrt{ \frac{1 + 10 k_t k_b }{ k_t + k_b } } \lor L_{clear} \sqrt{ ( 1 + \frac{k_t}{1 + k+t} ) ( 1 + \frac{k_b}{1+k_b} )}

Before we do anything exciting, we’re going to write out these equations in Python. This presents us with a bit of a challenge, because while Python will merrily evaluate brackets and the four standard operators (+-/*), it doesn’t inherently know how to square root.

While we could roll our own square root algorithm using primitive mathematics, I personally feel life is too short. So instead we’re going to call upon the math module. I’m not going to dwell too much on how modules work, at the moment, but instead just introduce you to the concept. A module is a chunk of reusable functionality. In the case of the math module, this functionality is (unsurprisingly) mainly mathematical.

To use a module in Python you need to import it. This tells Python that you want it to go a fetch all the functionality of a named module and bring it in to your program. To let us perform square roots we’re going to be using the sqrt function from the math module. To make code easier to read, Python programmers tend to respect the convention of putting all import statements at the start of a file- so at the top of our rccol.py we want to add import math.

Now we have a square root up our sleeve we can finally put in our braced and unbraced lengths calculations:

import math

l_clear = 7000
k_top = 0.1
k_bot = 0.1

braced = 0.5*l_clear * math.sqrt((1 + k_top/(0.45+k_top)) * (1 + k_bot/(0.45+k_top)))
unbraced = l_clear * max(math.sqrt(1 + 10*k_top*k_bot/(k_top+k_bot)), (1 + k_top/(1+k_top)) * (1 + k_bot/(1+k_bot)))

There’s a few things here. Firstly, note that when using the sqrt function from the math module, we use it’s full name (math.sqrt). The . notation is a way of saying “from” or “that belongs to” in Python. So math.sqrt means, the function sqrt from the math module we imported. The second is my cheeky use of the max() function- this works exactly as it does in Excel, it picks the maximum of two numbers. Note that max() is a built-in function- that is; it’s something you don’t have to import from a module.

Being Conditional

Our column is either going to be braced or unbraced. It’s not going to be both. Therefore we don’t really need to calculate the effective length for both conditions. And thus, it’s time to break out the control flow. These are the statements we use to control the flow of the program– getting it to loop and repeat things a certain amount of time, jump out and run through code defined elsewhere in a function, or branch depending on specific conditions.

In this situation, we need an if statement; if the column is braced then return one value, if it is unbraced then return another. In Python an if statement looks like this:

if customer_name == "James Bond":
    martini = "shaken, not stirred."
else:
    martini = "on fire."

In the above example, our Python Publican has specific instructions: if the customer is called James Bond, then serve a Martini to the classic standard. Or else, if it isn’t James Bond, just set fire to the Martini.

This example also introduces you to some of the finer points of Python. Firstly, did you notice that when I compared customer_name to "James Bond" I used ==? This is because the meaning of a single equals (=) is already taken; it means assign a value to a variable. That means that we have to use something else of equality, and in Python (and the majority of programming languages, in fact) that is ==.

Secondly, did you spot the indentation? What is done for each condition is indented one level. Normally this is just good programming practice, because it makes it easier for you to see what bits of code are dependent on another. However Python is sensitive to white space- for example, it doesn’t know you’ve finished your else until you stop intending your lines. Now is also a good time to point out a Python quirk- indent with either spaces or tabs; doing both in one file will cause errors (spaces are the reigning champion).

OK- so now we have the fantastic if statement, it’s time to use it:

import math

l_clear = float(input("Clear height: "))
k_top = float(input("k (top): "))
k_bot = float(input("k (base): "))
braced = input("Braced? (yes/no): ")

if braced == "yes":
    l_eff = 0.5*l_clear * math.sqrt((1 + k_top/(0.45+k_top)) * (1 + k_bot/(0.45+k_top)))
else:
    l_eff = l_clear * max(math.sqrt(1 + 10*k_top*k_bot/(k_top+k_bot)), (1 + k_top/(1+k_top)) * (1 + k_bot/(1+k_bot)))

print("Effective Length = ")
print(l_eff)

Now when you run the program you get asked to input a few key properties of the column, and asked if it’s braced or not. You then get the effective length appropriate to the support condition of your column. And perhaps more subtly, it means that our program can just use the variable l_eff (effective length), without having to constantly keep testing braced to see if it should be using the effective length of a un/braced column.


Knowing how to load in and use modules is going to open up a lot of pre-written functionality to us, and save us quite a bit of time. In later posts it’s also going to allow us to start spreading our program out across multiple files by writing our own modules. Similarly, writing anything that isn’t completely trivial without being able to set variables to different values depending on specific conditions is pretty awful. However there’s still a good few tools left to add to our inventory before we can really tackle this column designer, so stay tuned…

I’m going to talk about GitHub a bit later on, but if you want to have a look at the “finished” code from this tutorial, checkout:

https://github.com/thomasmichaelwallace/rccol

The post Python for Engineers: Part 3 appeared first on Being Brunel.

]]>
http://www.beingbrunel.com/python-engineers-part-3/feed/ 0
Building A Web App Part 5: Code Complete http://www.beingbrunel.com/building-web-app-part-5-code-complete/ http://www.beingbrunel.com/building-web-app-part-5-code-complete/#respond Tue, 21 Jun 2016 17:40:24 +0000 http://www.beingbrunel.com/?p=4396 Being Brunel | The Civil Engineering Blog

The only thing missing from our amazing prototype web application (to match built environment professionals in Slack channels by their interests), is some actual functionality. We've got...Read More

The post Building A Web App Part 5: Code Complete appeared first on Being Brunel.

]]>
Being Brunel | The Civil Engineering Blog

The only thing missing from our amazing prototype web application (to match built environment professionals to Slack channels by their interests), is some actual functionality. We’ve got to the point where we have a lovely static interface, but it doesn’t matter how hard you click to select any interests- nothing changes. In the final post of this mini-series we’re going to plug in that functionality.

Redux Modules

The only piece of the stack we haven’t used so far is Redux. Redux is responsible for the store. The store represents the data within our application. It will maintain a list of all the available interests and channels, listen for when a user clicks on an interest to de/select it and then update the list of relevant channels accordingly. And to make things easy, we’re going to do it all in one file, ./app/redux/channelFinder.js:

import { createAction, handleActions } from 'redux-actions';
import { connect } from 'react-redux';

const TOOGLE_INTEREST = 'networkBe/channelFinder/TOOGLE_INTEREST';
const toogleInterest = createAction(TOOGLE_INTEREST, interest => interest);

const allInterests = [
  'politics', 'sustainability', 'technical design', 'materials', 'books', 'iot',
  'bim', 'cities', 'diversity', 'generational gaps', 'health and wellbeing',
  'construction', 'digital engineering', 'meet-ups', 'modular design', 'engagement',
];
const allChannels = [
  { name: '#chat-bim', interests: ['bim', 'digital engineering'] },
  { name: '#chat-cities', interests: ['digital engineering', 'cities', 'iot'] },
  { name: '#chat-diversity', interests: ['diversity', 'engagement'] },
  { name: '#chat-generationgame', interests: ['generational gaps'] },
  { name: '#chat-health-wellbeing', interests: ['health and wellbeing', 'diversity'] },
  { name: '#chat-miffed', interests: ['meet-ups'] },
  { name: '#chat-playdates', interests: ['meet-ups'] },
  { name: '#chat-politics', interests: ['politics'] },
  { name: '#chat-sustainability', interests: ['sustainability', 'cities', 'materials'] },
  { name: '#chat-technical', interests: ['technical design', 'construction', 'modular design'] },
  { name: '#meets-general', interests: ['meet-ups'] },
  { name: '#twitter-book-club', interests: ['books'] },
];

export default handleActions({
  [TOOGLE_INTEREST]: (state, action) => {
    const selected = state.selected.includes(action.payload)
      ? [...state.selected.slice(0, state.selected.indexOf(action.payload)),
        ... state.selected.splice(state.selected.indexOf(action.payload) + 1)]
      : [action.payload, ...state.selected];
    const channels = allChannels
      .filter(c => c.interests.some(i => selected.includes(i)))
      .map(c => c.name);
    return { ...state, selected, channels };
  },
}, { interests: allInterests, selected: [], channels: [] });

const mapStateToProps = (state) => ({
  ...state,
});
const mapDispatchToProps = (dispatch) => ({
  toogleInterest: (interest) => dispatch(toogleInterest(interest)),
});
export const connectChannelFinder = connect(mapStateToProps, mapDispatchToProps);

There’s a lot going on here. The very first thing we do is define our one any only action, the action of toggling an interest between selected and unselected. In the Redux pattern, every action is represented by a unique identifier (networkBe/channelfinder/TOOGLE_INTEREST). This identifier, along with any payload (in our case the interest that wants toggling), is wrapped up in something called a Flux Standard Action; a way of collecting together this information. I mentioned, when we were building the stack, that we’ll be using createAction from redux-actions to save us having to write a function that generates a Flux Standard Action.

As we’re going to be doing all the computation on the client (i.e. we’re not going to have a clever server), the next bit of the code outlines all the possible interests for the user to select from, and all the channels available. The channel definitions set out which interests trigger the channel to be selected. For example, selecting ‘diversity‘ will prompt a recommendation of the ‘#chat-diversity‘ and ‘#chat-health-wellbeing‘ channels. As the web app is developed some of this logic will be moved server side; but for now we’ll keep it simple and on the client.

The next section is what Redux calls a Reducer. It takes the state (the interests, selected interests, and channels) the application is currently in and an action to apply, and returns a new state with the action applied. So in the case of our single ‘toggle interest’ action: the interests available (which will never change), the selected interests (which need to be updated to include/remove an interest; depending on whether or not it’s already been selected), and the relevant channels (which need to be updated to match the newly selected interest). The handleActions section also takes responsibility for setting the initial state; nothing selected, no channels recommended.

Finally we define how the state and the actions are accessed by our ChannelFinder container. In our case our state exactly matches the parameter inputs into the container (interests, selected, channels), so we can just pass it along. We also need to pass in our toggleInterest action so that our ChannelFinder will be able to dispatch (the Redux term) the toggle action that will de/select interests. The react-redux library provides us with a connect() function, which we can setup and then export for use on the container (ChannelFinder) to wire it into the reducer.

  • Dux – a methodology for writing Redux modules.

Wiring In Containers

As promised, we need to update our current ‘dumb’ container code (./app/containers/channelFinder.js) to make it smart:

import React from 'react';
import InterestPicker from '../components/InterestPicker';
import ChannelList from '../components/ChannelList';
import { connectChannelFinder } from '../redux/channelFinder';

const contentStyle = {
  maxWidth: 800,
  margin: 'auto',
};

const channelFinder = ({ interests, selected, channels, toogleInterest }) => (
  <div style={contentStyle}>
    <h1>Channel Finder.</h1>
    <InterestPicker
      interests={interests}
      selected={selected}
      toggle={toogleInterest}
    />
    <ChannelList channels={channels} />
  </div>
);
channelFinder.propTypes = {
  interests: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
  selected: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
  channels: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
  toogleInterest: React.PropTypes.func.isRequired,
};
export default connectChannelFinder(channelFinder);

Note how we’ve dropped the defaultProps property, and instead wrapped our returned channelFinder component in the connect function we exported in our ./app/redux/channelFinder.js module. We no longer need the default properties to be set, because we’re actually passing data in now. The connect function developed in our module will take the state/dispatcher and transform it in the interests, selected, channels and toggleInterest parameters for us. This relatively modest change is all that was needed to make our ‘component’ into a true container.

Finally we need to add Redux into our bootstrap, so update ./app/app.js:

import React from 'react';
import { Provider } from 'react-redux';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import ChannelFinder from './containers/ChannelFinder';

const app = ({ store }) => (
  <Provider store={store}>
    <MuiThemeProvider muiTheme={getMuiTheme()}>
      <ChannelFinder />
    </MuiThemeProvider>
  </Provider>
);
app.propTypes = {
  store: React.PropTypes.object.isRequired,
};
export default app;

And ./app/index.js:

import React from 'react';
import { render } from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
import { createStore } from 'redux';
import Reducer from './redux/channelFinder';
import App from './app';

injectTapEventPlugin();

const store = createStore(Reducer);
const app = (<App store={store} />);

const root = document.getElementById('content');

render(app, root);

In index.js we now create the store from our channelFinder reducer (using Redux’s createStore function). We then pass that as a newly added parameter to our app.js root component. This has been updated to use the <Provider> component from react-redux, which is responsible for giving the connect function (used in our <ChannelFinder /> container) the correct store to connect to.

Finally we have a working application- run npm test and you’ll see that we pass our behaviour test. Once you’re satisfied, run npm start to start the server and browse to http://localhost:3000. Behold the finished product, now with working buttons. We’ve finally delivered our prototype.

 


This has been a whistle stop tour of a fairly large amount of functionality, and as I said at the beginning- I don’t really expect anyone to follow this all unless they already know it. But hopefully it’s given you an outline of the process of creating a web application, and introduced you to a solid stack for you to master. Throughout this mini-series I’ve been listing out resources- I now recommend you go back and get to grips with those bits of the stack, or aspects of the language, that you don’t know- now you have a feel for how they fit in to the whole process.

You can find the working prototype here:

https://github.com/thomasmichaelwallace/network-be

This post is part of a five post mini-series on building a web app: Part 1, Part 2, Part 3, Part 4, Part 5.

The post Building A Web App Part 5: Code Complete appeared first on Being Brunel.

]]>
http://www.beingbrunel.com/building-web-app-part-5-code-complete/feed/ 0
Building A Web App Part 4: Writing Code http://www.beingbrunel.com/building-web-app-part-4-writing-code/ http://www.beingbrunel.com/building-web-app-part-4-writing-code/#respond Tue, 21 Jun 2016 17:39:30 +0000 http://www.beingbrunel.com/?p=4391 Being Brunel | The Civil Engineering Blog

In the last, fairly epic, post I walked you through the stack we're going to be using for this web application that will unite all you built environment professionals. What we haven't got, yet, is something that will actually run; just a...Read More

The post Building A Web App Part 4: Writing Code appeared first on Being Brunel.

]]>
Being Brunel | The Civil Engineering Blog

In the last, fairly epic, post of this mini-series I walked you through the stack we’re going to be using for this web application that will unite all you built environment professionals. What we haven’t got, yet, is something that will actually run; just a lot of tools, libraries and configuration. By the end of this post we’re going to have a static prototype. How’s that for fun?

Bootstrapping

Before we can start writing our functional code we need to provide an entry point. For a website, that’s an HTML page that the browser will download and render. If the site is actually a web application, then that HTML will point to a JavaScript file that will load in all the framework files, libraries and then actually start our app going. This is called bootstrapping.

From the configuration of our application, we said that when it started it should use webpack to compile our application starting with a few key files. Those were ./app/index.html and ./app/index.js. These two files are going to be our bootstrap, they’re going to provide a page that will start the browser loading the JavaScript (index.html), and then pull in the framework and libraries and actually start the web application (index.js).

The application code (i.e. the JavaScript) is going to handle actually rendering our application, so our landing/bootstrap HTML just wants to be as simple as possible:

<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>network-be</title>

  <link href='https://fonts.googleapis.com/css?family=Roboto:400,300,500' rel='stylesheet' type='text/css'>
  <style>
    body {
     color: #333;
     font-family: 'Roboto';
    }
    h1 {
     font-weight: lighter;
     font-size: 50px; 
    }
    h2 {
     font-weight: lighter;
     font-size: 25px;
    }
  </style>
 </head>
 <body role="application">

  <!-- view -->
  <div id="content">
   <p/>Loading, Ready, Run...</p>
  </div>
  <!-- /view -->

 </body>
</html>

This is a fairly minimal HTML page. It starts with the preamble about how the page is encoded, how it should be viewed on various devices, and the title that should be shown in the browser tab/window. The next section deals with some simple styling. First we pull in the Material Design font (called Roboto) from the GoogleFonts API. Then we use some inline CSS (a language for styling) to say that we want all our fonts to be slightly off black, in Roboto, and we want our headings (h1 and h2) to be light-weight (the opposite of bold). Finally we create a space for our application (<div id="content" />); this will be replaced by whatever the JavaScript renders once it has loaded.

You might notice that there is nothing in this HTML to actually load the scripts. This is because this file will be compiled through webpack and the links to the generated JavaScript will be injected at the end of the file (thanks to the HTMLWebpackPlugin section of our configuration). If we hadn’t of being doing it this way then we would have had to have added <script /> tags to the end of our body. However, if something can be automated easily- it probably should be.

Next up comes the JavaScript (./app/index.js):

import React from 'react';
import { render } from 'react-dom';

const app = (<p>Hello World</p>);
const root = document.getElementById('content');

render(app, root);

This script will create the world’s least inspiring application- something that just shows the words “Hello World“. However all we’re doing at the moment is creating our entry point- the actual functionality is yet to come. In this file we’re importing the React framework, and the render function from the React DOM library (the DOM is a technical name for the system that lays out pages in a browser). We’re then defining our app as a paragraph element saying “Hello World” and then locating the section in index.html (the document that this script is called from) that has been labeled ‘content’ (which we’ll call the application’s root element- the place that it starts). Finally we’re using the render function to render our app into the root element.

Congratulations, we’re now bootstrapped. You can finally run npm start, browse to http://localhost:3000 and you’ll be shown the uninspiring words “Hello World.” Once you’re bored, press ctrl+c in your terminal to stop the server running.

Testing

Good tests are tests that are written before you write the functionality. This is because you’re specifying what the behaviour should be, not verifying that what you implemented did what you thought it should. The procedure most developers follow is this: write a failing test (because there’s no functionality), implement the functionality to the point the test passes, then refactor, tidy, and verify you haven’t broken the test. This is called the red, green, refactor system.

You’re going to have to bare with me now, because this next bit requires a bit of a leap of faith. We’re going to create test for our one behaviour we outlined (Given a list of interests, When a user selects interests, Then a list of appropriate channels should be shown.) To keep things organised we’re going to put our specifications in a separate folder, so in the file ./app/specs/channelFinder.spec.js we’ll write the following:

import React from 'react';
import { mount } from 'enzyme';
import { createStore } from 'redux';
import Reducer from '../redux/channelFinder';
import App from '../app';

describe('A channel finder', () => {
  it('should show a list of matching channels when a user picks an interest', () => {
    const wrapper = mount(<App store={createStore(Reducer)} />);

    let suggestedChannels = wrapper.find('channelList').find('ListItem');
    expect(suggestedChannels.length).toEqual(0);

    const construction = wrapper.findWhere(i => i.props().label === 'construction');
    construction.props().onTouchTap();

    suggestedChannels = wrapper.find('channelList').find('ListItem');
    expect(suggestedChannels.length).toEqual(1);
  });
});

I know what you’re thinking: “how the hell did you come up with that?”. Let’s talk through it. Firstly, I’ve taken a punt at what my components are going to be called (I can always come back and change this test). I’ve said that this whole unit that collects interests and returns channel names is called a “channel finder”, that the list of channels will be a channelList, and that it each item in that list will be a ListItem, that construction will be an interest and it’ll only have one channel associated with it.

Knowing my assumptions, hopefully the test starts to become a bit clearer. It verifies that no channels are currently selected, finds an interest called construction and then clicks on it (called a tap, to be generic across desktops and phones). Finally, it verifies that, after tapping on an interest, the list of suggested channels now includes something. Possibly the most cryptic bit at the start is where we mount this app component with a store. That’ll be explained in the next post; for now you’ll just have to trust me that this is the line needed to create our application.

Just one thing I want to mention about this test, is that it is an intergration test; it tests how the application functions as a whole. It’s also very brittle, which is not ideal. Consider- this test will break if construction has more than one channel associated with it; which is not an indication that the behaviour of the application has changed. I’ve thrown together this test quickly because I’m just using it as a helpful way of telling “if I’m there yet” when I’m writing this prototype. As the program evolves, so will your tests- from development aides to ways of proving the system against accidental change.

We can now run our test using the npm test command we setup last time. As we have absolutely none of this implemented, your test will fail. Like the server, press ctrl+c to close the test suite. However, it’s not uncommon to leave it continuously testing, so that you get notified immediately once you’ve achieved your goal.

Components

So now we have a way of getting our application started, and verifying that we’ve delivered on our intentions, let’s take this a little further than “Hello World”. Different frameworks lead to different development styles. For React/Redux, it makes sense to create a static version of your website from the inside out, and then wire in the functionality. This is because it’s component based (to make a channel finder, you need a interest picker and a channel list first), and functional (in this case that means: the graphical interface is independent of the behaviour of the system).

We’re going to create two new directories: ./app/components and ./app/containers. In React/Redux terminology, a component is something that takes some inputs and renders something (sometimes called dumb components), while a container (also called a smart component) fetches data, interprets it and passes that down to the components. The idea is that components are not specific to the data you’re using; like the difference between a line and a drawing- a line can be used anywhere, but your drawing represents one thing only.

First, let’s create our component that will allow people to pick interets (./app/components/InterestPicker.js):

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';

const buttonStyle = {
  marginRight: 10,
  marginBottom: 10,
};

const interestPicker = ({ interests, selected, toggle }) => (
  <div>
    <h2>What interests you?</h2>
    {interests.map((i, n) => (
      <RaisedButton
        key={n}
        label={i}
        primary={selected.includes(i)}
        style={buttonStyle}
        onTouchTap={() => toggle(i)} 
      />
    ))}
  </div>
);
interestPicker.propTypes = {
  interests: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
  selected: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
  toggle: React.PropTypes.func.isRequired,
};
export default interestPicker;

This file really showcases how React works. We create a component (interestPicker) that takes three parameters: a list of interests, a list of interests that the user has selected, and ‘a way’ of toggling if an interest is selected. It then returns a block to be rendered with a header inviting people to answer “What interests you?”, and a set of buttons (RaisedButton from Material UI). Each of those buttons is labeled with an interest, is set to be coloured (or primary in the language of Material Design) if said interest in in the list of selected interests, and is linked to a function (toggle) that will be called when it’s tapped.

Our Channel List (./app/component/ChannelList) is in a similar vain, but even simpler:

import React from 'react';
import { List, ListItem } from 'material-ui/List';
import SocialGroupAdd from 'material-ui/svg-icons/social/group-add';

const channelList = ({ channels }) => (
  <List>
    <h2>You should checkout:</h2>
    {channels.length > 0
      ? channels.map((c, n) => (
        <ListItem key={n} primaryText={c} leftIcon={<SocialGroupAdd />} />
      ))
      : (<p>Nothing yet. Please pick a few more interests.</p>)
    }
  </List>
);
channelList.propTypes = {
  channels: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
};
export default channelList;

All the Channel List takes is a list of channels. It then outputs a block with a header (“You should checkout:”) and either a list of all the channels (with a nice icon) or a prompt (“Nothing yet. Please pick a few more interests.”) if there are no channels. If you take anything away from this; appreciate the simplicity of the React ‘data in – render out’; this is called a stateless component. Stateless components are ridiculously easy to read and test, as they mimic mathematical functions– you know that if you pass Channel List a list of three channels it’ll show them; there’s no setting up, no creating an object and then calling methods to move it into the right state, it’s just a simple map between inputs and outputs.

Wiring in a Static View

Technically we’ve hit a point where we have to implement a container. However it’s helpful practice to implement your container as a component first. That is, instead of worrying about writing the routines to fetch and interpret data- just create something that pass in some unchanging, sample, data. Aside from giving us a way to visually check the web app looks like we were expecting, it is also trivial to wire this in to the data when we promote it to being a proper container.

So let’s write our static version of ./app/containers/ChannelFinder.js:

import React from 'react';
import InterestPicker from '../components/InterestPicker';
import ChannelList from '../components/ChannelList';

const contentStyle = {
  maxWidth: 800,
  margin: 'auto',
};

const channelFinder = ({ interests, selected, channels, toogleInterest }) => (
  <div style={contentStyle}>
    <h1>Channel Finder.</h1>
    <InterestPicker
      interests={interests}
      selected={selected}
      toggle={toogleInterest}
    />
    <ChannelList channels={channels} />
  </div>
);
channelFinder.propTypes = {
  interests: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
  selected: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
  channels: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
  toogleInterest: React.PropTypes.func.isRequired,
};
channelFinder.defaultProps = {
  interests: ['digital engineering', 'eurocodes', 'construction', 'digital engineering', 'eurocodes', 'construction', 'digital engineering', 'eurocodes', 'construction', 'digital engineering', 'eurocodes', 'construction', 'digital engineering', 'eurocodes', 'construction', 'digital engineering', 'eurocodes', 'construction', 'digital engineering', 'eurocodes', 'construction'],
  selected: ['eurocodes'],
  channels: ['Colours and those that love them.', 'People that like cat.'],
  toggleInterest: () => {},
};
export default channelFinder;

The container code looks a lot like a standard component. We’re taking in all the data from our application (the interests, those that are selected, the channels suggested, and the function to toggle interest selections), and then passing them down the specific components that deal with each. The only difference is that we’re supplying the values to be rendered (in the defaultProps object) as well. In this case I’ve thrown a few interests together (although I’ve repeated them because making up data is boring), said that ‘eurocodes’ are selected, and put in a few channels. In the next post we’ll take this out and wire in a back end, but it’ll do for now.

Finally we’re going to connect this into the bootstrap. Material UI requires us to set a theming context- used to decide what colour, size, etc. every component included within it will be. It also needs us to load in the tap-event plugin before we start rendering. To make this process a bit tidier we’re going to split our bootstrap up. We’ll keep ./app/index.js as the process of creating the app component and rendering it into our root element on the page. But we’re going to move the definition of our app component into a separate file: ./app/App.js:

import React from 'react';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import ChannelFinder from './containers/ChannelFinder';

const app = () => (
  <MuiThemeProvider muiTheme={getMuiTheme()}>
    <ChannelFinder />
  </MuiThemeProvider>
);
export default app;

And updating our ./app/index.js:

import React from 'react';
import { render } from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
import App from './App';

injectTapEventPlugin();

const app = (<App />);
const root = document.getElementById('content');

render(app, root);

This keeps our index.js clean from the ‘noise’ introduced by having to wrap our Channel Finder in the MuiThemeProvider elements used by Material UI to set the themeing. This separation will also be helpful in the next post where we’ll need to introduce some Redux elements too.

Once again our app is in a working state, and when we start the server (npm start) and browse to our site (http://localhost:3000) we’ll see a nice cloud of tags and a list of channels. Nothing will happen if we click on them (and if you’ve got npm test still running you’ll see that we haven’t passed our test yet), but it verifies that your interface is sound.


A clear idea of a minimum viable prototype, what we’re doing, what it’ll look like, how it’ll behave; a stack built and a working (but not interactive) interface- we’re doing pretty good. Although we’re on our fourth post now, it’s worth noting that once you’ve invested the time in learning- something like this will take you no more than afternoon. And once you’ve got a few stacks under your belt you’ll find you pick them up a lot quicker- as with music, there’s nothing original out there.

This post is part of a five post mini-series on building a web app: Part 1, Part 2, Part 3, Part 4, Part 5.

The post Building A Web App Part 4: Writing Code appeared first on Being Brunel.

]]>
http://www.beingbrunel.com/building-web-app-part-4-writing-code/feed/ 0
Building A Web App Part 3: Tooling Up http://www.beingbrunel.com/building-web-app-part-3-tooling/ http://www.beingbrunel.com/building-web-app-part-3-tooling/#comments Tue, 21 Jun 2016 17:38:14 +0000 http://www.beingbrunel.com/?p=4387 Being Brunel | The Civil Engineering Blog

So we know what we're going to write, what it's going to look like, and what it needs to do before we can throw it to the wolves for comments. This post continues my weekend journey into prototyping...Read More

The post Building A Web App Part 3: Tooling Up appeared first on Being Brunel.

]]>
Being Brunel | The Civil Engineering Blog

So we know what we’re going to write, what it’s going to look like, and what it needs to do before we can throw it to the wolves for comments. This post continues my weekend journey into prototyping a web app that will eventually connect built environment professionals together; if you’re coming to this new then you should probably skip back to the beginning.

Finally, it’s nearly time to write some code. However, one does not simply write code. Before we go anywhere we’re going to have to select and build the stack on top of which we’ll build our web application. Theoretically this step is optional- you could write your own language, compiler; devise your own framework and tools; come up with your own design metaphors and algorithms. Life is short, and we’re supposed to be rapidly prototyping- so instead we’re going to use a stack of languages, tools and frameworks that other people have written to save a lot of boilerplate.

We’re going to be using a react + redux + webpack stack.

This is going to be a long article. Know this- you don’t have to become an expert in every one of the technologies I’m listing out here, but you should invest a little time becoming familiar with them if you plan to do any significant coding of you own.

Node.js

Node began its life as a way of writing web servers in JavaScript. However, when it comes down to it, it’s just a very good way of executing JavaScript outside of a browser. In fact, it’s become a touch ubiquitous (see next), so while we’re not actually going to write any server code for this application, we’re still going to need to go fetch node.

npm

The Node Package Manager (npm) is the real reason why node is at the bottom of this stack. The success of node means that npm offers us access to quarter of a million libraries and frameworks (code written and maintained by someone else). It also provides us with a standardised way of describing, and managing these dependencies in our prototype application. npm comes bundled with node, so there’s no need to download anything else at this point.

Right, so now we’re going to take our first step to actually writing this app. From the terminal, make a new folder for the project and run the command npm init. The gives us a guided way of creating the package.json file that describes the project. After answering some questions we’ve generated our first file, our ./package.json:

{
  "name": "network-be",
  "version": "1.0.0",
  "description": "A web application to connect people working in the built environment based on their interests.",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/thomasmichaelwallace/network-be.git"
  },
  "keywords": [
    "network",
    "built-enviornment"
  ],
  "author": "[email protected]",
  "license": "MIT"
}

Now that we’ve initialised our project (by creating a folder and making a default package.json file), we can start installing packages.

Babel

JavaScript is a funny language. Having nothing to do with Java, it owes much of its success to being in the right place at the right time. And that means that it’s a language with more than its fair share of flaws- typically languages thrive on being good and easy to develop specific solutions to specific problems on; rather than just being what you have to use if you want to write for a browser.

The various committees that control the language, however, are doing their best to improve the situation, leading to a language that is rapidly evolving. Unfortunately it’s evolving a touch too rapidly for your average browser to keep up- let alone your typical user who may not even be able to update Chrome on a daily basis.

Babel solves this problem by letting us write using the latest JavaScript syntax and features and then transpiling (like translating) them back into something older browsers can understand. Out of the box all babel can do is take a JavaScript file, interpret it, and then spit back out exactly the same file. Babel’s strength is in it’s plug-in system, which allows it the parse the file through multiple plugins that transform the output. This makes babel incredibly versatile, but a touch confusing for the uninitiated. So to use babel, we’ll need to install it, and several plug-ins (called presets) using npm:

npm install --save-dev babel-core babel-preset-es2015 babel-preset-stage-2 babel-preset-react

This command installs the core babel functionality, and the presets it needs to transform the latest version of Javascript (called ES2015), the second stage of the proposed future changes for JavaScript (called Stage 2; ‘draft proposals’), and the special language used by React (called JSX, discussed later). The --save-dev means that the packages will be added as development dependencies to the package.json. This is because you only need babel when you’re developing; you don’t need to give all your users the compiler, just the compiled code.

Now we’ve installed babel we need to configure it; it’s not enough just to install the presets, we have to explicitly tell babel we want it to use them. To do that we need to create a .babelrc file in our project directory specifying an array of presets to push and transform our source through (in json format):

{
  "presets": ["es2015", "stage-2", "react"]
}

Webpack

Using babel compounds a problem that using node modules introduces. Suddenly it’s not enough to just point our browser at a JavaScript file and say ‘run this’. The program needs to be transpiled by babel first, and then all the files it relies on that have been pulled in by npm. And while we could just manually run babel every time we wanted to run/test our app, and keep a diligent list of all the files we needed to copy in and reference- life is too short.

There’s been a whole plethora of tools created to fix this problem; so much so that they actually became a problem of their own. Even tutorials from last year will have you downloading 3 or 4 tools and chaining them together with each other. Thankfully the internet seems to have settled on using npm for module/package management and a tool called webpack for getting your program from well organised source files into a nice minimal package to send to the browser.

Once again webpack is only needed for development; the compiled files it produces are all we actually need to give the client, so we’re going to install and save this as a development dependency:

npm install --save-dev webpack babel-loader html-webpack-plugin webpack-dev-server

As with babel, webpack is extensible; it uses plugins to make its functionality. In the language of webpack we are going to use a babel loader. That just means that when it reads our source code, it’ll load it by putting it through the babel transformation for us. We’re also going to use the html-webpack plugin, which will handle generating and injecting the lines of code that tell the browser to load in our JavaScript into our web page for us. Finally, I’ve included the webpack development server, which provides us with a quick and easy way to continuously compile our code and serve it up to the browser as we’re making changes to it.

And just like babel, webpack won’t do anything unless we’ve put together a configuration file, so in webpack.config.js we need to put the following:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './app/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '/js/bundle.js',
  },
  devtool: 'source-map',
  resolve: {
    extensions: ['', '.js'],
    root: __dirname,
  },
  module: {
    loaders: [{
      test: /\.js$/,
      loader: 'babel',
      include: path.resolve(__dirname, 'app'),
    }],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './app/index.html',
      hash: true,
      inject: true,
    }),
  ],
  devServer: {
    port: 3000,
    contentBase: 'dist',
    inline: true,
  },
};

There’s a fair bit to take in here. Working from top to bottom, first we say that the starting point of all of our app will be the ./app/index.js file (when we write it). We then specify that we want webpack to compile everything to a dist folder. Because webpack (and babel) transform files, we then need to specify that we want to generate source-maps that can be use to relate transformed lines of code back to the original for debugging.

The next section configures webpack to only look for .js (JavaScript) files, and to run any that it finds in our source code (which will be in the ./app folder) through the babel loader so that it can be transformed back to something an average browser can understand. We then configure the two plugins/tools- telling the HTML Webpack Plugin to use the ./app/index.html file as a template and the dev server to use port 3000 and automatically update the web page inline when the underlying code changes.

ESLint

Losing the will to live yet? JavaScript is a language of tools and frameworks, and learning to craft your stack is important- so keep at it.

Next on our stack we have eslint. Whilst JavaScript has nothing to do with Java, it is definitely a scripting language. And that means that you only find out whether or not you’ve typed your code correctly when the interpreter gets to that specific line. This is annoying and dangerous, as it’s fairly easy to make a trivial mistake that will run, until suddenly it doesn’t.

To overcome this, JavaScript developers use something called linters. These are automated tools that essentially look over your shoulder constantly and go “oh, you missed a semi-colon there”, or “didn’t we agree that you were going to name all your variables with a lower case letter?”. Linters are opinionated- they all have various configurations and extensions that determine how they think the perfect JavaScript code looks. Personally, I use the following:

npm install --save-dev eslint eslint-plugin-import eslint-plugin-react eslint-plugin-jsx-a11y eslint-config-airbnb babel-eslint

Hopefully you’re beginning to get the gist of reading these. Once again a linter is just something to help the developer. ESLint (the linter I use) needs help to read React language add ons (also called jsx; React is coming later), and to cope with the latest JavaScript features enabled by babel. I’ve also been lazy and imported in the AirBnB configuration- as, by and large, I agree with them about what makes a well written piece of JavaScript.

To configure ESLint we need to do two things, firstly we need to create an .eslintrc file. Normally this would include all the rules you want to follow, and such. But in our case all we need to do is say we’re happy following AirBnB’s rules, that we’re using babel, and that we’ll be using a testing framework called Jasmine (more on that later).

{
  "extends": "eslint-config-airbnb",
  "parser": "babel-eslint",
  "env": {
    "jasmine": true
   }
}

Secondly we need to train our code editor to use ESLint. For Visual Studio Code, which I personally recommend, this just means installing the ESLint plugin.

Jasmine

In the last post, if you can remember that far back, I talked about how we’d be using Behaviour Driven Development. To enable this, we need to add something to our stack that can take our tests and verify that our code fulfils those behaviours we’ve defined. As is the mantra with JavaScript, there’s a dozen ways of doing this. I like Jasmine, which I think has the most beautiful documentation in the world, and is fluently simple to use.

You should know the pattern by now, first step- install:

npm install --save-dev jasmine jasmine-core karma karma-chrome-launcher karma-jasmine karma-mocha-reporter karma-sourcemap-loader karma-webpack

This needs a bit more explanation than the rest. You see, jasmine is simply a language for describing tests, we need to throw in a few more tools to make it useful. We’ll be using karma to actually discover and run our tests (in this case it’ll be using Chrome to run the tests in), Mocha to report the results in a readable way, and integrations for webpack and source code maps.

Step two- configure. Karma will configure everything else in the test stack, so let’s create karma.conf.js:

const webpackConfig = require('./webpack.config.js');

module.exports = function configure(config) {
  config.set({
    browsers: ['Chrome'],
    frameworks: ['jasmine'],
    reporters: ['mocha'],

    basePath: '',
    autoWatch: true,
    files: ['./app/**/*.spec.js'],
    preprocessors: {
      './app/**/*.spec.js': ['webpack'],
    },
    singleRun: true,

    webpack: webpackConfig,
    webpackServer: {
      noInfo: true,
    },
    // Webpack takes a little while to compile -- this manifests as a really
    // long load time while webpack blocks on serving the request.
    browserNoActivityTimeout: 60000, // 60 seconds

    client: {
      captureConsole: true,
    },
  });
};

This configuration outlines what I said, that we’ll be testing using Chrome as our browser, with the jasmine framework and mocha to display the results. We’ll be following a fairly standard convention of naming our tests [test].spec.js (spec, for specification). The configuration then tells Karma that our files need to be compiled through webpack before testing. Finally we’re going to opt to capture console output, which is good practice for debugging our tests as it means we can put console.log() messages in them to work out where things are failing.

npm (again)

It’s OK. This is the only tool we’re going to return to. However, not only does npm make a good way of managing you stack and dependencies; it’s also a pretty solid task runner. Now we’ve established how we serve our application (webpack), and test it (karma), we should update our package.json file to reflect this. So take out the main entry (as we’re not using node to serve), and add/update the test and start commands. Once we’ve done this we can run npm start to start our server, and npm test to test our code (although we don’t have any code yet…):

// ...
  "description": "A web application to connect people working in the built environment based on their interests.",
  "scripts": {
    "test": "karma start --no-single-run",
    "start": "webpack-dev-server"
  },
  "repository": {
// ...

React

Finally, the promised ‘React’. React is a library for building user interfaces. It was made by Facebook and is one of the fastest growing frameworks out there. As frameworks goes its amazingly light weight, which makes it easy to get your head round fairly quickly. It also lends itself to writing very tight code (code that is small, reusable, and easy to change). It does have an interesting quirk, though, in that it extends the JavaScript language with a syntax for describing HTML called JSX, which is why we’ve had to tell all of our tools about our decision.

Unlike everything before it, React is part of our application and must be given to the end user. It is therefore a straight-up dependency so we only need to use --save. It also doesn’t need a configuration file because it’s a library, not a tool, so all we need do for now is load it in:

npm install --save react react-dom

Enzyme

Because React is a UI library, it can be a bit difficult to test. To make life easier, the people at AirBnB have created Enzyme. It’s a library that allows you to virtually render and manipulate your components and then query them about the condition they’re in. Annoyingly, however, it needs a bit of configuration due to the way it loads in its own dependencies. So first we install:

npm install --save-dev enzyme react-addons-test-utils

And then you need at add the following to your webpack.config.js to enable it to correctly load in the libraries Enzyme depends upon:

// ...
  },
  externals: {
    'cheerio': 'window',
    'react/addons': true,
    'react/lib/ExecutionEnvironment': true,
    'react/lib/ReactContext': true
  },
  plugins: [
// ...

Redux

Did you spot that I specifically called React a user interface library? That’s because when Facebook first released React they did so with an outline discussion on how they thought the architecture behind the scenes should work; they called it Flux. The problem was, they didn’t actually provide any code that implemented the Flux pattern, and instead left the community to sort it out themselves.

After a few iterations Redux emerged, which actually develops what Flux started and takes it one step further. Redux is what we’ll be using to wire in our React interface so that when you click on a button, something actually happens!

npm install --save redux react-redux redux-actions

Redux provides the basic functionality for the Redux pattern. React-Redux provides us with a well thought out way of connecting Redux to React, and Redux-Actions is a library for reducing the boilerplate code required to implement interaction in Redux. You’ll see all of these in action in the next article where we finally start writing some code.

Material UI

My last library is simply an aesthetic one. The whole purpose of React is to render an interface. That means that if you want to draw a nice button, or a well designed list, etc. you have to write your own. To save time and ensure we end up with something that looks nice, I’m going to use the Material UI component library. This is a project that provides React versions of most of the Material Design controls specified by Google for use on their Android platform.

npm install --save material-ui react-tap-event-plugin

Note that the react-tap-event-plugin is just a dependency of Material-UI’s; it adds the notion of ‘tapping’ on bits of the interface to allow the library to work with phones just as well as a it works on desktop computers.

Git

Last, but so incredibly not least, is a touch of version control. Sure, you could just sit there and work on files on a directory on your computer. But you’d be missing out on a lot of useful functionality. Initially git gets sold to people on the ‘you can use git so that anyone can collaborate with you on writing code’. And that’s true, if you want to contribute to pretty much any of these tools I’ve built my stack on, you can fork, clone, patch and make a pull request back using git.

What’s often undersold, however, is the usefulness of git’ing on your own. You see, git provides three amazingly helpful tools. The first is that you can ‘commit’ at any time. This can be thought of as saving a snapshot of your code. If you commit often (I normally commit on every unit of functionality- that works out as something like five times an hour), then you have a rich history that you can roll back on (if you make a mistake), or check back to see how you used to do something before you changed your mind.

Critically, for a prototyping scenario, it allows you to branch and merge your code. That means that you can get your code to a working point and then branch off, leaving your working code intact, and try something new. You can have as many branches as you like, so you can be simultaneously giving a few things a go, and then merge in the bits that worked into the main code.


And that’s it. We’ve crafted our stack. I think that one of the hardest things for developers new to writing web applications is understanding that there’s not just one tool that you download, type your code into and then press ‘compile’. A lot of my effort, when I’m developing, goes into following and learning about the developments in JavaScript tooling, libraries and frameworks so that I know what to pick whenever I start a project.

This post is part of a five post mini-series on building a web app: Part 1, Part 2, Part 3, Part 4, Part 5.

The post Building A Web App Part 3: Tooling Up appeared first on Being Brunel.

]]>
http://www.beingbrunel.com/building-web-app-part-3-tooling/feed/ 2
Building A Web App Part 2: Specification http://www.beingbrunel.com/building-web-app-part-2-specification/ http://www.beingbrunel.com/building-web-app-part-2-specification/#comments Tue, 21 Jun 2016 17:37:28 +0000 http://www.beingbrunel.com/?p=4382 Being Brunel | The Civil Engineering Blog

This post continues on from the last, so I suggest you start there if you want to follow this series; making a simple web application to ask a user what about the built environment interests them and suggest...Read More

The post Building A Web App Part 2: Specification appeared first on Being Brunel.

]]>
Being Brunel | The Civil Engineering Blog

This post continues on from the last, so I suggest you start there if you want to follow this series; making a simple web application to ask a user what about the built environment interests them and suggest some Slack channels they can join accordingly. In this article we’re going to continue not writing any code, but that’s because we want to firm up our idea a bit, before we just go blindly creating.

Behaviour Driven Development

Behaviour Driven Development is an incredibly useful tool. It’s something that I employ on a daily basis to ensure that I only deliver what I have to; and that what I do does what the user was expecting. The premise is simple: Express your application as a series of behaviours and test against them- if it passes all the tests, then it must meet the requirements.

BDD, as it’s called in the biz, was an evolution of Test Driven Development; which set out to test each and every line of code by defining what it did before it did it. The problem was that it focused on the implementation instead of the result. BDD admits that all the user cares about is the behaviour of the application; it doesn’t matter to them if it’s done by an elegant bit of code, or an elaborate system involving pulleys and penguins.

In the last post I discovered that the sole feature we needed to implement for this prototype was: “Ask users about their interests and suggest channel names accordingly.” Although not strictly a requirement, it’s helpful to express the feature formally in a language called Gherkin. Not only does it discipline you into fully considering the problem, but it matches the procedure used in the testing tools:

  • In order to meet people with similar interests
  • As a user
  • I want to find channels that match my interests

Thus, my scenario is:

  • Given a list of interests
  • When a user selects interests
  • Then a list of appropriate channels should be shown.

Wireframes

So we know what the our web app is going to do, but we haven’t really touched on what it’s going to look like. That’s what wireframing is about; a wireframe is a sketch of what the interface could look like. Remember we’re aiming to fail fast, so that means we don’t want anything elaborate.

Let’s turn to our single feature/scenario description. To achieve that I need:

  • A list of interests
  • Each interest must be ‘selectable’
  • A list of channels

Let’s keep it simple (stupid); we can do this all on one page without hurting ourselves. You can use a pen and paper to wireframe, or one of the variety of fun digital tools for this. I normally do it by hand, but for this post I’m using Wireframe.cc to save you from my terrible handwriting:

wireframe

Hopefully it’s fairly obvious: The user is presented with a cloud of interests. Clicking on an interest toggles whether or not it is selected (it colours to indicate selection). As interests are selected the list below the interest cloud starts to populate with channel names matching the user’s interests.


I know what you’re thinking. Two articles in and there’s still no code; what sort of guide is this?! The problem with writing things down, is that it makes everything sound formal and long winded. But I invite you to think about how this would have gone if we’d just been in a meeting room with a whiteboard. At this point code is the most expensive thing we can create (even if it is just a small prototype). If I sit down with you and hash out the behaviours you want to achieve and draw out a sketch of the user interface, we could iterate through a dozen ideas in 10 minutes. So bare with me.

This post is part of a five post mini-series on building a web app: Part 1, Part 2, Part 3, Part 4, Part 5.

The post Building A Web App Part 2: Specification appeared first on Being Brunel.

]]>
http://www.beingbrunel.com/building-web-app-part-2-specification/feed/ 2
Building A Web App Part 1: Failing Fast http://www.beingbrunel.com/building-web-app-part-1-failing-fast/ http://www.beingbrunel.com/building-web-app-part-1-failing-fast/#comments Tue, 21 Jun 2016 17:36:40 +0000 http://www.beingbrunel.com/?p=4377 Being Brunel | The Civil Engineering Blog

'm willing to admit that this series of posts is going to be a little off topic, however I've had enough engineers ask me about the wonderful world of web apps and how to build one that I thought it'd be worth...Read More

The post Building A Web App Part 1: Failing Fast appeared first on Being Brunel.

]]>
Being Brunel | The Civil Engineering Blog

I‘m willing to admit that this series of posts is going to be a little off topic, however I’ve had enough engineers ask me about the wonderful world of web apps and how to build one that I thought it’d be worth doing a mini-series stalking me as I attempt to design one for, what will turn out to be, an engineering cause.

Unlike my Python guide, this will focus more on the process of getting something together. There’s quite a lot to cover (five posts worth, in fact), and I’ll only be able to give a glancing blow to some of the more detailed topics. I also won’t be stopping to explain the syntax, methods, etc. of the code I’ll be providing. I’m not saying this to put you off, quite the opposite. I recommend you go straight through this mini-series not worrying to much if you don’t completely get something immediately. Then go back and use the links I’ve provided fill in the details, once you’ve got the shape of the solution. I’ll also be providing the complete working code at the end of the series for you to pull apart.

You’re not going to be a web developer at the end of this, but hopefully you’ll know where to start looking.

So lets get started:

Nearly a month ago now, someone from the BIM2050 crew go in touch with me to talk about an idea they had for a website. We had a conversation and there was a lot of predefined ideas, context, and ‘like x meets y’. So I said “sure, I’ve got so much spare time these days that I hardly know what to do with myself- I’d love to spend it programming for you.” And that’s how I got where I am now.

Fail Fast

I think one of the most important things to do when trying out a new idea is to set yourself up for failure. The chances of you just immediately coming up with exactly the right solution is zero to none, so it’s best to take an approach that means that you can fail at a low cost. I’ll probably do a whole post about how this philosophy can be applied to engineering, but for now that means that I need to distill all the hopes and dreams of the original request into a simple idea to be tested- a minimum viable product.

In this case, the idea can be summed up as:

A way of connecting people working in the built environment based on their interests.

That’s right. We’re writing Grindr for Engineers (that’s so very untrue, but it’s going to be a fun way to think of it). Although this idea is pretty simple, it’s actually a bit broad in its application. So to focus in on our minimum viable product we’re going to accept some constraints (because, as any mathematician will tell you; constraint maketh the solution). Our constraints come from looking at the most critical points in the original context:

  • People will be connected by joining Slack channels that match their interests
  • The target audience is busy; there should be as little friction as possible in the process

With these constraints, it’s possible to begin to shape a minimum viable solution- so we’ll stop there.

The Bare Minimum

Until now, I haven’t actually stated that this will be a web application (the original pitch was for one, but that doesn’t mean it’s right). However web applications are fantastic for minimising friction; all you need is a device with a web connection and a browser– no installing software, no traveling to specific locations, very little wait time. And thus, we now know that we’re designing a website.

The most useful constraint of the two is that people will be ‘connected’ by being invited to join a Slack Channel. That means that our minimum viable product doesn’t need to cope with maintaining the connection; just on establishing it. Or to put it another way, it only needs to identify which Slack channels you should join based on your interests.

So here we go:

Ask users about their interests and suggest channel names accordingly.

I know this doesn’t sound that exciting, but it does two things. It provides us with something that can be delivered very quickly but can still be used to achieve the principle aim; something that can be tested against to discover if the idea is good. It also provides a point for discoverability; something to build upon. We’re at the rapid prototyping stage here- it’s all about keeping change easy and failure cheap, and that means not investing too much in any given solution.


And that’s the first part- note the complete lack of code. This is because the absolutely fastest way to fail is to fail without doing any work at all. A thought experiment, a few sketches, just bouncing ideas around- these are all examples of failing fast. However, sooner or later I’m going to have to do some work; and that’s for part two…

This post is part of a five post mini-series on building a web app: Part 1, Part 2, Part 3, Part 4, Part 5.

The post Building A Web App Part 1: Failing Fast appeared first on Being Brunel.

]]>
http://www.beingbrunel.com/building-web-app-part-1-failing-fast/feed/ 4
Programming Languages For Engineers http://www.beingbrunel.com/programming-languages-engineers/ http://www.beingbrunel.com/programming-languages-engineers/#comments Mon, 06 Jun 2016 16:23:29 +0000 http://www.beingbrunel.com/?p=4307 Being Brunel | The Civil Engineering Blog

Last weekend someone asked me what programming language they should learn, and I unhelpfully responded with "it depends". And it does- if I asked you what material I should learn to...Read More

The post Programming Languages For Engineers appeared first on Being Brunel.

]]>
Being Brunel | The Civil Engineering Blog

Last weekend someone asked me what programming language they should learn, and I unhelpfully responded with “it depends”. And it does- if I asked you what material I should learn to design with, you’d probably say something similar. The fact is, the reason there’s so many different programming languages is not (as it may first appear) to bewilder the uninitiated, but because they all solve different problems for different people.

However, there aren’t such things as stupid questions, just stupid answers. So in today’s post I’m going to attempt to answer the question by outlining three common things engineers looking to program want to do, and making a recommendation as to what you should go about learning. Obviously there are always different answers if you ask different people, but if we could save time and just agree I’m right- that’d be grand.

Automation and Desktop Tools: C#

The majority of programs used by engineers are desktop applications. Automating and writing tools to make your life easier on a day to day basis must be the main thing I find engineers are trying to achieve when they first start programming. Although this often manifests itself as intricately crafted Excel macros, sooner or later you’re going to want to move on- and that’s when I recommend you find C#.

using System;
namespace HelloWorld.CSharpExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

So why C# (pronounced C Sharp)? Well for a start, most of the applications you use on a daily basis will have a C# interface- Rhino, Excel, Revit, SAP/ETABS, etc. This means that you can write your own tools to drive, process and transfer data between programs– a very common use case for automating engineering tasks. It also has support for Web APIs and COM; capturing the way the other 10% of programmable applications communicate.

C# is primarily a windows language, so developing desktop applications is relatively straight forward. It is a high-level language and also sits on top of something called the .NET Framework, which means you get a lot of functionality out of the box. Finally, it is the only language on this list that is compiled ahead-of-time, which means that you’ll benefit from being able to identify most errors before you run your application.

Scientific Applications: Python

I’m already talking about Python in another series, but the fact remains that for whatever reason the scientific community love a bit of Python. Because of this, regardless of what you think about the language itself (and Python does have its fair share of eccentricities), the massive number of fantastic scientific and mathematical libraries that are being created by its community automatically makes is a great language for these applications.

print("Hello World!")

So why Python? Well, it’s incredibly tolerant, which makes it ideal for prototyping and throwing together code to see what you can get working. However, you can say that about a lot of languages. Where Python really shines is third party libraries like NumPy, SciPy, DEAP, etc. that provide fast and stable implementations of many common and cutting-edge algorithms and methods. With access to these it can become incredibly easy to solve complex problems (like writing a Genetic Algorithm in 23 lines of code).

Web/Cross-Platform: Javascript

I hesitate in recommending JavaScript to anybody who doesn’t already know another language, as it is a language of quirks that makes it easy to fall into bad habits. However it is the language of the internet. That means if you want to develop an application that works pretty much anywhere; JavaScript is the language you need to learn.

console.log('Hello World!')

JavaScript is an odd language, it has nothing to do with Java, and owes its popularity much more to chance than design. Really, the only reason we use JavaScript so extensively is that it pretty much accidentally ended up on every computer after browsers all implemented it. Although it’s something you learn to love eventually, there’s a lot out there to catch the less experienced developer out.

Last year JavaScript had a bit of a revamp (called ECMA2015, or ES6) and I would recommend people new to the language start there and then work backwards. It’s a language of tools (node for servers, npm for downloading third party libraries, babel for transpiling, webpack for compiling), a language of frameworks (react or angular for views, redux for state, d3 for graphing, etc.), and a language of new exciting developments (electron for cross-platform desktop apps, react-native for phone apps, three for 3D websites). And that makes it hard, but incredibly worthwhile, to dip your toe into.


I’ll probably get around to each of these in turn discussing the resources available and any specialist challenges engineering offers them. But until now I hope that’s given you all some where to get started.

The post Programming Languages For Engineers appeared first on Being Brunel.

]]>
http://www.beingbrunel.com/programming-languages-engineers/feed/ 1
Evaluate: Excel’s Dirty Secret http://www.beingbrunel.com/evaluate-excels-dirty-secret/ http://www.beingbrunel.com/evaluate-excels-dirty-secret/#respond Sat, 04 Jun 2016 09:30:44 +0000 http://www.beingbrunel.com/?p=4211 Being Brunel | The Civil Engineering Blog

As much as I hate to promote the use of Excel, I’ll grudgingly admit that it’s a useful application. And until you’ve all learned Python- it remains one of the most popular pieces of engineering software today. So you might as well learn how to squeeze every last drop of functionality from it.Read More

The post Evaluate: Excel’s Dirty Secret appeared first on Being Brunel.

]]>
Being Brunel | The Civil Engineering Blog

As much as I hate to promote the use of Excel, I’ll grudgingly admit that it’s a useful application. And until you’ve all learned Python– it remains one of the most popular pieces of engineering software today. So you might as well learn how to squeeze every last drop of functionality from it.

I’ve written a few posts now on Excel functions you might not have heard of. However, there’s one function that I’ve abstained from sharing. This is because it deserves a post of its own; a function so easily abused that the only reason Microsoft keep it is to maintain compatibility with Excel 4.0- and even then, they have hidden it away.

I would like to introduce you all to the Evaluate function.

The Evaluate(<text>) function is simple. It asks Excel to evaluate the text within the brackets as though you’d typed it in the formula bar yourself. As a few examples:

  • Evaluate("1+1") returns 2
  • Evaluate("A1 * 3") returns triple the value in cell A1.
  • Evaluate(A1 & " (" & A2 & ")") runs whatever formula has been typed in cell A1 on whatever has been typed in cell A2; e.g. if A1 = Sum and A2 = 1, 2, 3 then it would show 6, the sum of 1, 2 and 3.

And that’s the power of Evaluate. It allows you to dynamically build functionality; to allow your spreadsheet to effectively build and adapt itself. The most practical applications centring on allowing the user to enter their own transformations, or building different expressions based on the data/user input.

In an attempt to stop people from accidentally birthing Skynet in Excel (and also because dynamic evaluation prevents Excel from being clever about how it does its calculations, making it less performant) Microsoft has effectively hidden away the Evaluate function.

To resurrect this function, we need to do some trickery. We must define a new named range to invoke the function. To do this open Define Name from the Name Manager (Formula > Define Name in more recent versions of Excel) and enter:

  • Name: EvalLeft
  • Refers To: =EVALUATE(INDIRECT("RC[-1]",FALSE))

Then press OK.

You can now use the Evaluate function! To test this type 1 + 1 in cell A1, and =EvalLeft in cell B1. Lo-and-behold you’ll be presented with the number 2. Feel free to experiment. You can use string concatenation (&‘ing together values from different cells or "text") to build complex expressions, like my third example above.

For completeness I’ll just explain why this trick works. To keep compatibility with Excel 4.0 Microsoft had to leave Evaluate in. The compromise was that it would only be available as an undocumented Macro. This macro isn’t directly callable from your spreadsheet, however the name manager has access to it. Of course, if you had to type the text you wanted evaluated in the name manager every time it wouldn’t be all that useful. So instead we reference another cell, in this case we use the Indirect function to reference the cell immediately to the left of the cell that EvalLeft is called in.

Before you get all excited, I am legally obliged to tell you that Eval is Evil. In Excel there aren’t really any security concerns, so we’ll skip that argument against dynamically constructed code- however it does mean that you have a level of indirection; anyone reading your code needs to work out what your Evaluate string construction is doing before they can work out what the resulting text then evaluates to. This can lead to some exciting debugging. So, let me just remind you that with great power comes great repercussions.

The post Evaluate: Excel’s Dirty Secret appeared first on Being Brunel.

]]>
http://www.beingbrunel.com/evaluate-excels-dirty-secret/feed/ 0
Python For Engineers: Part 2 http://www.beingbrunel.com/python-engineers-part-2/ http://www.beingbrunel.com/python-engineers-part-2/#comments Thu, 26 May 2016 11:30:02 +0000 http://www.beingbrunel.com/?p=4155 Being Brunel | The Civil Engineering Blog

As promised, today we're going to put in some functionality; we're going to calculate the gross area of the column. Arguably not that exciting, but it'll arm us with a surprisingly large number of the building blocks...Read More

The post Python For Engineers: Part 2 appeared first on Being Brunel.

]]>
Being Brunel | The Civil Engineering Blog

It turns out there’s a surprisingly large amount of engineers excited about the prospect of learning Python! If you haven’t read part one, I suggest you do that now– as I can’t start every post explaining how to install and run Python 3!

As promised, today we’re going to put in some functionality; we’re going to calculate the gross area of the column. Arguably not that exciting, but it’ll arm us with a surprisingly large number of the building blocks we’ll need to tackle some of the harder questions.

Getting Talkative

Let’s make the wild assumption that we’ve got a 500mm square column. To calculate the area we just multiply (which is represented by the * in computer notation for no sensible reason at all) 500 by 500.

So let’s create the file rccol.py, with the following completely uninspiring code in:

500 * 500

And when we run it (python rccol.py) we’ll calculate the area of said column. You’ll have to take my word on that because you get absolutely zero output. This is because any programming language that constantly shouted the result of any calculation you did would be incredibly irritating.

As I hinted last week, the solution is to use the print() function. A function in programming is the same as a function in mathematics, it’s something that you give some parameters (called arguments) to, and it returns something back. In the case of print(), it takes the argument (given inside the brackets) and outputs it to the command line.

Therefore, to output our calculated area we need to wrap the calculation in a print() function:

print(500 * 500)

Now when you run it you are helpfully told that 500 x 500 is 250000- what an amazing use of the gigaFLOPS your computer can offer.

As an aside, you might be wondering why you didn’t need to use the print() function when we were just typing in python directly into the interpreter last week. It might help if I tell you that the proper name for that is a REPL (or a Read, Evaluate, Print Loop); it reads your input, evaluates the answer and prints it out. As such the print() function is already baked in!

Variables

I have two major problems with our code, it’s not very descriptive (what is this 500?) and it also only works for columns that are 500 x 500. We can solve both of these problems by using variables:

width = 500
depth = 500
area = width * depth
print(area)

Variables are a simple but powerful concept; they are the algebra of programming. In the code above we introduce the variable width and we say that it will equal 500 (this is called an assignment). Once we’ve assigned a value to a variable we can then use the variable instead of repeating that value everywhere. So instead of having area = 500 * 500, we can use area = width * depth.

Not only does this make it much more clearer what’s going on, but we can sanely make changes- knowing that I only have to change width = 500 to width = 600 in one place and all calculations using the width of the column will be updated to use 600 instead of 500.

User Input

I’m sure some of you are feeling that I’m a little prematurely satisfied with our code. I mean, who’s heard of a program where you have to go in and edit random lines of code every time you want to change your inputs?

Like print() we have the input() function, which waits for a user to type something and then returns that value to the program, so that:

typed = input()

Makes the variable typed equal whatever the user typed before pressing the enter key.

Now it’s tempting to say, “OK Tom- I’ve got this- let’s just use input() to get the width and depth from the user.” Well, give it a go:

width = input()
depth = input()
area = width * depth
print(area)

However you’ll get this cryptic message back:

Traceback (most recent call last):
File "rccol.py", line 3, in <module>
area = width * depth
TypeError: can't multiply sequence by non-int of type 'str'

And this takes me to the last thing I want to explain, and that’s the wonderful world of typing.

Data Types

The problem here is that when you type in something, you’re typing in text. That means that although you may have typed a number when prompted for width and depth, you’ve actually typed in the text 500.

Now you and I both know that 500 is a number, because we can read. But computers are dumb. Python has attempted to multiply two pieces of text, and this error poses the philosophical question, how does one multiple one word by another? To Python this is just as confusing as if you’d been asked to multiply apples with oranges.

The technical word for how a program interprets data is called the data’s Type. Python has a whole variety of exciting types, however I’m going to introduce you to the three most pertinent of them, with a translation from the computer science term:

  • int – (short for integer) a whole number
  • float – (short for floating point) any number
  • string – (as in a set of characters ‘strung‘ together) text; words, numbers and punctuation

As input() returns a string (text), we have to explicitly tell Python that we want to treat it as a number (in this case, a float). To do that we’ll use the float() function, which will read the argument and attempt to convert it into a floating point number:

width = float(input())
depth = float(input())
area = width * depth
print(area)

Now we can run the code without errors!

User Interfaces

Just to tie this all together we’re going to do some tidying up:

print("RC Column Designer v0.2")

width = float(input("Column Width: "))
depth = float(input("Column Depth: "))
area = width * depth

print("Column Area = ")
print(area)

Here we can see that to allow Python to tell the difference between text (as a string) and text that is code to be executed, you have to quote it; "In Python, this is a piece of text". This snippet of code also uses input("prompt"); where we give input() a prompt argument so that the user knows what they’re expected to type in!

Now when we run the code for our 500mm square column we get:

RC Column Designer v0.2
Column Width: 500
Column Depth: 500
Column Area =
250000.0


Well that’s variables, the use of functions (will come to defining them soon), and the basics of types. And with this information alone we could rewrite the spreadsheet, but I want you to come away with an understanding of some of the abstractions programmers use to write cleaner code faster- so we won’t stop here.; not by a long shot.

I’m going to talk about GitHub a bit later on, but if you want to have a look at the “finished” code from this tutorial, checkout:

https://github.com/thomasmichaelwallace/rccol

The post Python For Engineers: Part 2 appeared first on Being Brunel.

]]>
http://www.beingbrunel.com/python-engineers-part-2/feed/ 2
Engineering the Twitter API http://www.beingbrunel.com/engineering-twitter-api/ http://www.beingbrunel.com/engineering-twitter-api/#respond Tue, 24 May 2016 08:01:13 +0000 http://www.beingbrunel.com/?p=4126 Being Brunel | The Civil Engineering Blog

Last week I talked at length about the wonderful world of the Web API, but completely failed to provide any details of how you can start playing with them. Well today...Read More

The post Engineering the Twitter API appeared first on Being Brunel.

]]>
Being Brunel | The Civil Engineering Blog

Last week I talked at length about the wonderful world of the Web API, but completely failed to provide any details of how you can start playing with them. Well today we’re going to do some engineering with twitter using their RESTful API.

Interacting with Web APIs is normally done programmatically, and so varies from language to language. However, once you’ve got the process down it’s just a matter of implementation. To ease the learning curve, however, we’re going to be using Twitter’s Developer Console; thus requiring you to do absolutely no coding at all:

Twitter Developer Console

OAuth

As Microsoft’s Tay learnt the hard way– if you go around trusting everybody you meet on the internet, you’re going to get shutdown. This means that most ‘open’ API’s on the internet need you to authenticate; provide an identity that you can be traced and trusted against. OAuth is one of the most common ways of authenticating yourself to a Web API. In fact, you’ve probably used OAuth without knowing it!

As a ‘good-enough’ analogy, OAuth is like your site safety card. You get yourself tested by, and give all your personal details to, the issuing authority, and then you get given a card. When you visit a site the inspector rings up the issuer and verifies the card, and then hands you a visitor pass for that day and that site. In this case the card is your login details, the issuing authority is often someone like Twiter, Google, GitHub, etc., the ‘site’ is the api and the visitor pass is called an access token.

So, before we can started you need to authenticate in the Twitter Developer Console. At the top centre is an Authentication area, initially saying No Auth. Drop this down and select OAuth 1.1, at which point you’ll be asked to login to Twitter. Congratulations, you’ve now got your access token (although this interface simplifies things and just stores it behind the scene.)

Headers

So let’s make a request. To save you learning the whole Twitter API you can expand the dark gray sidebar on the left on the console, which will then list all the actions available to you. We’re going to search tweets, and in Twitter’s RESTful API that means GET‘ing /search/tweets.json (I’ll touch on what the .json means later).

twitter-console-expand

To be helpful the console will now expand to ask you for the parameters needed to complete the query string. For this example we’ll go searching up the #EngineeringIsArt tag, so type #EngineeringIsArt into the q parameter and press Send.

The Console then shows you two (overly) technical looking outputs. On the left is the Request that you made, and on the right is the Response the Twitter server returned. We’re going to focus on the response, which is formed of two parts- the header (first bit) and the data (which starts at the {).

Headers are used by HTTP to transfer protocol level information. There’s a lot of information in the response header, with everything from the time the data was put together for you to the cookies that it wants the browser to set. Only two bits of this are all that interesting for us: the status and the content-type.

The status is a number indicating how things went. There are a good few codes, however the most useful to know are:

  • 200: OK
  • 400: Bad Request (normally because you didn’t authenticate)
  • 404: Not Found
  • 500: Server Error

The content-type tells you what ‘format’ the content you’ve be returned is in. In this case you’ve being given some json, but it could be a jpeg image or something even more exciting!

JSON

A few years back the web was a place of many languages, however these days you’ll find that most Web APIs will return data to you in something called JSON (JavaScript Object Notation). Sometimes you might also see an option for XML, but by and large we all talk JSON.

The data in the response is in JSON:

"statuses": [
  {
    "created_at": "Sun May 22 13:16:41 +0000 2016",
    "id": 734372412578533400,
    "id_str": "734372412578533376",
    "text": "I call this 'Fenland Footbridge'. Because that's what it is... #EngineeringIsArt https://t.co/BE1qPcGBhR",
    "truncated": false,
    "entities": {
      "hashtags": [
        {
          "text": "EngineeringIsArt",
          "indices": [
            63,
            80
          ]

Hopefully you can make out some of the data already, but it’ll help if I tell you that JSON works like this:

  • "key": "value"
  • { collection of keys and values }
  • [ list of values/collections ]

So in the data above we have a key statuses that contains a list of Twitter statuses (tweets). The components of each status is collected in { } brackets, so the first status was created at Sun May 22 13:16:41 +0000 2016 with the text I call this 'Fenland Footbridge'. Because that's what it is... #EngineeringIsArt https://t.co/BE1qPcGBhR.

Return Post

To finish off let’s use the Twitter Developer’s Console to send me a message.

  1. Making sure that your Authentication is set to OAuth so that twitter trusts you to send a message…
  2. Expand the API selector on the left side and Direct Message > direct_messages/new.json
  3. Enter the parameters:
    1. text: Cheers for the tutorial Tom!
    2. screen_name: beingbrunel
    3. user_id: leave blank
  4. Press Send

Looking at the Request you’ll see you’ll see you POST‘ed to (twitter)/1.1/direct_messages/new.json?text=Cheers%20for%20the%20tutorial%20Tom!&screen_name=beingbrunel (the funny %‘s are to do with the way punctuation is sent in HTTP).

In the response you’ll see 200 in the header; you successfully sent me a message (Thanks!). But you’ll also see a bit lump of data, giving the ID of the message, the text, and some information about yourself in the sender` collection. This ‘echoing what you sent’ approach is fairly common in WebAPIs as it lets you verify that what you asked to happen, happened.


And that’s most of the more difficult bits of working with a Web API. In the final post of this series I’m going to hopefully get you started on some of the APIs that have some more practical use to you civil engineers out there.

The post Engineering the Twitter API appeared first on Being Brunel.

]]>
http://www.beingbrunel.com/engineering-twitter-api/feed/ 0