text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91
values | source stringclasses 1
value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
Archived:How to add a submenu in PySymbian
From Nokia Developer Wiki
Article Metadata
Tested with
Devices(s): Nokia N96Compatibility
Platform(s): S60 2nd Edition, S60 3rd EditionArticle
Keywords: appuifw, menu
Created: (15 Mar 2007)
Last edited: fasttrack (25 Sep 2009)
Overview
Python can use submenu in menu options but it can be difficult to remember how to use them !
- Item 1
- Submenu
- Item 2
- Item 3
Identation has been used for a better understanding. Don't mismatch the parentheses ! Item2 and item3 will be displayed on screen only when you click on submenu.
Code
#import module
import appuifw
# create menu
appuifw.app.menu = [(u"item 1", item1_cb),
(u"Submenu", (
(u"sub item 2", subitem2_cb),
(u"sub item 3", subitem3_cb)
)
)
]
# item1_cb, subitem2_cb, subitem3_cb are callback
Postconditions
Here is a screenshot to illustrate this submenu. | http://developer.nokia.com/community/wiki/index.php?title=How_to_add_a_submenu&oldid=63897 | CC-MAIN-2014-10 | refinedweb | 134 | 58.92 |
Consume NuGet Packages
Alt+Shift+N
Alt+7
You can install, update, and remove NuGet packages via the NuGet window Alt+7 and NuGet quick list Alt+Shift+N.
Browse installed and available NuGet packages
By default, the Packages tab of the window shows all packages installed in the whole solution, but you can change the view to only show packages of a specific project. To do so, use the scope selector next to the search box:
Available packages for the selected scope are always shown below the installed packages.
Packages that are referenced from other installed packages are displayed in the Implicitly Installed category. Their versions are shown in brackets because you cannot upgrade or downgrade them. To learn which package references an implicitly installed one, right-click it and choose Quick NuGet Documentation or press Ctrl+Q.
You can select installed or available packages in the left part of the Packages tab, and use the right part to check package details, as well as to install, upgrade/downgrade, or remove the package in specific projects:
Restore and Upgrade NuGet packages
Rider provides two algorithms for restoring NuGet packages:
Normal — calls the standard NuGet restore mechanism, which can be slow, especially on .NET Core projects. It is available in the main menu ( ), in the NuGet quick list Alt+Shift+N, and by clicking Restore
on the NuGet window toolbar.
Force — performs a number of heuristics to determine which packages should be restored. The 'Force' algorithm works almost instantaneously, however there could be cases where it fails to restore some packages.
We recommend using force restore for large projects. It is available in the main menu ( ) or in the NuGet quick list Alt+Shift+N.
When you open a solution, Rider will automatically apply the 'Light' algorithm to restore missing packages. If necessary, you can change the auto-restore behaviour on the NuGet settings page, which you can also open by clicking NuGet Settings
on the NuGet window toolbar.
To upgrade the installed packages, click Upgrade all packages in Solution
on the NuGet window toolbar and then optionally choose which packages should be upgraded.
Alternatively, you can select one of the installed packages in the left-hand side of the NuGet window choose the desired version in the right part, and then upgrade/downgrade specific projects to this package version.
Find and install NuGet packages
To find a NuGet package, use the search field and the list of Available packages, which appears under the list of Installed packages.
In the search field, you can enter a package name to look for or use prefixes:
T: to look for types and
N: to look for namespaces.
By default, Rider searches all available package sources, but you can limit the search scope using the corresponding selector:
A single click a package source will select the source and deselect all others. You can Shift -click to select multiple sources or click All feeds to select all.
Install or upgrade/downgrade a NuGet package
Find the desired package as described above and select it in the left part of the Packages tab
In the right part of the tab, choose a project where you want to install the selected package. If your solution contains too many projects, you may want to use the scope selector on the toolbar to display specific project and hide all others.
Use the Prerelease checkbox on the toolbar to show or hide pre-release versions of the package.
Use the Version selector in the right tab to choose the desired version of the package.
Before installing the selected package, you may want to check which dependent packages will be installed. To do so, expand Frameworks and Dependencies in the right part:
Depending on the selected package version, and on whether the selected package is installed in the selected project, you will be able to install, upgrade or downgrade the package.
After installing a new package, you will see it's readme.txt file in the editor so that you will be able to check if any additional steps are required after installing.
If config file/XDT transformations are implemented in the package, JetBrains Rider will run them to help in adding required entries, for example to an App.config or Web.config file.
The easiest way to start the search for a NuGet package is to use the corresponding Alt+Enter action that becomes available for unresolved namespaces:
... and types:
In any case, JetBrains Rider will open the NuGet window, where you will see all packages that contain the desired type or namespace.
Manage package sources:
Credential providers for private NuGet feeds
JetBrains Rider lets you authenticate to private NuGet feeds that use with different authentication methods.
Authentication prompt for username/password combination
In the Sources tab of the NuGet window, you can edit or add a feed and add credentials in the form of a username/password combination.
The URL to private feeds is often shared with team members in the NuGet.config file that sits next to the solution file, so that everyone on the team can connect to such private feed. On the first load of such solution where package restore is required, JetBrains Rider will prompt for credentials.
When credentials are correct, they are stored in JetBrains Rider’s password store so that you don’t have to re-enter credentials each time you access a NuGet feed. The password store is configurable on the Appearance and Behavior | System Settings | Passwords page of the Settings/Preferences Ctrl+Alt+S.
JetBrains Rider also has integrated credential providers for MyGet and Visual Studio Team Services (VSTS).
Use authentication plugins
For private feeds that use plugin-based authentication method, such as the one provided by Azure Artifacts, you need to change the Use credential providers preference on the Build, Execution, Deployment | NuGet page of the Settings/Preferences Ctrl+Alt+S to NuGet/.NET CLI plugins or to NuGet/.NET CLI plugins, then Rider integrated (if you use different authentication methods) and then restart JetBrains Rider.
Once authentication plugins support is enabled, the %USERPROFILE%\.nuget\plugins (Windows) and $HOME/.nuget/plugins (Linux/macOS) path will be monitored for credential provider plugins that are applicable, and JetBrains Rider will use those to perform necessary authentications.
NuGet options
You can configure NuGet preferences in the NuGet settings page, which you can open by clicking NuGet Settings
in the NuGet window or by choosing in Rider settings Ctrl+Alt+S.
In the Search section, you can choose:
Include prerelease — lets you search and install pre-release versions of packages. This preference is synchronized with the same preference shown on the toolbar of the Packages tab.
Include unlisted — lets you search and install versions of packages that are at unlisted on the server (for example, at NuGet website). You may want to use this option to see outdated versions of packages.
Preferences in the Install and Update and in Uninstall sections work exactly the same as in Visual Studio package manager:
Manage NuGet caches
NuGet caches all downloaded packages to make them available when there is no Internet connection and to prevent multiple downloads of the same package.
With Rider, you can view locations of NuGet caches and clear selected locations in the Folders tab of the NuGet window. Clearing NuGet caches is safe, it does not affect packages installed in your projects.
Edit NuGet configuration files
If necessary, you can also manually edit NuGet configuration files — NuGet.Config, packages.config, and *.nuspec. Most of the coding assistance features including syntax validation and Code Completion (IntelliSense) are there for you.
NuGet quick list
The most frequently used actions are available in the NuGet quick list — Alt+Shift+N or:
| https://www.jetbrains.com/help/rider/Using_NuGet.html | CC-MAIN-2021-10 | refinedweb | 1,286 | 58.32 |
Getting Started with Yoga and Prisma for Building GraphQL Servers
By now, you have probably heard a lot of buzz about GraphQL going around and how it’s going to replace REST but you don’t even know where to begin. You hear a lot of buzzwords about mutations and queries but what you’re used to is GET and POST requests on your different endpoints to fetch data and make changes to your database. Thinking about making a switch to GraphQL and don't know where to begin? This article is for you.
In this article, we are going to take a look at how to convert a database to a GraphQL API using Prisma.
Prerequisites
To follow through this article, you’ll need the following:
Table of Contents
- Basic knowledge of JavaScript
- Node installed on your machine
- Node Package Manager installed on your machine
To confirm your installations, run the command:
node --version npm --version
If you get their version numbers as results then you’re good to go!
Using Prisma to connect GraphQL to a database
Prisma is a service that allows you to build a GraphQL server with any database with ease. To get started with using Prisma, you need to install the command line interface first:
npm install -g prisma
This globally installs
prisma for future use on your machine. The next thing you need to do is to create a new service. To do this, run the command:
prisma init scotch-prisma-demo
When you run this command, a prompt will be shown for you to decide what server you want to connect to.
For demo purposes, select the
Demo Server option and then a browser prompt will be shown to register with Prisma Cloud. After successful login, click the
CREATE A NEW SERVICE option and then copy the key required to log in to Prisma from the page.
Head over to your terminal, close the current process if it’s still running and then login to prisma by pasting the command copied from the browser into the terminal:
Once you’ve successfully signed in, return to the command line and select the region for your demo server and follow the remaining prompts as shown below:
You can also head over here if you want to connect Prisma with own database.
Now that the service has been created, you need to deploy it. To do this, head over to the
scotch-prisma-demo directory and run the deploy command:
cd scotch-prisma-demo prisma deploy
Once deployment is complete, on the Prisma Cloud you can see a list of your deployed services:
To open the GraphQL API and start sending queries and running mutations, run the command:
prisma playground
Updating Schema
When the
scotch-prisma-demo folder was created, two files were created in the folder
prisma.yml- containing the
endpointand
datamodelfor the server.
datamodel.graphql- Containing the schema for the server.
Edit the
datamodel.graphql file to look like this:
type User { id: ID! @unique name: String! }
This means the schema will contain the
ID and
name for the user. To update the schema, run the command:
prisma deploy
Using Yoga and Prisma Binding to interact with Prisma Service
In the last section, we saw how to use Prisma to turn a database into GraphQL API and then run Queries and mutations from the playground. Here’s the thing though. In a real-life application, leaving all this functionality to anyone who has access to the Prisma means that the client has the entire database exposed to them and this is not good.
To to this, Prisma has the
graphql-yoga and
prisma-binding which allow you to build a GraphQL server on top of the Prisma service by connecting the resolvers of the GraphQL server to Prisma’s GraphQL API using Prisma binding.
In the
scotch-prisma-demo folder initialize a node project using the command:
npm init -y
This automatically creates a
package.json file for your project
Installing the necessary modules
To continue building the graphql server, we will need to install the following modules by running the command:
npm install graphgql-yoga prisma-binding
Reorganize File Structure
Run the following commands:
mkdir prisma mv datamodel.graphql prisma/ mv prisma.yml prisma/ mkdir src touch src/index.js touch src/schema.graphql
Creating Application Schema
The GraphQL server needs to have a Schema that helps identify the operations that can be carried out on the server. For this application, edit the
src/schema.graphql to look like this:
type Query{ user(id: ID!): User } type Mutation { signup(name: String!): User! }
In this case, the schema allows for the following:
- Fetch a single user based on its
id
Downloading Prisma Database Schema
If you look at the schema definition above, you can see that the
User is not defined. Ideally, you could redefine the
User type in the schema but since there already exists a definition in the Prisma service created earlier, we will use that instead to prevent us from having multiple locations for one definition.
Install the GraphQL CLI by running:
npm install -g graphql-cli
and then create a
.graphqlconfig in the root directory of the project and update it as follows:
touch .graphqlconfig.yml
projects: app: schemPath: src/schema.graphql extensions: endpoints: default: prisma: schemaPath: src/generated/prisma.graphql extensions: prisma: prisma/prisma.yml
You can download the Prisma schema by running the following command:
graphql get-schema --project prisma
Then, update the
src/schema.graphql to look like this:
import User from './generated/prisma.graphql' type Query{ user(id: ID!): User } type Mutation { signup(name: String!): User! }
You have the Prisma schema downloaded in the
/src/generated/prisma.graphql file.
Instantiating Prisma bindings and Implementing Resolvers
The next thing to do is to ensure that Prisma’s GraphQL API can be accessed by the resolvers using the
prisma-binding. To do this, update the
index.js file to look like this:
// src/index.js const { GraphQLServer } = require('graphql-yoga') const { Prisma } = require('prisma-binding') const resolvers = { Query: { user: (_, args, context, info) => { // ... } }, Mutation: { signup: (_, args, context, info) => { // ... } } } const server = new GraphQLServer({ typeDefs: 'src/schema.graphql', resolvers, context: req => ({ req, prisma: new Prisma({ typeDefs: 'src/generated/prisma.graphql', endpoint: 'PRISMA_ENDPOINT', }), }), }) server.start(() => console.log(`GraphQL server is running on`))
Note that the
PRISMA_ENDPOINTcan be obtained from your
/prisma/prisma.ymlfile.
Update the resolvers in your application by adding the following into your
index.js file:
// src/index.js [...] const resolvers = { Query: { user: (_, args, context, info) => { return context.prisma.query.user( { where: { id: args.id, }, }, info ) } }, Mutation: { signup: (_, args, context, info) => { return context.prisma.mutation.createUser( { data: { name: args.name, }, }, info ) } } } [...]
Update your
package.json file as follows:
{ "name": "scotch-prisma-demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "node src/index.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "graphql-yoga": "^1.14.7", "prisma-binding": "^2.0.2" } }
Here, we added the
start script to the project. Now, you can run the application by using this command:
npm start
This starts the server and the playground for use. When you head over to the browser and navigate to
localhost:4000, you get the following:
Now that we have built the GraphQL server over the Prisma Service, the playground no longer connects directly to the Prisma Endpoint but to the application itself. With this, the client is restricted to only performing actions that have been defined in the new schema on the server.
Conclusion
In the article, we have seen how to create a Prisma service that converts a database to a GraphQL API and how to use GraphQL Yoga and Prisma Binding to build a GraphQL server on the service for use by client applications. Here’s a link to the GitHub repository if interested. Feel free to leave a comment below. | http://brianyang.com/getting-started-with-yoga-and-prisma-for-building-graphql-servers/ | CC-MAIN-2018-51 | refinedweb | 1,318 | 63.29 |
> From: Peter Donald [mailto:donaldp@apache.org]
>
>
> think I put that in there so...
>
> Each different concern (ie logging, failonerror, classloader,
> documentation) could have a different namespace. Each
> namespace would be
> passed to an appropriate handler. So attributes prefixed with
> doc: would be
> passed to DocumentHandler, attributes prefixed with log:
> would be passed to
> handler that determins how verbose target/task is etc.
>
> This way we would not have to add code to all the different tasks that
> checks if failonerror is set etc. It is all centralized in the
> engine/handlers. If we work in an interceptor architecture
> (like tomcat3.x)
> we could even have pluggable element handlers. That may have to wait
> though because it is a HUGE amount of work ;)
>
Another application for namespaces would be to associate <tasklib>s (jars
with pluggable tasks) with namespaces. That way we can avoid the problam of
name clashing when different people write their own set of tasks specific to
aparticular field.
Jose Alberto | http://mail-archives.apache.org/mod_mbox/ant-dev/200103.mbox/%3C012f01c0b2da$36ecd800$ef69883e@viquity.com%3E | CC-MAIN-2014-52 | refinedweb | 164 | 65.42 |
Graphs provide us with a very useful data structure. They can help us to find structure within our data. With the advent of Machine learning and big data we need to get as much information as possible about our data. Learning a little bit of graph theory can certainly help us with that.
Here is a Graph Analytics for Big Data course on Coursera by UCSanDiego which I highly recommend to learn the basics of graph theory.
One of the algorithms I am going to focus in the current post is called Connected Components. Why it is important. We all know clustering.
You can think of Connected Components in very layman's terms.
To put a Retail Perspective: Lets use these family IDs to provide personalized recommendations based on a family needs. We can also use this family ID to fuel our classification algorithms by creating grouped features based on family.
In Finance Perspective: Another use case would be to capture fraud using these family IDs. If an account has done fraud in past, it is highly probable that the connected accounts are also susceptible to fraud.
So enough of use cases. Lets start with a simple graph class written in Python to start up our exploits with code.
This post will revolve more around code from here onwards.
""" A Python Class A simple Python graph class, demonstrating the essential facts and functionalities of graphs. Taken from Changed the implementation a little bit to include weighted edges """ class Graph(object): def __init__(self, graph_dict=None): """ initializes a graph object If no dictionary or None is given, an empty dictionary will be used """ if graph_dict == None: graph_dict = {} self.__graph_dict = graph_dict def vertices(self): """ returns the vertices of a graph """ return list(self.__graph_dict.keys()) def edges(self): """ returns the edges of a graph """ return self.__generate_edges() def add_vertex(self, vertex): """ If the vertex "vertex" is not in self.__graph_dict, a key "vertex" with an empty dict as a value is added to the dictionary. Otherwise nothing has to be done. """ if vertex not in self.__graph_dict: self.__graph_dict[vertex] = {} def add_edge(self, edge,weight=1): """ assumes that edge is of type set, tuple or list """ edge = set(edge) (vertex1, vertex2) = tuple(edge) if vertex1 in self.__graph_dict: self.__graph_dict[vertex1][vertex2] = weight else: self.__graph_dict[vertex1] = {vertex2:weight} if vertex2 in self.__graph_dict: self.__graph_dict[vertex2][vertex1] = weight else: self.__graph_dict[vertex2] = {vertex1:weight} def __generate_edges(self): """ A static method generating the edges of the graph "graph". Edges are represented as sets with one (a loop back to the vertex) or two vertices """ edges = [] for vertex in self.__graph_dict: for neighbour,weight in self.__graph_dict[vertex].iteritems(): if (neighbour, vertex, weight) not in edges: edges.append([vertex, neighbour, weight]) return edges def __str__(self): res = "vertices: " for k in self.__graph_dict: res += str(k) + " " res += "\nedges: " for edge in self.__generate_edges(): res += str(edge) + " " return res def adj_mat(self): return self.__graph_dict
You can certainly play with our new graph class.Here we try to build some graphs.
g = { "a" : {"d":2}, "b" : {"c":2}, "c" : {"b":5, "d":3, "e":5} } graph = Graph(g) print("Vertices of graph:") print(graph.vertices()) print("Edges of graph:") print(graph.edges()) print("Add vertex:") graph.add_vertex("z") print("Vertices of graph:") print(graph.vertices()) print("Add an edge:") graph.add_edge({"a","z"}) print("Vertices of graph:") print(graph.vertices()) print("Edges of graph:") print(graph.edges()) print('Adding an edge {"x","y"} with new vertices:') graph.add_edge({"x","y"}) print("Vertices of graph:") print(graph.vertices()) print("Edges of graph:") print(graph.edges())
Vertices of graph: ['a', 'c', 'b'] Edges of graph: [['a', 'd', 2], ['c', 'b', 5], ['c', 'e', 5], ['c', 'd', 3], ['b', 'c', 2]] Add vertex: Vertices of graph: ['a', 'c', 'b', 'z'] Add an edge: Vertices of graph: ['a', 'c', 'b', 'z'] Edges of graph: [['a', 'z', 1], ['a', 'd', 2], ['c', 'b', 5], ['c', 'e', 5], ['c', 'd', 3], ['b', 'c', 2], ['z', 'a', 1]] Adding an edge {"x","y"} with new vertices: Vertices of graph: ['a', 'c', 'b', 'y', 'x', 'z'] Edges of graph: [['a', 'z', 1], ['a', 'd', 2], ['c', 'b', 5], ['c', 'e', 5], ['c', 'd', 3], ['b', 'c', 2], ['y', 'x', 1], ['x', 'y', 1], ['z', 'a', 1]]
Lets do something interesting now.
We will use the above graph class for our understanding purpose. There are many Modules in python which we can use to do whatever I am going to do next,but to understand the methods we will write everything from scratch. Lets start with an example graph which we can use for our purpose.
g = {'Frankfurt': {'Mannheim':85, 'Wurzburg':217, 'Kassel':173}, 'Mannheim': {'Frankfurt':85, 'Karlsruhe':80}, 'Karlsruhe': {'Augsburg':250, 'Mannheim':80}, 'Augsburg': {'Karlsruhe':250, 'Munchen':84}, 'Wurzburg': {'Erfurt':186, 'Numberg':103,'Frankfurt':217}, 'Erfurt': {'Wurzburg':186}, 'Numberg': {'Wurzburg':103, 'Stuttgart':183,'Munchen':167}, 'Munchen': {'Numberg':167, 'Augsburg':84,'Kassel':502}, 'Kassel': {'Frankfurt':173, 'Munchen':502}, 'Stuttgart': {'Numberg':183} } graph = Graph(g) print("Vertices of graph:") print(graph.vertices()) print("Edges of graph:") print(graph.edges())
Vertices of graph: ['Mannheim', 'Erfurt', 'Munchen', 'Numberg', 'Stuttgart', 'Augsburg', 'Kassel', 'Frankfurt', 'Wurzburg', 'Karlsruhe'] Edges of graph: [[]]
Lets say we are given a graph with the cities of Germany and respective distance between them. You want to find out how to go from Frankfurt (The starting node) to Munchen. There might be many ways in which you can traverse the graph but you need to find how many cities you will need to visit on a minimum to go from frankfurt to Munchen) This problem is analogous to finding out distance between nodes in an unweighted graph.
The algorithm that we use here is called as Breadth First Search.
def min_num_edges_between_nodes(graph,start_node): distance = 0 shortest_path = [] queue = [start_node] #FIFO levels = {} levels[start_node] = 0 shortest_paths = {} shortest_paths[start_node] = ":" visited = [start_node] while len(queue)!=0: start = queue.pop(0) neighbours = graph[start] for neighbour,_ in neighbours.iteritems(): if neighbour not in visited: queue.append(neighbour) visited.append(neighbour) levels[neighbour] = levels[start]+1 shortest_paths[neighbour] = shortest_paths[start] +"->"+ start return levels, shortest_paths
What we do in the above piece of code is create a queue and traverse it based on levels. We start with Frankfurt as starting node. We loop through its neighbouring cities(Menheim, Wurzburg and Kassel) and push them into the queue. We keep track of what level they are at and also the path through which we reached them. Since we are popping a first element of a queue we are sure we will visit cities in the order of their level.
Checkout this good post about BFS to understand more about queues and BFS.
min_num_edges_between_nodes(g,'Frankfurt')
({'Augsburg': 3, 'Erfurt': 2, 'Frankfurt': 0, 'Karlsruhe': 2, 'Kassel': 1, 'Mannheim': 1, 'Munchen': 2, 'Numberg': 2, 'Stuttgart': 3, 'Wurzburg': 1}, {'Augsburg': ':->Frankfurt->Mannheim->Karlsruhe', 'Erfurt': ':->Frankfurt->Wurzburg', 'Frankfurt': ':', 'Karlsruhe': ':->Frankfurt->Mannheim', 'Kassel': ':->Frankfurt', 'Mannheim': ':->Frankfurt', 'Munchen': ':->Frankfurt->Kassel', 'Numberg': ':->Frankfurt->Wurzburg', 'Stuttgart': ':->Frankfurt->Wurzburg->Numberg', 'Wurzburg': ':->Frankfurt'})
I did this example to show how BFS algorithm works. We can extend this algorithm to find out connected components in an unconnected graph. Lets say we need to find groups of unconnected vertices in the graph.
For example: the below graph has 3 unconnected sub-graphs. Can we find what nodes belong to a particular subgraph?
#We add another countries in the loop graph = Graph(g) graph.add_edge(("Mumbai", "Delhi"),400) graph.add_edge(("Delhi", "Kolkata"),500) graph.add_edge(("Kolkata", "Bangalore"),600) graph.add_edge(("TX", "NY"),1200) graph.add_edge(("ALB", "NY"),800) g = graph.adj_mat() def bfs_connected_components(graph): connected_components = [] nodes = graph.keys() while len(nodes)!=0: start_node = nodes.pop() queue = [start_node] #FIFO visited = [start_node] while len(queue)!=0: start = queue[0] queue.remove(start) neighbours = graph[start] for neighbour,_ in neighbours.iteritems(): if neighbour not in visited: queue.append(neighbour) visited.append(neighbour) nodes.remove(neighbour) connected_components.append(visited) return connected_components print bfs_connected_components(g)
The above code is similar to the previous BFS code. We keep all the vertices of the graph in the nodes list. We take a node from the nodes list and start BFS on it. as we visit a node we remove that node from the nodes list. Whenever the BFS completes we start again with another node in the nodes list until the nodes list is empty.
[['Kassel', 'Munchen', 'Frankfurt', 'Numberg', 'Augsburg', 'Mannheim', 'Wurzburg', 'Stuttgart', 'Karlsruhe', 'Erfurt'], ['Bangalore', 'Kolkata', 'Delhi', 'Mumbai'], ['NY', 'ALB', 'TX']]
As you can see we are able to find distinct components in our data. Just by using Edges and Vertices. This algorithm could be run on different data to satisfy any use case I presented above.
But Normally using Connected Components for a retail case will involve a lot of data and you will need to scale this algorithm.
Connected Components in PySpark
Below is an implementation from this paper on Connected Components in MapReduce and Beyond from Google Research. Read the PPT to understand the implementation better. Some ready to use code for you.
def create_edges(line): a = [int(x) for x in line.split(" ")] edges_list=[] for i in range(0, len(a)-1): for j in range(i+1 ,len(a)): edges_list.append((a[i],a[j])) edges_list.append((a[j],a[i])) return edges_list # adj_list.txt is a txt file containing adjacency list of the graph. adjacency_list = sc.textFile("adj_list.txt") edges_rdd = adjacency_list.flatMap(lambda line : create_edges(line)).distinct() def largeStarInit(record): a, b = record yield (a,b) yield (b,a) def largeStar(record): a, b = record t_list = list(b) t_list.append(a) list_min = min(t_list) for x in b: if a < x: yield (x,list_min) def smallStarInit(record): a, b = record if b<=a:>=a:>
Or Use GraphFrames in PySpark
To Install graphframes:
I ran on command line: pyspark --packages graphframes:graphframes:0.5.0-spark2.1-s_2.11 which opened up my notebook and installed graphframes after i try to import in my notebook.
The string to be formatted as : graphframes:(latest version)-spark(your spark version)-s_(your scala version).
Checkout this guide on how to use GraphFrames for more information.
from graphframes import * def vertices(line): vert = [int(x) for x in line.split(" ")] return vert vertices = adjacency_list.flatMap(lambda x: vertices(x)).distinct().collect() vertices = sqlContext.createDataFrame([[x] for x in vertices], ["id"]) def create_edges(line): a = [int(x) for x in line.split(" ")] edges_list=[] if len(a)==1: edges_list.append((a[0],a[0])) for i in range(0, len(a)-1): for j in range(i+1 ,len(a)): edges_list.append((a[i],a[j])) edges_list.append((a[j],a[i])) return edges_list edges = adjacency_list.flatMap(lambda x: create_edges(x)).distinct().collect() edges = sqlContext.createDataFrame(edges, ["src", "dst"]) g = GraphFrame(vertices, edges) sc.setCheckpointDir(".") # graphframes uses the same paper we referenced apparently cc = g.connectedComponents() print cc.show()
The GraphFrames library implements the CC algorithm as well as a variety of other graph algorithms.
The above post was a lot of code but hope it was helpful. It took me a lot of time to implement the algorithm so wanted to make it easy for the folks.
If you want to read up more on Graph Algorithms here is an Graph Analytics for Big Data course on Coursera by UCSanDiego which I highly recommend to learn the basics of graph theory. | https://www.tefter.io/bookmarks/65877/readable | CC-MAIN-2021-04 | refinedweb | 1,880 | 67.04 |
Programming Books
Java Programming
Books
JSP Programming Books...
Java Sever Faces Books
J2EE Design Patterns Books
Servlets Books...
Programming Books
A Collection of Large number of
Free
index
Programming Tutorials : Many
Free Programming tutorials
Many links to the online programming tutorials. These
programming tutorial links will help you in increasing your programming skills.
Database books
Database books- Page 20
... environments such as .NET, Workspace, PowerBuilder, Java?, Eclipse, etc...;
Oracle XML DB and J2EE features Security Implementation
The XMLNews
Java Programming Books
Java Programming Books
... this brief: This Java programming stuff is a lot easier than it looks. I'm... understanding of the programming model inherent in the J2EE platform
Free Java Books
Free Java Books
Sams Teach Yourself Java 2 in 24 Hours
As the author of computer books, I spend a lot... the
whip. So I'll keep this brief: This Java programming stuff is a lot easier than
Programming Tutorials Links
| Tutorials
Books | VB Tutorial
| Java Script Tutorial
Ajax Tutorial |
Dojo Tutorials |
Programming
Books...
Programming | Java Beginners Examples
| Applet Tutorials
| Awt 6 Index
Chapter 6
Applets, HTML, and GUI's
JAVA IS A PROGRAMMING LANGUAGE DESIGNED for
networked computers and the World Wide Web. Java applets...
contained in objects. In Java, event-oriented programming is object-oriented
Java Programming: Chapter 10 Index
connections. In Java, input/output involving files and
networks is based...:
Section 1: Streams, Readers, and Writers
Section 2: Files
Section 3: Programming with Files
Section 4: Networking
Section 5: Threads and Network Programming
Java Programming: Chapter 7 Index
Chapter 7
Advanced GUI Programming
IT'S POSSIBLE TO PROGRAM A WIDE... to Swing.
Although the title of the chapter is "Advanced GUI Programming... look at two other programming techniques, timers and threads.
The material 11 Index
look at two advanced programming
techniques, recursion and linked data...
Section 4: Binary Trees
Section 5: A Simple Recursive-descent Parser
Programming...
| Previous Chapter
| Main Index
JSF Books
programming, and had lived to tell the tale-David in Graphic Java....
Books
of Core java Server Faces...JSF Books
J2EE - Java Beginners
J2EE Programming What i need to learn to start programming in J2EE
Java & JEE books Page16
Java & JEE books Page16
...
The Java 2 Platform, Enterprise Edition (J2EE), has rapidly established a new... technical reference for the Java programming language. If you want to know the precise
J2EE
J2EE What is J2EE?
J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide
J2ME Books
;
Free
J2ME Books
J2ME programming camp... of programming concepts. It also provides a step-by-step Java Card applet...;
Wireless
Java Programming with J2ME
Perfect
EJB Books
, the sheer magnitude of making a Java 2 Enterprise Edition (J2EE) application work.... He commits none of the popular sins of J2EE books (he neither tries to teach basic Java, neglects the design issues that are critical to J2EE projects, nor
Java & JEE books Page17
Java & JEE books Page17
... how to create and run Java? 2 Platform, Enterprise Edition (J2EE? platform... a familiarity with Java programming methods and tools, in particular Enterprise Java
CORBA and RMI Books
;
Client/Server Programming with Java.../Server Programming with Java and CORBA is the book to read if you're thinking about... other programming books, CodeNotes drills down to the core aspects of a technology
j2ee - Java Beginners
j2ee why we are using the j2ee? Hi friend,
J2EE Stands for Java 2 Enterprise Edition.
J2EE is an environment for developing and deploying enterprise applications.
J2EE specification is defined by Sun
Database books
and logic.
* You can use the Java programming language as an integral part...
Database books- Page 9
ASA Programming Interface Guide
This chapter provides
Database books
and storing both data and logic.
* You can use the Java programming language...
Database books- Page 6
....
The Java adaptive server enterprise
This book describes how
J2EE - Java Interview Questions
J2EE What is J2EE architecture? Hi friend,
The Java? 2 Platform, Enterprise Edition (J2EE) provides a standard for developing... solutions. The J2EE specification satisfies these challenges by providing
JSP Programming Books
Java Server Programming, J2EE Edition, by multiple authors (see below...
JSP Programming Books
... JSP is a key component of the Java 2 Platform Enterprise Edition (J2EE
J2EE Tutorial - Introduction
presentation of what & why of J2EE.
(It is better for aspiring Java...
security.)
J2EE is not the Java , that
comprises... in BDK, Swing etc.( topics covered in great detail by
books on Core Java
Struts Books
applications in J2EE. A lot of books have emerged to satisfy the appetite of avid Struts...;
Java
Books Struts in Action
While many Struts... Java programming skills by learning to apply the Struts framework. Get a fresh
Java XML Books
number of Java programming books on the market. This presents potential Java book...
Java XML Books
Java
and XML Books
One night
J2EE Design Patterns Books
Tomcat Books
Tomcat Books
... enterprise Java developers will have a complete reference to setting up, running... with Java servlets and JavaServer Pages.
Tomcat
Book Information
Servlets Books
, JavaServer Pages (JSP), Apache Struts, JavaServer Faces(JSF), or Java programming... amazon.com and fatbrain.com as one of the ten best computer programming books...;
Java
Servlets Programming
Aimed
J2EE Interview Questions
;
Question: What is J2EE?
Answer: J2EE Stands for Java 2... in the Java
programming language and are compiled in the same way as any...;standard" Java classes is that J2EE components are
assembled
Programming: Body Mass Index - Dialog
Java NotesProgramming: Body Mass Index - Dialog
Name ________________________________________
Description
Write a program that computes the user's Body Mass Index (BMI).
BMI is a commonly used formula which shows the relationship
Ajax Books
,
Ajax Patterns and Best Practices by Christian Goss, Apress Books Ajax Programming... Java+XML books under his belt and the Freemans are responsible for the excellent...
Ajax Books
AJAX
J2EE Tutorial
In this section we will read about Java J2EE.
This section is for those who... or large.
Requirements To Develop Java J2EE based application... need to :
Familiar with Java Programming Language .
JDK ( Java
J2EE interview questions page1
J2EE interview questions page1
What is J2EE?
J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set
E-Books: C-and-C++-books
;
Java-JEE-books
This guide contains advanced configuration...
E- Books
Collection of best ebooks available on the internet.
Browser the following list to find the books for you.
C-and-C
Books Of Java - Java Beginners
Books Of Java Which Books Are Available for Short / Quick Learning
My Favorite Java Books
Java NotesMy Favorite Java Books
My standard book questions
When I think... language and want to
learn Java, these are good books.
Head First Java... or are a C++ programming converting
to Java, this is a really good book, or set
Linux and Unix Books page2
Linux and Unix Books page2
Network programming under Unix systems
This document is meant to provide people who already have a knowledge of Programming in C
index of javaprogram
index of javaprogram what is the step of learning java. i am not asking syllabus am i am asking the step of program to teach a pesonal student.
To learn java, please visit the following link:
Java Tutorial
Linux and Unix Books page5
Linux and Unix Books page5
... framework for programming reliable distributed systems. Protocol composition... email, you know about spam. There are whole books on how to stop it, and it's even
Linux and Unix Books page1
Linux and Unix Books page1
... their capabilities to Unix, Linux, Java, and Mac platforms.
... a fairly powerful programming language. A shell program, called a script
MySQL Books
MySQL Books
List of many MySQL books.
MySQL Books
Hundreds of books and publications related to MySQL are in circulation that can help you get the most of out MySQL. These books
J2EE clients
J2EE clients What are types of J2EE clients?
Following are the types of J2EE clients:
Applets.
Application clients.
Java Web Start-enabled rich clients, powered by Java Web Start technology.
Wireless clients, based
Mysql Date Index
Mysql Date Index
Mysql Date Index is used to create a index on specified table. Indexes in
database are similar to books in library. It is created on one or more
Perl Programming Books
Perl Programming Books
... programming projects that highlight some of the moderately advances features of Perl, like... a marriage of two compatible yet unlikely partners. Extreme Programming (XP
J2EE Tutorial - Session Tracking Example
J2EE Tutorial - Session Tracking Example
...;
// THIS IS A JAVA BEAN.
import java.util.*;
public class... studying EJB, the most important topic in J2EE, there will be
reference
Java & JEE books
Java & JEE books
...
This is an introduction to using the Java programming language in concurrent... with the production of software artefacts using the programming language Java, a process
Body Mass Index (BMI)
Java: Body Mass Index (BMI)
The Body Mass Index program is divided into two files, the main program...
// File: bmi/BMI.java
// Description: Compute Body Mass Index
Open Source Books
Review
Books on programming languages are fairly straightforward...
Open Source Books
Open Books
O'Reilly has published a number of Open Books--books with various forms of "open" copyright--over the years
Java Script Programming Books
Java Script
Programming Books
Sams
Teach Yourself Java... tools such as HTML have been joined by true programming
languages
j2ee - Java Beginners
j2ee class Interviews Question page8,J2EE Interviews Guide,J2EE Interviews
that run on the server. J2EE components are written in the Java programming...;
What is J2EE ?
Java 2 Platform, Enterprise Edition.
.... The difference between J2EE components and "standard" Java classes is that J2EE
about J2EE. - Java Beginners
about J2EE. I know only core Java ... what chapter I will be learn to know about J2EE
Java & JEE books Page18
Java & JEE books Page18
Advanced Programming for the Java 2 Platform
As an experienced developer on the Java platform, you undoubtedly know how fast moving
Misc.Online Books
of a Java computer or a Haskell computer. For the programmer, the programming... takes a deeper look at object-oriented programming than previous Lisp books, showing...
Misc.Online Books
Java & JEE books Page1
Java & JEE books Page1
.... The J2EE Engine is the primary engine for the usage type Application Server Java... and recommendations for the AS-Java are equally relevant to securing the J2EE Engine
J2EE Online Training
J2EE Online Training
Due to increasing significance of Java Enterprise Edition or Java 2 EE, the
need for J2EE online training has increased manifold. As this j2ee platform is commonly used for server programming hence most
what is the difference in java and j2ee
what is the difference in java and j2ee Hi, Please tell me:
1. What is the difference between Java and Core Java and
2. Difference between Java and J2EE
J2EE - Java Interview Questions
J2EE How do we call destroy() in service
Web Sphere Books
;
Enterprise
Java Programming With IBM WebSphere Books...;
Introduction to Java Using WebSphere
Books
A step-by-step, hands-on approach to Java programming using WebSphere that makes coding Java simpler
Free JSP Books
Professional Java Server Programming, J2EE Edition, by multiple authors (see below.../j2ee.
More
Servlets and JavaServer Pages
The Java 2... is required, but the reader is assumed to be familiar with the Java programming
Java Programming: Other Features of Java
to cover all the features
of the Java programming language, or even to give... of the book is to explain programming, not
Java. Nevertheless, it can serve... continue your study of Java programming.
JAR Files and Resources
Each
about J2EE. - Java Beginners
about J2EE. I know only core Java ... what chapter I will be learn to know about J2EE. Hi Friend,
Please visit the following link:
Thanks
Database books
Database books- Page 8
... with the PL/1 programming language and know how to write PL/1 programs under...
Open ServerConnect is a programming environment that lets you create mainframe
Java & JEE books Page12
Java & JEE books Page12
Introduction to Programming Using
Java, Fourth Edition ... of the Java Programming Language
The Java platform consists
index - Java Beginners
index Hi could you pls help me with this two programs they go hand in hand.
Write a Java GUI application called Index.java that inputs several... the number of occurrences of the character in the text.
Write a Java GUI
Database books
Database books- Page 18
The server enterprise monitor client-library programmer's.... It is an application programming interface that enables you to write client
Database books
Database books- Page 14
Server Administration Guide for DirectConnect
This chapter..., and Open Database Connectivity (ODBC) application programming interfaces (APIs
Java & JEE books Page5
Java & JEE books Page5
Advanced Java Programming Tutorial
As indicated in the title..., which are not covered in the J2EE 1.4 Tutorial:
* The Java
Database books
Database books- Page 11
... Programmer's reference
Java Database Connectivity (JDBC) from the Java... program interface (API) that allows Java applications to access multiple database
Java server Faces Books
Java server Faces
Books
Java
server Faces...;
Store-Java
Buy two books direct from O'Reilly and get
J2EE Development-zen Platform
development and runtime environment for J2SE and J2EE (Java 2 Platform,
Standard... J2EE Development-zen Platform
... for the
development of internet, intranet, web service or B2B applications with Java.
Companies
Java arraylist index() Function
Java arrayList has index for each added element. This index starts from 0.
arrayList values can be retrieved by the get(index) method.
Example of Java Arraylist Index() Function
import
Java Programming: Section 6.2
. And the <CITE> style
tag is meant for titles of books.
You can get....
The Applet tag and Applet Parameters
The <APPLET> tag is used to add a Java...
a number of smaller files. Your Java development system is probably
capable
j2ee - Java Server Faces Questions
J2EE EAR Structure What is the structure for J2EE EAR Interview Questions
j2ee what are the services does the weblogic server provide in project development
OR
what are the services we take from the weblogic during project development
Java Programming: Solution to Programming Exercise
Solution for
Programming Exercise 9.4
THIS PAGE DISCUSSES ONE POSSIBLE SOLUTION to
the following exercise from this on-line
Java textbook...
[ Exercises
| Chapter Index
| Main Index
Java Programming: Solution to Programming Exercise
Solution for
Programming Exercise 9.3
THIS PAGE DISCUSSES ONE POSSIBLE SOLUTION to
the following exercise from this on-line
Java textbook...;IV", "I" };
For each index i, numbers[i] is the int equivalent
J2EE Interviews Question page9,J2EE Interviews Guide,J2EE Interviews
;
What is Java 2 Platform, Enterprise Edition (J2EE) ?
An environment...
J2EE Interviews Question page9
What is J2EE server ?
The runtime portion
Some Notes on Java Programming Environments
Appendix 2:
Some Notes on Java Programming Environments
ANYONE WHO...-line environments. All programming
environments for Java require some text...
that I am not an expert on Java programming environments. I am including
Java Reference Books
.
Java network programming books.... In this review, I'll examine a crop of books that want to be your Java network programming...
Java Reference
Books
Free JSP download Books
;
Java Servlets and JSP
free download books... you can learn Java web programming using this book's fresh approach, real-world... required the use of several books as well as online tutorials and the Java
Java Programming: Solution to Programming Exercise
Solution for
Programming Exercise 2.1
THIS PAGE DISCUSSES ONE POSSIBLE SOLUTION to
the following exercise from this on-line
Java textbook... main()
} // end class
[ Exercises
| Chapter Index
Ask Questions?
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions. | http://www.roseindia.net/tutorialhelp/comment/58416 | CC-MAIN-2013-20 | refinedweb | 2,616 | 57.06 |
3.6.1 Main function [basic.start.main] ][]) { /* ... */ }
In the latter form argc shall be the number of arguments passed to the program from the environment in which the program is run. If argc is nonzero these arguments shall be supplied in argv[0] through argv[argc-1] as pointers to the initial characters of null-terminated multibyte strings (ntmbs s) ([multibyte.strings]) and argv[0] shall be the pointer to the initial character of a ntmbs that represents the name used to invoke the program or "". The value of argc shall be non-negative. The value of argv[argc] shall be 0. [ Note: It is recommended that any further (optional) parameters be added after argv. — end note ]
The function main shall not be used within a program. The linkage ([basic.link]) of main is implementation-defined. A program that defines main as deleted or that declares main to be inline, static, or constexpr is ill-formed. The name main is not otherwise reserved. [ Example: member functions, classes, and enumerations can be called main, as can entities in other namespaces. — end example ]
Terminating the program without leaving the current block (e.g., by calling the function std::exit(int) ([support.start.term])) does not destroy any objects with automatic storage duration ([class.dtor]). If std::exit is called to end a program during the destruction of an object with static or thread storage duration, the program has undefined behavior.; | https://timsong-cpp.github.io/cppwp/n3337/basic.start | CC-MAIN-2021-17 | refinedweb | 239 | 58.48 |
How to convert a class to another class type in C++?
Pre-requisite: Type Conversion in C++, Advanced C++ | Conversion Operators
Through class conversion, one can assign data that belongs to a particular class type to an object that belongs to another class type.
Example:
Let there be two classes ‘A’ and ‘B’. If we want to allocate the details that belong to class ‘A’ to an object of class ‘B’ then this can be achieved by –
B(object of class B) = A(object of class A)
where ‘=’ has been overloaded for objects of class type ‘B’.
Class conversion can be achieved by conversion function which is done by the use of operator overloading.
Example:
GeeksforGeeks GeeksforGeeks
Recommended Posts:
- Can a C++ class have an object of self type?
- std::any Class in C++
- std::string class in C++
- Array class in C++
- std:: valarray class in C++
- Structure vs class in C++
- std::uniform_int_distribution class in C++
- Difference between namespace and class
- C++ string class and its applications
- C++ String Class and its Applications | Set 2
- Virtual base class in C++
- What all is inherited from parent class in C++?
- Why is the size of an empty class not zero in C++?
- Simulating final class in C++
- Friend class and. | https://www.geeksforgeeks.org/how-to-convert-a-class-to-another-class-type-in-c/ | CC-MAIN-2019-30 | refinedweb | 211 | 65.25 |
See me blather about software development, Gadgets, Technology, Fatherhood, plus anything else that gets me going.
Disclaimer: This is not a documented or supported feature. That means it was not tested, and might not work, and if it doesnt please dont call Microsoft Support and complain. If it does work, then hoorah.
Introduction
Ever stepped into a function you didn’t want to? Like an ATL or MFC CString constructor for example? Or a conversion operator you are really not interested in? Well there is a way to tell the Visual Studio debugger to never, ever step into a particular function. This is not a documented option, but the information is available in newgroups, but the changes from 6.0 to 7.0 have caused a great deal of confusion. Here is the real story for 7.0 (and 7.1).
Visual C++ 6
Visual C++ 6 users should run over to to get the scoop. Life was simple in VC6, but due to the fact that the ReadPrivateProfile API was used to read the autoexp.dat file, there were some limitations on what could and could not go in the file, especially equals signs. For this and other reasons (eg non-Power users cannot write to autoexp.dat on an NTFS drive) the information was moved to the registry for 7.0.
Visual Studio 7.0/7.1
The new list lives in the registry underneath HKCU\Software\Microsoft\VisualStudio\7.0\NativeDE\StepOver (use 7.1 if you are using Visual Studio 2003). The two last keys will not exist by default. Underneath this you need to place a list of string values of decimal numbers, paired with regular expressions. Figure 1 shows an example of this from my VS 2003 machine. Using a screenshot is clearer than showing the contents of a .reg file as .reg files need extra escape characters which renders them much more meaningless. (I will show the matching .reg file later). Due to an “oversight” (translation: bug) the items are evaluated in descending numeric order e.g. the “20” rule will match before the “10” rule. If you look at the example you can see that I have one rule, and that is any function name that starts with “ATL::” will not be stepped into.
The registry really contains “ATL\:\:.*=nostepinto” : lets dig into that a bit more. Function names are specified using regular expression syntax, the same as the rest of Visual Studio. In regex you need to escape colon characters, hence the two “\:” sequences. The “.*” is regex for “zero or more of any character” ie a general wildcard. The equals sign marks the end of the function name, and “nostepinto” means functions matching this patter will not be stepped into. The only other option for the right-hand-side is “stepinto” which performs the exact opposite function: it tells the debugger you want to step into these functions no matter what other entries (that follow this one) say.
Having decoded the screenshot, here is the .reg file that was made when I exported it. Note it is more complicated due to the escaping rules for .reg files.
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\7.1\NativeDE\StepOver]"20"="ATL\\:\\:.*=nostepinto"
Visual Studio 8.0 (Whidbey)
Not sure when it happened, but beta 2 anyway requires this to be in HKLM not HKCU so the full reg path is now HKLM\Software\Microsoft\VisualStudio\8.0\NativeDE\StepOver. Yes, that means you need to be an Admin to set it up, and it is set for all users of your box. That's what happens when features aren't "official".
Advanced Features
The debugger supports additional escapes over and above the normal Visual Studio regular expression syntax, but note that even I have never tried these so YMMV. I got this list from comments in the source. Well I'm sure you know that such things cannot always be trusted 100%, but here they are anyway:
\cid A C/C++ identifier
\funct A C/C++ function name
\scope A set of class/namespace specifiers for a function (e.g. ATL::CFoo::CBar::)
\anything any string
\oper A C/C++ operator
Additional Examples
These examples are shown exactly how you would enter them via RegEdit, not in the more cumbersome .reg format. The numbers are arbitrary, but in the multi-line examples their relative values are important to get the right ordering.
Don’t step into members of CString[AWT] etc:
1 \scope:CString.*\:\:.*=NoStepInto
Don’t step into overloaded operators:
10 \scope:operator\oper:=NoStepInto
Don’t step into ATL:: except for CComBSTRs non-operator members:
20 ATL\:\:CComBSTR::\funct:=StepInto
10 ATL\:\:.*=NoStepInto
Don’t step into templated things, unless they are merely templated functions in a non-templated class:
20 \scope:\funct:=StepInto
10 .*[\<\>].NoStepInto
Notes
MSFT disclaimer: This posting is provided "AS IS" with no warranties, and confers no rights.
This post is popular with spammers so I am closing it for new comments. | http://blogs.msdn.com/andypennell/archive/2004/02/06/69004.aspx | crawl-002 | refinedweb | 839 | 66.54 |
When I edit a XAML file in Visual studio and look at a bound element like this...
<Entry Text="{Binding Username}" />
I see a little squiggly green line under the first two letters of Username. This is my beloved ReSharper letting me know that it "Cannot resolve symbol 'Username' due to unknown DataContext".
This started to annoy me so I did a little research. I found that if I added the following properties to the ContentPage element the little warning disappeared. (this is used in WPF development)
xmlns:d="" xmlns:mc="" mc:Ignorable="d" xmlns:rootViewModel="clr-namespace:MyApp.ViewModels;assembly=MyApp" d:DataContext="{d:DesignInstance rootViewModel:LoginViewModel}"
Not only did the annoying warnings disappear but many benefits were unlocked! (available only with ReSharper)
This makes the XAML more integrated with the code and could reduce defects and improve efficiency. I was preparing to write a blog post highlighting this trick. I figured I better actually run the app first, just as a sanity check, to make sure it runs and... Crash! ... "Xamarin.Forms.Xaml.XamlParseException: MarkupExtension not found for d:DesignInstance". Reality bytes.
If Xamarin.Forms was modified to ignore these designer XAML properties, it would unlock some great development features for ReSharper users. (There may be a way to enable these features without Resharper but might be more involved. It is so close with ReSharper)
Hi @Mobile_Dan ,
please report a bug at http:\bugzilla.xamarin.com
Thanks Cliff.
I filed a bug here:
Dan
100% agree! I just landed on this issue, myself. I have been coding luckily away in the designer/Xaml and just tried to launch it and landed on this issue. It is so common/ubiquitous in WPF-land that I really didn't think twice about this. Please consider adding support for this very awesome (and expected!!) feature.
I do have to say that I have been MOST impressed with the development/design experience w/ ReSharper and Xamarin.Forms. It has been quite amazing. This little hiccup has been really the only rub so far. I'd rate it at a surprising 90% experience when compared to WPF. 10% going to this problem.
FWIW, keep your eyes on this thread... we might have found a workaround in the meantime (and feel free to "me too" to help nudge it along,
):
Cheers for this heads-up. I'm another happy resharper forms user, didn't even think this was possible.
We use design time data very successfully in WPF. I did get the BindingContext setup in XAML using a ViewModelLocator and MVVM Light rather than setting it in code using code.
BindingContext="{Binding Source={x:Static mvvm:App.Locator}, Path=Search}"
WOW! The owner of that project got that feature in already! Pretty impressive. You can see the documentation here:
I have installed the latest version (available today) and verified that it works and strips out the DesignInstance and all d: namespace elements. Pretty awesome.
Thanks Michael!
I have the NuGet package you referenced, XCC, successfully removing design time properties from XAML in Visual Studio.
Unfortunately XCC does not compile in Xamarin Studio on the Mac. I filed an issue with the author on GitHub.
I do most Xamarin development in Visual Studio but occasionally run iOS from Xamarin Studio on the Mac. I won't use any component that doesn't also work in Xamarin Studio so I'll hold off using XCC for now.
XCC might be a good option for those who only use Visual Studio. Note: I did not try XCC on Xamarin Studio on the PC.
I'll report back here if XCC starts working on Xamarin Studio on the Mac.
Hi, i'm trying to use this technique, but it doesn't seem to help for
ListViewitem templates. I still get a squiggly for property bindings i have in a TextCell. Any ideas here?
I got it working by declaring the designer DataContext for the TextCell like this...
thanks @Mobile_Dan , that helps.
Is this only Visual Studio related or would that also help us poor xamarin studio guys?
I was only able to get the link between XAML and the bound class working in Visual Studio with ReSharper. I briefly tried it in Xamarin Studio and I don't see that the designer properties mentioned above have any beneficial effect. Unfortunately they do not compile so if you're running the same project in Visual Studio and Xamarin Studio (as I do) these designer properties will not run in Xamarin Studio.
The designer properties have a beneficial effect only in Visual Studio with ReSharper but do not run from Visual Studio. @MichaelDeMond noted that a NuGet Package for Visual Studio called XCC will remove these designer attributes allowing the project to run .
I wasn't able to get XCC to work in Xamarin Studio on the Mac. I filed an issue with the author on GitHub. (XCC would not get the link working between XAML and the bound class but at least designer attributes would be stripped out allowing the project to run)
For now I am using XCC on Visual Studio and occasionally when I run in Xamarin Studio, I use a global search replace tool to remove the XAML attributes that cause problems.
I am searching in all XAML files and removing the following two string expressions:
I am using a tool called Search and Replace but there are many other options including Xamarin Studio itself.
I'm experiencing the same issue with xcc in Xamarin Studio. It would be great if this could be fixed.
Same issue, it doesn't work with Xamarin Studio. I work on VS, but my co-worker wants to develop on OSX.
I also have this issue
2019 and the exception still appearing Xamarin.Forms.Xaml.XamlParseExceptionPosition 13:14. : MarkupExtension not found for d:DesignInstane | https://forums.xamarin.com/discussion/comment/108135/ | CC-MAIN-2019-47 | refinedweb | 974 | 56.66 |
Things I learned about zip files
In an effort to advance my python skills, I spent some time slowly pecking away at the puzzles on pythonchallenge. I got stuck on most of the challenges, and either had to search for a hint, or ask for help from a friend, or both. This latest one was particularly instructive, and it had to do with zipfiles.
I thought I knew what zip files were. I have used them since grad school, for transferring folders via email, and for compression. I used various utilities and command-line tools to deal with zipping and unzipping. But I never needed to know how they worked.
Then I got stuck for a while because I was looking specifically for a pythonic solution for zip files.
Things I Learned and How I Learned Them
1. Pydoc != online documentation for some libraries
For some python modules, the docstrings are great, and save you the work of having to hunt for the right version of the online documentation. Sometimes the docstrings are actually even better than the docs.
If you do this:
pydoc zipfile.is_zipfile
You’ll get this:
zipfile.is_zipfile= is_zipfile(filename) Quickly see if a file is a ZIP file by checking the magic number. The filename argument may be a file or file-like object too
I had gotten out of the habit of checking docstrings, because sometimes the docstrings are nonexistent, and then your best bet is to:
- Ask google
- Find the source code, and hope it’s really easy to understand
- Ask friends if they know, or if they can recommend something more usable
2. Sometimes wikipedia fills in all the stuff the documentation skipped over.
Some things I needed to know were actually easier to find out about on wikipedia.
I did not know that there is such a thing as a magic number, and that the one for ZIP actually spells out PK, for Phil Katz, the author of PKZIP.
3. It’s not actually cheating to use unix tricks.
The command “file” will give you information about the filetype. So if you download something and you’re not sure what it is, or you just want to verify that it’s what you thought it should be (say, before you decompress it), try this first.
file myfile.zip
returns something like this:
myfile.zip: Zip archive data, at least v2.0 to extract
A friend recommended this nice tool called xxd, which gives you a hex dump of a file (even on Mac OSX!).
This can be useful if you suspect there is text hidden in a file that is otherwise only binary or not human-readable.
4. Some older modules haven’t been updated in a long time.
The zip file format was invented ~20 years ago (1993), which means it doesn’t contain a way to work with these chunks of data in memory. So you have to save the whole thing to a file in order to do anything.
It turns out that file-like objects can be a pretty vague way to describe what kind of input a method can handle. And the error messages don’t say what I really needed to hear, which was something like:
Please stop trying to give me a urllib2 response, I only eat files!
Also, unlike more modern Python modules, there were not any examples of how to use the methods. So eventually I figured out that all I had to do was this:
import urllib2 import zipfile #do what you normally do with a webpage response = urllib2.urlopen("") body = response.read() #write it to a file, or you'll be screwed with open("target.zip", 'wb') as myfile: myfile.write(body) #confirm that it's actually a zip file print zipfile.is_zipfile("channel.zip") #create a zip file object instance, so you can use the zipfile class methods myfile = zipfile.ZipFile("channel.zip")
5. Code Review.
After reading the original version of this post, one friend commented that I should I should do it his way, with StringIO.
Another friend emailed me this code block, which actually answered my original question about how to do it in-memory. As usual, the real lesson here is, if you don’t know the name of something, it’s hard to know how to look it up.
import io import sys import urllib2 import zipfile if __name__ == '__main__': zip_url = "" response = urllib2.urlopen(zip_url) body = response.read() byte_buffer = io.BytesIO(body) myfile = zipfile.ZipFile(byte_buffer) print myfile print zipfile.is_zipfile(byte_buffer) | https://szeitlin.github.io/posts/engineering/things-i-learned-about-zip-files-last-week/ | CC-MAIN-2022-27 | refinedweb | 758 | 72.26 |
WebSphere® Portal delivers a single point of access for applications and information within a customizable and extendable framework. It integrates an application deployment platform with team collaboration, content publishing, workflow, and enterprise application access services. For more information, see the developerWorks WebSphere Portal page.
Question: I installed WebSphere Studio 5.0 and updated it to 5.0.1. I downloaded the Portal Toolkit 5.0 and it will not allow me to install the Portal because I am missing 4 fixes on the WebSphere Application Server runtime (which it lists and they are also recorded in the documentation as required). My question is where can I find those fixes - I've looked everywhere and can only find one (PQ76567). The docs only refer to the CD. I also found PQ73644, but only as part of a fixpack and when I installed the fixpack, the Portal installer still did not recognize that it was installed.
Answer: These fixes are part of the WebSphere Portal V5 shipment and are not made available exclusively for Portal Toolkit V5 because it is assumed that users of the Portal Toolkit V5 also have access to WebSphere Portal V5. If this is not the case, contact IBM Service and request that these fixes be sent to you.
Question: I have two questions: 1) I need to do password aging, but do not need a high end solution like TAM. Is there a way to do this with LDAP or within the Portal? 2) I need to deploy MapPoint in a portlet - is this difficult?
Answer: 1) WebSphere Portal itself does not support the concept of password aging, and neither do LDAP servers as far as I know. 2) MapPoint is a Web Service. It should be simple enough to build a portal that renders the XML feed from the Web Service as portlet content. There are portlets available on the Portal Catalog that help you build a Web services-based portlet, but I am not familiar with any of them.
Question: I just recently installed WebSphere Portal 5.0. While experimenting with changing themes, I switched from the Admin theme to the Admin with the Left Navigation theme. In the new theme, I no longer have access to an Adminstration link, and thus cannot change it back or administer my portal. Any ideas? (submitted by cburleso@us.ibm.com)
Answer: After you install V5.0, the default administration theme is "Admin with Left Navigation", so I presume based on your description, that you had at some point changed to the "Admin" theme before now, trying to set it back. I also presume that once you exit Administration by clicking on the MyPortal link, you no longer see the Administration link. The visibility of that link should not depend on what theme you chose for Administration, but instead, depends on your authorization to enter administration. Did you make any changes to your user's authorization within the portal, such that the user no longer has rights for administering the portal?
If you still suspect that it has something to do with the theme choice you made for Administration, you can reset your choice using XMLAccess. Refer to the WebSphere Portal V5 InfoCenter on how to use XMLAccess to administer portal. Basically, you can export the portal's configuration, then locate the <content-node> element for the Administration node, and change the
themeref attribute to point back to the Admin theme's
objectid.
Question:
I have a problem with my J2EE project that has a Portlet project in it. I can deploy it at the Portal server, but when I try to invoke the portlet, a problem occurs. In the portlet, there are references to objects from the EJB project, part of the whole J2EE project
(
EGovernmentEJB.jar). In the portlet's project
manifest.mf file, there is
Class-Path: EGovernmentEJB.jar, where the objects that the portlet is referencing are located.
EGovernmentEJB.jar is also put in the
WEB-INF/lib/ directory of the Portlet project.
So when everything is deployed and I invoke the portlet (that has references to EGovernmentEJB, the EJB part), the output in the log is:
SRVE0020E: [Servlet Error]-[egovernmentportlet.EGovernmentPortlet]: Failed to load servlet: java.lang.Error: Unresolved compilation problems: The import bg.telelink.egovernment.forms.form51.dto cannot be resolved The import bg.telelink.egovernment.forms.form51.util cannot be resolved Form51ServiceConstants cannot be resolved Form51LabelsDTO cannot be resolved (or is not a valid type) for the field EGovernmentPortlet.form51LabelsDTO Form51ServiceConstants cannot be resolved The method createForm51() is undefined for the type bg.telelink.egovernment.forms.form51.ejb.Form51SessionFacadeLocal form51LabelsDTO cannot be resolved The method retreiveForm51EntireSkeleton(java.lang.Short) in the type bg.telelink.egovernment.forms.form51.ejb.Form51SessionFacadeLocal is not applicable for the arguments (short) form51LabelsDTO cannot be resolved Form51CustomDTO cannot be resolved or is not a type The method getFilledDTO(org.apache.jetspeed.portlet.PortletRequest) is undefined for the type egovernmentportlet.EGovernmentPortlet Form51DTO cannot be resolved or is not a type fo -- --
"All cannot be resolved"" refs are from
EGovernmentEJB.
(submitted by Dobri)
Answer:
This seems like a classloader visibility issue. According to the Servlet 2.3 Spec, I do not see what the defined behavior should be of specifying the Class-Path header in the WAR's
manifest.mf file. Unfortunately, I have more questions than answers. Are there other instances of
EGovernmentEJB.jar? Since other JARs contained in
WEB-INF/lib are automatically picked up, have you tried removing the Class-Path header from the portlet WAR's
manifest.mf? Could it be that there are problems with the EJB loading? Does the EJB itself have access to
EGovernmentEJB.jar? EJBs are loaded at the application server classloader level, so the EJB could not see any resources under the portlet's
WEB-INF/lib directory unless you had a copy of
EGovernmentEJB.jar under something like
/AppServer/lib, in which case you might have resolution conflicts. If you have a real EJB that requires access to these same resources, consider putting under
AppServer/lib, instead of within the portlet. The portlet should see these resources there.
Question: I would like to inquire on the integration between the Lotus products and WebSphere Portal. WebSphere Portal V5 only has Domino R5.0.12 support currently for Sametime, Quickplace integration. However, Domino is already up to R6.5 and many customers use R6.x or above. What is the recommended path for Domino R6 users to implement Lotus collaborative components to the Portal?
Answer: Sametime 3.1 is being certified with an upcoming fixpack of WebSphere Portal V5 (called 5.0.2). With Sametime 3.1, you can use Domino 6.x for your LDAP. There is a future version of QuickPlace that is designed to work with Domino 6.x. The product plans are not finalized so I cannot release any details on that, but presumably WebSphere Portal will pick up support for that level of QuickPlace when it is available.
Question: We are having Portal in Suse Linux with user authentication from MS ADS. Currently, users are added to OU in ADS and also in the Users table in DB2 local in Linux. We want to add the user to the Portal group during the self-registration by writing the customization code. This is for the ACL in the Portal so that the users are automatically added to group after self-registration. We have set the ACL in the Portal based on this group already existing. We want to achieve is by adding a row into Member table in DB2. We are not able to find any code or samples for this. Is there a right way or any other way to achieve this?
Answer: WebSphere Portal provides the PUMA API for managing users and groups. It is not really a publically supported API, so we provide documentation for it with the understanding that the interface may change over time. In fact, in WebSphere Portal V5, the interface is deprecated. We intend to replace it with a publically supported WebSphere Member Manager (WMM) interface in the near future, but the PUMA interface will remain until the WMM interface is available.
Using the PUMA interface, you can programmatically manipulate group ownership, and thus at the time of registration, assign the new user to a specific group. For more information on this interface, see the WebSphere Portal Support site. You will need a Passport Advantage user ID and password to access this document.
Question: I have WebSphere Portal V5 with Collaboration Center installed, Sametime server 3.0, and Quickplace server 3.0.1 behind the company's firewall. Now I want the Portal to be accessed from the Internet. What are the TCP ports that have to be opened in order for all the servers to work together?
Answer: QuickPlace uses the standard HTTP port for communication (80). Sametime uses a private port (1533).
Question: I had a problem starting WebSphere Portal server. The error is "Failed to load servlet." I installed WebSphere Application Server and WebSphere Portal a few days ago. It ran fine. I was able to start Portal and browse it. Now it gives this error, and I didn't do anything with it since the installation. (submitted by Yifei)
Answer:
I suggest inspecting the
SystemOut.log and
SystemErr.log files under the
.../PortalServer/log directory to see if you can find the errors. Hopefully, the error messages earlier in the log will yield the reason for the failure. If not, or if you can't figure out a way to correct it, then I would suggest contacting IBM Service.
Question: When will the ability to do multi-developer Portlet Remote debugging be available? We would like to share instances with many developers for remote debugging on higher powered systems (AIX). (submitted by Matt Langley)
Answer: Remote debugging is available within the Portal Toolkit. There is nothing to prevent each of your Portal Toolkit installations to use a common remote Portal Server for the debugging environment.
Question: We would like to design a portlet to call a separate Java servlet/JSP that will pop up in another browser window. How would you recommend doing this? Should it be in the same WebSphere_Portal server or "server1" on the application server? How can we pass the data, such as user info, from the portlet to the Java servlet? How can we maintain the servlet called under the portlet security framework?
Answer: The most common solution for this is to package a servlet with your portlet within the same WAR. We have several portlets that do this. In your portlet's JSP, you can have an HREF with a target="_blank" attribute to create a new window for the other servlet. The servlet is registered in the portlet's web.xml file and is assigned a context root to access the portlet.
Because the servlet and the portlet are in the same Web module (WAR), they can share session information.You can have your portlet put application-specific data in the portlet session that the servlet can then pull out. The trick is, though, that the data put into the session will be namespace-encoded by the portlet's WAR name, so you will need to figure out what that pattern is for that Web module and use it to pull attributes off the session (or simply look at all of the attributes in the session and use the right one).
I'm not sure exactly what you mean by the portlet's security framework. You cannot grant authorization to the servlet, only the portlet, through the portal. You must use the portal to access the portlet, so if the portlet is unavailable, then the associated servlet is unavailable. If the portlet is required to set certain context information in the session for the servlet, then directly addressing the servlet (around the portal) can cause an error because that context information is missing.
Question: Currently WebSphere Portal V5 Express requires additional setup for a database and LDAP server. Do you recommend implementing on the Cloudscape database first, and then migrating to a database such as DB2 when required, or going straight to DB2? Will any data be lost from the migration from Cloudscape to DB2 such as from the Portal Document database?
Answer: The database transfer is designed to preserve all data from Cloudscape to whatever your target database happens to be. That being said, though, the complexity and chance for error increases with the complexity of the data being transferred. If you know you are planning to move to another database, I would plan to do that sooner than later.
Question: I have installed WebSphere Application Serverwith IBM HTTP Server 1.3.19.4 with ssl configured. What is required to upgrade to IBM HTTP Server 1.3.19.6 without disturbing the current installation. How I will do that?
Answer:
This is a WebSphere Application Server question, not so much a Portal question, but you should be able to upgrade safely. Backup your
httpd.conf file as it contains (in the last few lines) the configuration entries that register the WebSphere Application Server plugin to the Web server. If, after the upgrade, these lines are gone, you can simply add them back from the backup.
Related information
- Guide to WebSphere Portal 5.0
- Applying the State Pattern to WebSphere Portal V5 Portlets: Part 1. Overview
- Comparing the JSR 168 Java Portlet Specification with the IBM Portlet API
- Using Cooperative Portlets in WebSphere Portal V5
- Extending the State Pattern for Multi-Portlet Applications. | http://www.ibm.com/developerworks/websphere/library/techarticles/0401_lamb/lamb.html | CC-MAIN-2014-41 | refinedweb | 2,264 | 56.76 |
Understanding Servlets
Most of the work that you will do with Tomcat will involve four of the directories located under the root Tomcat directory. These directories are
C:\Program Files\Apache Tomcat 4.0\binThis directory contains scripts to perform functions such as startup, shutdown, and so on. Under Windows, these scripts are .bat files, and under Unix, they are .sh files.
C:\Program Files\Apache Tomcat 4.0\confThis directory contains configuration files, which control the behavior of the server. Most of these files are in XML format. The most important file in here is called server.xml, the main configuration file for the server.
C:\Program Files\Apache Tomcat 4.0\logsThis directory contains the logs that are created by the Tomcat server. You inspect these logs to discover clues about why certain problems are occurring with the installation and/or your programs.
C:\Program Files\Apache Tomcat 4.0\webappsThis directory is where you put your programs. Web servers don't like to access files all over your computer because of the security risks. They prefer to allow clients to access only files that are stored in one place and its subdirectories.
Testing the Installation
After you have finished the installation, you will want to test the server using servlets provided by Apache before writing your own. The reason for this is that any problem you have running their servlets is certainly a configuration problem. If you run your own servlets without first verifying that the installation is correct, the problem could be either in the installation or with your servlet.
Testing the installation is easy. First, start Tomcat by following the procedure described previously. Next, type the following command in a browser address box:
You should immediately see a screen that looks like Figure 21.3.
Figure 21.3The Tomcat localhost home page will display when the server is running properly.
If you do not see this page immediately, the most likely reason is that you have another program listening to port 8080. In that case, edit the file called server.xml in the C:\Program Files\Apache Tomcat 4.0\conf directory. Look for the following lines:
<!--"/>
Edit the fourth line and change it to some value more than 1024, like 1776. It will look like this:
<!-- Define a non-SSL HTTP/1.1 Connector on port 8080 --> <Connector className= "org.apache.catalina.connector.http.HttpConnector" port="1776" minProcessors="5" maxProcessors="75" enableLookups="true" redirectPort="8443" acceptCount="10" debug="0" connectionTimeout="60000"/>
Save this file and restart the Tomcat server. Repeat the test by opening a browser, but this time type
If this doesn't open the magic Web page shown in Figure 21.3, consult the troubleshooting documentation that Tomcat installed on your hard drive.
Note - This chapter uses port 1776 for all the examples. The reason for this is that port 8080, the default Tomcat port, was already in use on our test machine.
Programming Servlets
Servlet programming is built on a solid foundation of prewritten Java classes. Instead of creating servlets as Java classes that are started by calling a main method, servlets are extensions of other classes that already know how to interact with Web servers and servlet containers.
The following classes and interfaces are the most important ones to understand when programming servlets:
ServletThis interface defines the init(), service(), and destroy() methods. It also defines two more methods that implementing classes must provide, getServletConfig() and getServletInfo(), which allow you to query the servlet for information about the servlet itself (author, version, copyright, and so on). The servlet container is programmed to expect a servlet to implement these five methods. This is how code that you write can be plugged into a framework such as the servlet container so easily. Advanced programmers might want to implement this interface directly in a new class instead of using either the GenericServlet class or HttpServlet class. This would require you to write quite a bit of code, however, and it is not needed to satisfy ordinary requirements.
GenericServletThe GenericServlet class provides a simple implementation of the Servlet interface. It is called "Generic" because it does not assume that the protocol it will process will be HTTP. If you were writing your own protocol, you would extend this class. Normally, you override the service() method.
HttpServletThis is the class that is most often extended when servlets are written. It extends GenericServlet to provide HTTP-specific processing. Because HTTP is so common, servlets that extend this class tend to be the easiest to write. Normally, you override the doGet(), doPost(), or both methods of this class. This class contains a default implementation of service() that calls the appropriate doXXX() method, depending on the type of request that is received.
ServletRequestThis interface defines an object that contains the information that the client has provided, along with his request to run the servlet. A concrete implementation of this object is ServletRequestWrapper class.
HttpServletRequestWrapperThis is an extension of the ServletRequestWrapper that contains information specifically assuming that the request will be in HTTP format. In most servlets, this class is accessed polymorphically via a handle to the ServletRequest interface. See Chapter 7, "Inheritance," for information on how this works.
ServletResponseThis interface defines a convenient way for a servlet to communicate the information that it wants to send to the client to the servlet container. A concrete implementation of this object is ServletResponseWrapper class.
HttpServletResponseWrapperThis is an extension of the ServletResponseWrapper that assumes that the response will be in HTTP format. In most servlets, this class is accessed polymorphically via a handle to the ServletResponse interface.
Programming Generic Servlets
Even though most of this chapter will deal with HTTP-based servlets, it is useful to understand how a servlet can be created that is not tied to this protocol. Listing 21.1 shows a simple generic servlet.
Listing 21.1 The GenericHello Class
/* * GenericHello.java * * Created on June 21, 2002, 5:28 PM */ import javax.servlet.*; import java.io.*; /** * * @author Stephen Potts * @version */ public class GenericHello extends GenericServlet { /** Initializes the servlet. */ public void init(ServletConfig config) throws ServletException { super.init(config); } /** Destroys the servlet. */ public void destroy() { } public void service(ServletRequest req, ServletResponse resp) throws ServletException, java.io.IOException { resp.setContentType("text/html"); java.io.PrintWriter out = resp.getWriter(); out.println("Hello from the GenericHello Servlet"); out.close(); } /** Returns a short description of the servlet. */ public String getServletInfo() { return "This servlet tests the GenericServlet class"; } }
Notice that this class extends the GenericServlet class. As discussed previously, this is a protocol-neutral servlet class.
public class GenericHello extends GenericServlet
The init() method is overridden here. Notice that it is passed a ServletConfig class, which it passes along to the super(GenericServlet) class's init() method. The ServletConfig class contains references to the servlet name and the ServletContext object. For now, we can ignore these objects.
public void init(ServletConfig config) throws ServletException { super.init(config); }
We override the destroy() method just for show.
public void destroy() { }
We also override the getServletInfo() method so that you will have an example of how this is done.
public String getServletInfo() { return "This servlet tests the GenericServlet class"; }
Finally, the service() routine is where the action is, what little there is in this example.
public void service(ServletRequest req, ServletResponse resp) throws ServletException, java.io.IOException { java.io.PrintWriter out = resp.getWriter(); out.println("Hello from the GenericHello Servlet"); out.close(); }
We create a handle to the response object's PrintWriter object so that we can send some information to the client. We are not interested in any of the information available from the client in this simple example. We print a string to this object, and then close it. The servlet container is responsible for actually getting the string to the client.
Page 2 of 9
| http://www.developer.com/java/ent/article.php/10933_2178651_2/Understanding-Servlets.htm | CC-MAIN-2015-22 | refinedweb | 1,301 | 58.08 |
Post your Comment
source code program - Java Beginners
source code program I need the source code for a program that converts temperatures from celsius to fahrenheit and vice versa, as well as converting kilometers to miles and vice versa using Java "classes". Hi
source code - Swing AWT
source code source code for a program to shutdown, restart, log off the pc after clicking jbutton on jpanel or a jframe by user.
thanks in advance
source code - Java Beginners
source code Hi...i`m new in java..please help me to
write program that stores the following numbers in an array named price:
9.92, 6.32, 12,63, 5.95, 10.29. program should also create two arrays named units and amounts
provide source - Java Beginners
provide source please provide code for this program
Write a program to download a website from a given URL. It must download all the pages from... the files/pages must be stored in a folder. Hi
This is the source code
Open Source Software
Open Source Software
Open Source Software
Open source doesn't just mean access to the source code. The program must include source code, and must allow distribution Accounting
;
Open Source Accounting and Inventory Program Launched
A web based, open source accounting and inventory program called NOLA has been...Open Source Accounting
Turbocase open source Accounting software
Open Source HTML
Open Source HTML
HTML Tidy Library Project
A quorum...;
Open Source HTML Parsers in Java
NekoHTML is a simple HTML... element tags.
Open Source Search Engines
Open Source Web Page
Certified Open Source Software certification mark and program. You can read about...Open Source Web Page
The
Open Source Page
Open Source Initiative... is "Open Source." We also make copies of approved open source licenses here
Open Source Jobs
;
All About Open Source
Open source usually refers to a program in which...Open Source Jobs
Open Source Professionals
Search firm specializing in the placement of Linux / Open Source professionals, providing both
Open Source DRM
available) program under the open-source Common Development and Distribution...Open Source DRM
SideSpace releases open source DRM solution
SideSpace Solutions released Media-S, an open-source DRM solution. Media-S is format
Open Source Directory
Open Source Directory
Open Source Java Directory
The Open Source Java...;
Open Source Directory Services
Apple's Open Directory... with open source directory
Red Hat Directory Server began life as the Netscape
java source code - Java Beginners
java source code write a program to read the value of n as total number of friend relatives to whom the person wants to call
Compiling a Java program
Java NotesCompiling a Java program
Turning a Java source program...:
Create the source program with a text editor (eg, jEdit, TextPad... used short directory names without spaces.
Compile the source program
Open Source Version Control
Open Source Version Control
CVS:
Open source version control
CVS... your program under a source code version control management software from the very...; program
Open Source program
Applications for Open Sound System
SLab Direct... or display functions loaded at run time.
Open source sound project
The l.o.s.s project promotes and supports the use of free, open source CD
Open Source CD
TheOpenCD
TheOpenCD is a collection of high quality Free and Open Source Software. The programs run in Windows and cover the most... CD is a collection of over 100 Free/Open Source software for home and business
Best Open Source Software
Best Open Source Software
Best Open Source
Open source software. Often (and sometimes incorrectly) called freeware, shareware, and "source code," open... the term
open source, and even fewer are aware that this alternative software
Open Source Application Server
Open Source Application Server
New Open-Source Application Server
A new open source application server is available for download from WSO2 Inc., a little known but highly regarded Sri Lankan firm of open source developers
Open Source Download
Open Source Download
Downloads - UNIX & Open Source
A modification of the free/open source GNU Image Manipulation Program (GIMP), intended..., etc. remain available.
The official AWeb Open Source
Path of source code
Description:
This example demonstrate how to get the path of your java program file. The
URI represents the abstract pathname and URL construct from
URI.
Code:
import java.io.
Open Source Movement
Open Source Movement
Open source movement Wikipedia
The open source movement is an offshoot of the free software movement that advocates open source software as an alternative label for free software, primarily
Post your Comment | http://www.roseindia.net/discussion/19342-Open-Source-program.html | CC-MAIN-2013-20 | refinedweb | 750 | 61.56 |
I'm confused about how
subprocess
Popen()
sys.path
subprocess.Popen
sitecustomize.py
os.environ
# copy PYTHONPATH environment variable into PATH to allow our stuff to use
# relative paths for subprocess spawning
import os
if os.getenv('PYTHONPATH') is not None and os.getenv('PATH') is not none:
os.environ['PATH'] = ':'.join([os.getenv('PATH'), os.getenv('PYTHONPATH')])
os.environ
subrocess.Popen
env
env
os.getenv
env={'PATH': '/explicit/path/to/search/from'}
# some_script.py
from subprocess import Popen, PIPE
spam, eggs = Popen(['../subdir1/some_executable'], stdout=PIPE, stderr=PIPE).communicate()
/dir/subdir2
python some_script.py
/dir
python subdir2/some_script.py
/dir/subdir2
os.environ['PATH']
OSError: [Errno 2] No such file or directory
(filling in details from a comment to make a separate answer)
First off, relative paths (paths containing slashes) never get checked in any PATH, no matter what you do. They are relative to the current working directory only. If you need to resolve relative paths, you will have to search the PATH manually, or munge the PATH to include the subdirectories and then just use the command name as in my suggestion below.
If you want to run a program relative to the location of the Python script, use
__file__ and go from there to find the absolute path of the program, and then use the absolute path in
Popen.
Secondly, there is an issue in the Python bug tracker about how Python deals with bare commands (no slashes). Basically, on Unix/Mac
Popen uses
os.execvp when invoked with
shell=False, which means it looks at the value of
PATH as it was when Python launched and no amount of changing
os.environ will help you fix that. Also, on Windows with
shell=False, it pays no attention to PATH at all, and will only look in relative to the current working directory.
If you JUST need path evaluation and don't really want to run your command line through a shell, and are on UNIX, I advise using
env instead of
shell=True, as in
Popen(['/usr/bin/env', 'progtorun', other, args], ...). This lets you pass a different PATH to the
env process, which will use it to find the program. It also avoids issues with shell metacharacters and potential security issues with passing arguments through the shell. Obviously, on Windows (pretty much the only platform without a
/usr/bin/env) you will need to do something different. | https://codedump.io/share/VV2mkWawVHf8/1/python-subprocess-popen-environment-path | CC-MAIN-2017-04 | refinedweb | 403 | 56.45 |
The JDOM-document builders allows to crate new JDOM document directly from its DOM
analog. The algorithm is the same as when loading document from XML-file, except
DOM-object is on input instead of XML file.
You just create DOMBuilder instance and used its build method with DOM passed there
to create new JDOM document. This is shown below:
import org.jdom.Document;
import org.jdom.input.DOMBuilder;
/**
* This sample program showing how it is easy to convert
* from DOM to JDOM document.
*/
public class Test {
public static void main(String[] args) {
try {
// we have a DOM-document as input:
org.w3c.dom.Document dom = getDOM(...);
// just convert:
DOMBuilder builder = new DOMBuilder();
Document document = builder.build(dom);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks. | http://www.java-tips.org/other-api-tips/jdom/converting-from-dom-to-jdom.html | CC-MAIN-2015-22 | refinedweb | 145 | 60.51 |
.
Okay...I am confused. I don't know whether it is a good question or not. A boolean variable reserves 1 byte in memory but can only hold two possible values, true(1) or false(0). A single binary digit can also hold two values 1 or 0. My question is why a boolean variables takes 8 bit to represent.
It's a good question.
Booleans really only need one bit to represent a true or false state, however as you note, bool variables use a whole byte. Why? Because the smallest unit of memory that a computer architecture can get or set is 1 byte. If booleans were only 1 bit, all of the booleans within the same byte would have the same memory address, and there's be no way to differentiate them!
There are ways to pack 8 booleans into a single byte. I cover these some of these techniques in future lessons.
Those techniques you mention are the use of bitmasks right?
Bit flags (which are related to bit masks, but slightly simpler).
I will get to that topic soon :)
Thanks. (and sorry in advance for my awful english)
Hi, I recently attempted the quiz of this section and wanted to avoid writing 4 else if statements. I'm not sure where I went wrong:
C++ doesn't parse this expression in the way you're intending.
You could use the logical OR operator to do something similar, like this:
Oh, thank you very much.
Hi, I have just completed the quiz, and the program works but it differs from the solution you provided. I'm just wondering if there is something I should do differently:
Nope, this is great. It's a better solution than mine because you use logical OR (which we haven't covered yet).
Hey Alex.
Is this code correct or the quiz solution is the better way to get around it?
You're on the right track, but your program doesn't produce the correct results.
Hmmmm,
I am kind of new in to programming so please excuse me any strange sound questions.
So the program as far I understand is taking the value from the user and if it's not 1,4,6 then true value is returned to the function caller which executed the first statement???
Thanks for any inside on this.
I am really enjoying this tutorial so Thanks again.
Yes, but:
1) You don't handle 8 or 9 properly.
2) It's odd to define the not-prime numbers instead of the prime numbers.
I came up with a different solution to the one you listed:
Aside from having less to type is there a reason your solution is better than this?
Your solution works but has a lot of redundancy. If you ever wanted to update the string "The digit is prime" you'd have to update it in 4 different places.
For a simple program like this that's not that big of a deal, but as programs get more complex, the more you can reduce redundancy the better.
Hello Alex,
First of all, thanks for designing such a great tutorial! It makes learning a lot of fun since the approach is very systematic; not to mention the fact that it uses language that new programmers are comfortable with.
I have a doubt regarding the following program (one of the examples in this lesson)-
Why is it 'if (equal)' ?
Why not 'if (equal == 1)' or 'if (equal == true)' ?
I checked all three variations and they all work perfectly, so what's the difference?
Besides, couldn't we just write the program as-
It makes it shorter, and perhaps there's a lower chance of errors.
Please enlighten me! :P
Thanks!
As you note, we use "if (equal)" because it evaluates identically to "if (equal == true)". You can see why this is true by making a table:
Therefore the "== true" part is redundant.
Hi,
I'm using Visual studio 2010.I believe my code is similar to the solution above(in the quiz)However,my program seems to recognize all inputs from user as being prime including numbers that are not prime. How do I solve this?
Reply to this message and post your code so we can see what's wrong.
line 12:
should be
You want Prime to default to being false because you are only making it true if it matches one of the conditional statements(if (x == 2) for example). If it doesn't match one of those statements then those statements get ignored and Prime stays false so when the program gets to
then it will skip to the else statement(telling the user their number is not prime) because its not true.
Suggestion for this part, another common prefix for bool functions is has. And since you do a lot to ensure good coding style (love that you do that btw.) I would add that it's not only common but in most cases considered good style, since it for most boolean purposes makes the purpose of the function clearer.
Good call. I updated the lesson to note this.
in the above solution, couldn't you have put the
if (prime)
cout << "The digit is prime" << endl;
else
cout << "The digit is not prime" << endl;
part inside the other if statements like you would do in most other languages?
for example:
if (x == 2)
prime = true;
std<<cout::"the digit is true";
else if (x == 3)
prime = true;
std<<cout::"the digit is true";
else if (x == 5)
prime = true;
std<<cout::"the digit is true";
else if (x == 7)
prime = true;
std<<cout::"the digit is true";
I've also noticed that c++ does not automatically edit the indentation in the statements like compilers in most other languages would.
Thanks for the reply, and for building this amazing website
You could, but I wouldn't recommend doing it this way. Why? Because if you want to change what is printed, you have to change 4 statements instead of one. Although it's not that bad to do with 4 statements, imagine if there were 100, or 1000.
One of the goals when programming should be to reduce redundancy, and your code adds redundancy.
I'm not sure if I understand the significance between = and ==. I get that = is assigning a value while == is comparing, but it seems like replacing the == with = in the sample code should either give a syntax error or the correct result. When I try this, it compiles correctly, but entering an 8 gives me the result "This digit is prime." I would appreciate it if someone could help me to understand why this is so.
It sounds like you're doing something like this:
So first, this will assign the value 2 to x, which probably isn't what you want.
But the real question here is what does x = 2 evaluate to? The answer, it turns out, is x.
So after x = 2 evaluates, you're left with:
which will be true if x is anything other than 0. So the ... part of the code is executing when you aren't expecting it to, and this is setting the value of isPrime to true.
seems like some people have a doubt about operators represented by using common symbols.
maybe if you extend "1.5 — A first look at operators" with that = and == (for example) should be interpreted as "assign" and "compare" NOT as "equals" and "equals equals".
also that == or <= should be interpreted as a single symbol, not 2 keys pressed one after the other, but as if it is 1 key pressed.
make a remark that due the lack of symbols available in the keyboards, the language uses a combination of what is available to represent... stuff.
some educators like to present programmers as being lazy(which might be true for the majority of them) hence the reason to write "==" instead of "compare".
you get the idea. use better words :)
I think I took the quiz too seriously =P
PS. No, I didn't read the hint, it's cheating =D
Hi I have an assignment at school similar to this but I'm having a hard time with it. Hopefully someone can help! So the input can be from 2-100 and then determine whether it is prime or not. Then if it is not prime, I need to be able to print whether it is divisible by 2, 3, 5, or 7. How do I do that?
I just wanted to share my quiz answer for any future readers.
Thank you for this! I was trying to figure out how to use bool prime(false) or bool prime(int x) as a forward declaration and could not figure out what I was doing wrong. Now my compiler errors make sense.
One additional note: when converting integers to booleans, the integer zero resolves to boolean false, whereas non-zero integers all resolve to true.
At this point, you should just specify that any numerical value that is not 0 or 0.0 w.r.t its data type will be true.
Can any one help check my code? There's some semantic error, but I can't figure out why.
#include <iostream>
using namespace std;
bool isPrime(int)
{
int x;
if (x==2)
return true;
else if (x==3)
return true;
else if (x==5)
return true;
else if (x==7)
return true;
else
return false;
}
int main()
{
cout << "Please enter a 1-digit number." << endl;
int myNumber;
cin >> myNumber;
if (isPrime(myNumber))
cout << "The digit is prime" << endl;
else
cout << "The digit is not prime" << endl;
return 0;
}
Change:
to:
As you wrote it, you didn't give your function parameter a name, so the value being passed in (myNumber) is being discarded. You defined variable x inside the function, but you never initialized it with a value, so it's essentially useless.
Hi!
So I'm getting the coding right when trying some things, I'm just struggling to understand something. Line 27 of your example to be exact.
On line 26 we declare the variable beEqual. Then we have a function call to IsEqual in order to initialize beEqual. Am I right in assuming that IsEqual will return to the caller function a 1 if both values are equal, and a 0 if they are not equal?
Now line 27. We say: if (beEqual)... what exactly does this mean? Because I'm sure beEqual=beEqual, so why dont we always print "x is equal to y" ?
Or should I read it as: if (1) and if (0)?
I hope I'm making sense here!
isEqual() will return true (1) if the values are equal, and 0 otherwise.
"if (beEqual) ..." is the same as writing "if (beEqual==true) ...". So in this case, we're testing beEqual to see if it's true, and which statement is executed depends on whether that equality test is true or false. I'll make this more clear in the lesson text.
I want to ask why following code works?
#include
int main()
{
using namespace std;
int x;
cout << "Please feed in the first number" <> x;
int y;
cout << "Please feed in the second number" <> y;
bool z;
if (x==y)
z = true;
else
z = false;
if (z)
cout << "Both digits are equal" << endl;
else
cout << "Both digits are different" << endl;
return 0;
}
When the user feeds in two different numbers then the statement which says
if (z)
must hold 0 as z and in return should type "Both digits are equal" because this cout statement follows if (z) statement.
is equivalent to:
which means
hey nice explanation alex very helpfull...........
wouldnt it be the same to put instead of x==y, this: x=y????
i tried and got the same result so.....what is the difference and when do I use each operator????
Thanks..
= - assignment operator, used to assign a specific value to whatever you want to assign to.
== - comparing operator, using to compare 2 things.
Yay, I think I completely understand how bool works now.
Thanks Alex, this is so much better than even some of those books on cpp.
P.S. Here's my little test that succeeded btw.
Hi there, I was just wondering if you just wanted to find if the numbers are equal why have you included the code from line 20 to line 32.
Hi, i tried to make this program work with three numbers:
i.e.
return (x == y == z)
the program compiled fine and ran, but did only gave the result for "else" (false)
after i took away "int z" it worked just fine...
does bool only work for two variables?
The reason is when you say a == b == c, first it checks a and b and if those two numbers are equal, you are trying to check if c is equal to 1(true). Try this:
bool IsEqual(int a, int b, int c)
{
if(a == b)
{
if(b == c)
return true;
}
else
return false;
}
Hi Alex (Admin)!
Great site.
Just wanted to say that I find your site extremely educational, and for me, easy to follow. Good work!
P.S.
I get just as much fun/learning reading the comments at the end of the tutorial as I do from the lessons. I can't finish a section without reading the comments!
Brilliant!!!
Could someone please give me a definitive answer about the difference between explicit and implicit assignments.
Thanks
I've never seen that type of assignment used for a built-in, although I do not doubt that it works. I believe that "int i = 1;" uses int's default constructor THEN uses int's assignment operator. Whereas "int j(1);" uses a version of int's constructor which accepts an integer. In theory the second should be more efficient although compilers are most likely smart enough to optimise away the extra step.
I don't get how it can run the function bool IsEqual(int x, int y), if there is no function call in the program later. I would figure you would need,
bool Isequal(x,y); <----in main function to call the IsEqual function?
for the program to read
bool IsEqual(int x, int y)
07.{
08. return (x == y); // use equality operator to test if equal
09.}
so how does it work without a function call being made?
the if statement calls the function to check if (x==y)
Great Tutorials, well written and structured. many thanks.
coming from a background in Oracle and using mainly PL/SQL i have gotten used to the idea that booleans are tristate (true, false or null/unknown) and so an if statement against an uninitialsed boolean var would always return null (and thereby only be handled by "else") without any warnings - dangerous.
It might be worth noting for people like me that uninitialised boolean variables, aside from raising a warning at compile and a "break" at runtime (in VC2008 at least), will almost always return true (i assume this because the uninitialised memory address will almost always contain a non-zero value as below).
Please i need some help...
Can please anyone review this code? It is supossed to accept the input of 2 numbers, the asks for the answer if they are equal and not equal and says if the answer is either right or not:
Thanks!
It seems you wrote IsFalse instead of IsEqual.
Hey!
In which cases do we use the implicit assignment?
You can use it in any case where you're creating a variable and initializing it with a value. It's neither better nor worse than explicit assignment as far as I know.
Hey Alex,
Nice tutorial section! Some comments that might improve readability of this section:
1. Mention that the test x==y will output a 0 if false and a 1 if true and discuss the use of this equality as a logic 'test'. It took me a few moments to appreciate that for myself.
2. Logic commands have not been discussed in the tutorial yet (if, not etc) so someone new to programming might find this confusing.
You could also mention that if(1) runs the first command in an if statement and if(0) runs the 'else' statement. Interestingly if(5), if(11) and all if(!=0) has the same effect as if(1). i.e all non-zero values are true in the context of the if statement.
:)
Thanks for your thoughts. I added a comment about conversion of integers to booleans because that's not very intuitive to new programmers. Your other comments are valid, but are discussed in future chapters when I tackle those specific topics.
Please correct me if I am wrong:
If the Value of TRUE is 1 (00000001), Doesn't (!TRUE) make the value to be equal to (111111110) internally? If that is the case then evaluating:
if (!TRUE) will always be TRUE.
Hi,
Actually what u r doing is not correct. u r performing bit wise not that is ~ operator in c.
now u r using operator ! which actually ORs all the bits of the value and then compliments it i.e.
if TRUE is 1(00000001) then ORing will give its value 1(binary not 00000001) this is only a bit so now it will compliment it to 0 and then return the resulting false(000000000).
For futher query you can ask me..on new_programers@yahoo.com
Thnks,
Correct. ! is a logical not, whereas ~ is a bitwise not.
Yup, I had trouble with this one quite a while ago, one thing you'd have to remember is that bool is based on being simply on or off, where if something exists, it's on, and if it doesn't it's off. 1 or 0.
Boolean values are more ideally used if preexisting values exist much like radio buttons, in HTML for example...
<form>
Is your car new or not?<br>
<input name="newCar" type="radio" value="1" /> Yes<br>
<input name="newCar" type="radio" value="0" /> No<br>
</form>
I have problem actually I don't know how to use the boolean with ( cin ) ..
like this example:
if i want to ask some one about his car ?
===========
bool car;
=====
is the above good solution or not ??
...
i'm witing for your answer
thank you so much
When trying to cin boolean values, if the user enters the number 0, this will be treated as the value false. If the user enters anything else, it will be treated as the value true.
There are several ways to proceed:
* Tell the user to enter 0 for no and 1 for yes and then cin a bool.
* Tell the user to enter 'y' or 'n' and then cin a character.
Once you get to the lesson on strings, you could also do this:
* Tell the user to enter "yes" or "no" and then cin a string.
Hi Alex,
I was trying to make the same type of program. Basically a yes or no question. I'm able to cin a bool easily by having the person enter a 1 for yes, 0 for no. However I'm trying to have them input 'y' and 'n'. You said earlier:
"* Tell the user to enter ‘y’ or ‘n’ and then cin a character. "
I'm confused on how this program is supposed to look.
I've tried many ways, and none work. This is the last part I've tried to make to get the correct answer. Can you bool a char? Could you tell me what I'm doing wrong?
Its ugly but I'm trying haha. I've tried using bool equal(n) and other styles but none work.
These portions of your code are wrong (First of all, if the user is sleeping, he/she isn't going to enter 'y' :) :
You can't define a name twice in the same scope. Giving them different data types won't help. Consequently, defining char ch and bool ch inside same function is not valid. remove the line
from your code. In the same line, you are also assigning a char to a bool. Programmers never do that.
here you are assigning a boolean true to a char. Boolean true evaluates to integer 1 and chars in C++ are treated as integers. If you assign an integer to a char, then the given integer will be treated as an ASCII code and program will print the equivalent character by looking at ASCII table. Integer 1 is equivalent to somewhat called "start of heading" in ASCII table, and is considered unprintable. So, the syntax may be valid, but has no meaning at all. Remove this too.
, Due to the previous changes in your code, this won't work. In fact, you don't even need to define a char n variable. Secondly, this will not do what's supposed. Pretend, because chars are treated as integers, and boolean true or false means integer 1 or 0 respectively, this line of code is a valid if expression. But what would be evaluated? I am not sure but I think true always.
I think you need to go back and read about chars, if-else, data types, ASCII table etc. Your code is a superb mess. After reading those articles again, you may fix all of the errors (all errors are not mentioned) yourself.
Hi Devashish,
Yeah, if the user is actually sleeping they can't press 'y', but thats kind of the bad joke :).
Oh I see, so theres no way to bool a char.
You could do this:
Alternatively, you could avoid using a boolean variable altogether:
Thanks so much, that makes a lot of sense. I was wondering if I didn't even need to use the bool, just not sure what I could use since I've only gotten up to the chapter for chars so far.
HEY ALEX!
IT IS RIGHT TO ADD THIS OPERATOR ">>"
TO COUT.....
HERE WHY AM ASKING THIS
YOU ADDED ">>" IN COUT IN ABOVE
ANSWER THAT YOU HAD REPLIED..
'"
'"
AND ONE MORE QUESTION
IS IT POSSIBLE TO CREATE OR DESIGN
SOMETHING LIKE FACEBOOK AND WHATSAPP ...
AND ALSO IN MY CODEBLOCKS 16.01 WHEN I COMPILE YOUR ABOVE ANSWER WITHOUT INT MAIN THERE A
ERRORS COME SAYING "cout does not name a type" "expected unqualified id before if and else".
No, that was a typo on my part. I've changed "cout" to "cin" as intended.
> IS IT POSSIBLE TO CREATE OR DESIGN SOMETHING LIKE FACEBOOK AND WHATSAPP …
Given that these things exist, I'd say yes, it's possible. But if I were going to develop the next Facebook, I'd probably use something other than C++.
My code above is a snippet, not a full program. You'll need to #include iostream if you want to compile it, so the compiler knows what cout and cin are.
I'm confused as to why you make the IsEqual function a bool, wouldn't making it an int function work just as well? Or is it declared as a bool function so you have an idea of what the return values will be and what the function does? Sorry if I sound like a newbie :p
IsEqual function isn't a bool, it returns a bool. Boolean values are used to represent values that can only be true or false. When we're talking about whether a value is equal, either it is (true), or it isn't (false). Consequently, it makes more sense to return a bool than an int. While technically returning an int would work (returning the value 1 if the parameters are equal, and 0 otherwise), returning a bool is more intuitive and leaves less room for errors to be made.
Name (required)
Website
Save my name, email, and website in this browser for the next time I comment. | https://www.learncpp.com/cpp-tutorial/boolean-values/comment-page-1/ | CC-MAIN-2021-04 | refinedweb | 4,003 | 72.05 |
We've provided a set of starter files with skeleton code for the exercises in the lab. You can get them in the following places:
Previously, we had dealt with tuples, which are immutable sequences. Python has built-in lists, which are mutable. This means you can modify lists without creating entirely new ones. Lists have state, unlike tuples.
Just like with tuples, you can use slicing notation with lists. In addition, not only can retrieve a slice from a list, you can also assign to a slice of a list. This is possible because lists are mutable.
What does Python print? Think about these before typing it into an interpreter!
>>> lst = [1, 2, 3, 4, 5, 6] >>> lst[4] = 1 >>> lst _________ >>> lst[2:4] = [9, 8] >>> lst _________ >>> lst[3] = ['hi', 'bye'] >>> lst _________ >>> lst[3:] = ['jom', 'magrotker'] >>> lst _________ >>> lst[1:3] = [2, 3, 4, 5, 6, 7, 8] >>> lst _________ >>> lst == lst[:] _________ >>> lst is lst[:] _________ >>> a = lst[:] >>> a[0] = 'oogly' >>> lst _________ >>> lst = [1, 2, 3, 4] >>> b = ['foo', 'bar'] >>> lst[0] = b >>> lst _________ >>> b[1] = 'ply' >>> lst _________ >>> b = ['farply', 'garply'] >>> lst _________ >>> lst[0] = lst >>> lst _________ >>> lst[0][0][0][0][0] _________
Python has a
list class that contains many useful methods. Using the
builtin
dir() function will show you all of them, like so:
dir(list)
Some of the most common methods include
append(),
extend(), and
pop().
>>> l = [3, 5, 6] >>> l.append(10) # adds an element to the end >>> l [3, 5, 6, 10] >>> l.extend([-1, -6]) # concatenates another list to the end >>> l [3, 5, 6, 10, -1, -6] >>> l.pop() # removes and returns the last element -6 >>> l [3, 5, 6, 10, -1] >>> l.pop(2) # removes and returns the element at the index given 6 >>> l [3, 5, 10, -1]
Try to solve the following list problems with mutation. This means that each function should mutate the original list. In other words:
>>> original_list = [5, -1, 29, 0] >>> function(original_list) # doesn't return anything >>> original_list # mutated list here
Prioritize solving these problems with iteration, but for extra practice, also solve them using recursion. Remember: these functions should NOT return anything. This is to emphasize that these functions should utilize mutability.
Write a function that reverses the given list.
def reverse(lst): """Reverses lst using mutation. >>> original_list = [5, -1, 29, 0] >>> reverse(original_list) >>> original_list [0, 29, -1, 5] """
Write a function that maps a function on the given list.
def map(fn, lst): """Maps fn onto lst using mutation. >>> original_list = [5, -1, 2, 0] >>> map(lambda x: x * x, original_list) >>> original_list [25, 1, 4, 0] """
Write a function that filters a list, only keeping elements that satisfy the predicate.
def filter(pred, lst): """Filters lst with pred using mutation. >>> original_list = [5, -1, 2, 0] >>> filter(lambda x: x % 2 == 0, original_list) >>> original_list [2, 0] """.
>>> [i**2 for i in (1, 2, 3, 4) if i%2 == 0] [4, 16]
is equivalent to
>>> lst = [] >>> for i in (1, 2, 3, 4): ... if i % 2 == 0: ... lst.append(i**2) >>> lst [4, 16]
List comprehensions allow you to apply map and filter at the same time, in very compact syntax. The general syntax for a list comprehension is
[<expression> for <element> in <sequence> if <conditional>]
The syntax is designed to read like English: "Compute the expression for each element in the sequence if the conditional is true."
Implement a function
coords, which takes a funciton, a sequence, and
an upper and lower bound on output of the function.
coords then
returns a list of x, y coordinate pairs (tuples) such that:
See the doctest if you are still confused.
One other thing: your answer can only be one line long. You should make use of list comprehensions!
def coords(fn, seq, lower, upper): """ >>> seq = (-4, -2, 0, 1, 3) >>> fn = lambda x: x**2 >>> coords(fn, seq, 1, 9) [(-2, 4), (1, 1), (3, 9)] """ return _______________
To practice, write a function that adds two matrices together using generator expression(s). The function should take in two 2D lists of the same dimensions.
def add_matrices(x, y): """ >>> add_matrices([[1, 3], [2, 0]], [[-3, 0], [1, 2]]) [[-2, 3], [3, 2]] """ return ________________
Now write a list comprehension that will create a deck of cards. Each element in the list will be a card, which is represented by a tuple containing the suit as a string and the value as an int.
def deck(): return ________________.
def sort_deck(deck): "*** YOUR CODE HERE ***"): """Return a dictionary: keys are words; values are lists of successors. >>> text = ['We', 'came', 'to', 'investigate', ',', 'catch', 'bad', 'guys', 'and', 'to', 'eat', 'pie', '.'] >>> table = build_successors_table(text) >>> table {'and': ['to'], 'We': ['came'], 'bad': ['guys'], 'pie': ['.'], ',': ['catch'], '.': ['We'], 'to': ['investigate', 'eat'], 'investigate': [','], 'catch': ['bad'], 'guys': ['and'], 'eat': ['pie'], 'came': ['to']} """ table = {} prev = '.' for word in tokens: if prev in table: "***YOUR CODE HERE ***" else: "***YOUR CODE HERE ***" prev = word return table.
Hint:): """Prints a random sentence starting with word, sampling from table. """ import random result = '' while word not in ['.', '!', '?']: "***YOUR CODE HERE ***" .' | https://inst.eecs.berkeley.edu/~cs61a/sp14/lab/lab04/lab04.php | CC-MAIN-2020-10 | refinedweb | 844 | 71.85 |
proxy
Angel middleware to forward requests to another server (i.e.
webdev serve).
Also supports WebSockets.
import 'package:angel_proxy/angel_proxy.dart'; import 'package:http/http.dart' as http; main() async { // Forward requests instead of serving statically. // You can also pass a URI, instead of a string. var proxy1 = Proxy(''); // handle all methods (GET, POST, ...) app.fallback(proxy.handleRequest); }
You can also restrict the proxy to serving only from a specific root:
Proxy(baseUrl, publicPath: '/remote');
Also, you can map requests to a root path on the remote server:
Proxy(baseUrl.replace(path: '/path'));
Request bodies will be forwarded as well, if they are not empty. This allows things like POST requests to function.
For a request body to be forwarded, the body must not have already been parsed. | https://pub.dev/documentation/angel_proxy/latest/ | CC-MAIN-2021-21 | refinedweb | 128 | 59.9 |
P U B L I S H I N G
pl
C o m m u n i t y
$ 44.99 US
27.99 UK
Sa
m
Simon Jackson
Unity 3D UI Essentials
Unity 3D UI Essentials
ee
D i s t i l l e d
Unity 3D UI Essentials
Leverage the power of the new and improved UI system for Unity
to enhance your games and apps
E x p e r i e n c e
Simon Jackson:
.
It truly has been a tormentous year but it looks to be getting better. Through
it all, my wife Caroline has been my tiller, keeping me straight and true
while I tend to my game development and writing efforts. Looking forward,
I'll likely be crafting more of my own experiences with my kids pitching in;
Caitlin, new to game development in school, being my sidekick, Jessica
adding her colorful artistic talent to the mix, and the boys (Alexander and
Nathan) no doubt trying to destroy my efforts through testing.
Additionally, a big thanks to my extended family (Mike and Marilyn) for
helping out with the kids and keeping the writing area a kids-free zone for a
few desperate hours. (It's amazing what a few hours respite can do.)
Also a big shout out to the PWSA (Prader-Willi Syndrome Association
) for their help and support with Alexander, plus the
Warrington Youth Club (
) for their exciting events to keep him
entertained, especially in his more trying times. On that last thread, a very
big thank you to Westland Drive respite (supported by Warrington council),
who give us peace of mind and a night off from time to time; Alexander
certainly loves his visits there.
Finally, thanks to the reviewers of this title (especially Simon W and
Andrew D who joined me from my previous book); they kept me grounded
and on target, although didn't help keeping the page count down. Thanks for
your support guys!
Unity 3D UI Essentials
A new era has dawned, and Unity Technologies have taken a big, bold step. Not only
have they delivered on some big promises for an all new and improved UI system for
Unity projects, but they have also made the source for the new UI completely open
source, giving everyday developers access to the inner workings of the new UI.
These are bold steps indeed. Many felt that the new UI wouldn't live up to the dream that
was sold, as it had been years since they announced it was coming. Delays and rewrites
made it look like it was never going to happen, leaving developers with either having to
live with the existing legacy GUI or pay for some of the more advanced GUI systems on
the asset store (such as NGUI).
Now, after a long and highly deliberated beta program, the new UI system is finally upon
us. In some areas, it meets our expectations; in some, it falls a bit short (however, this is
only the beginning). In other areas however, it has gone far beyond.
Throughout this title, we will peel back the layers of all this new technology to
understand what each component does, how it fits together, and how to use it to build a
fantastic new UI in our projects. Each chapter builds upon the last, to arm you (the
reader) with all the knowledge required to assemble your UI within your projects. You
will not just build on screen menus and options, but to embed UI elements within your
3D game world.
Not only have Unity released the new UI system, they have also given every developer
access to the source that builds the UI, allowing you to better understand how things are
built and enable you to extend the existing controls or even build your own. If you are
feeling adventurous, you can even submit fixes or new features back to Unity for them to
include within Unity itself.
Finally, we can now build what we want, how we want and best of all, it's completely
free and available with the Free license for Unity. All hail and rejoice!
Now what are you waiting for? Pack up your towel, brew a freshly hot cup of tea, crack
open this guide, and start exploring the all new universe of UI.
Chapter 3, Control, Control, You Must Learn Control, Unity UI introduces a heap-load
of new UI controls to suit just about any UI need, from buttons and checkboxes to entire
scrollable areas and layout masks. Here, we will delve deep into how to make the most of
all the controls available.
Chapter 4, Anchors Away, provides a detailed walk-through of how to make the most of
the new Unity UI anchor system and build responsive layouts/designs.
Chapter 5, Screen Space, World Space, and the Camera, Here we finally delve into one
of the most highly anticipated parts of the new UI system: the ability to easily build
perspective UI layouts and add UI elements as 3D objects within a scene.
Chapter 6, Working with the UI Source, looks at all the coding behind the UI framework
and explores the new Event System and UnityEvent frameworks. The chapter finishes
with a walk-through, the open source project for the UI system, allowing you to see just
about every line of code Unity has written for the new UI.
Appendix, The 3D Scene Sample, talks about a flashy 3D demo scene, which was
discussed in Chapter 5, Screen Space, World Space, and the Camera, to show off the UI.
Because this wasn't the focus of the book, it was added as an optional appendix that you
could follow if you wish. The instructions are also available online and as a
downloadable package to enable developers of all levels to make use of it.
Tips, tricks, and an understanding of legacy GUI and what it has done for us
State of play
You may not expect it, but the legacy Unity GUI has evolved over time,
adding new features and improving performance. However, because it has
kept evolving based on the its original implementation, it has been hampered
with many constraints and the ever pressing need to remain backwards compatible
(just look at Windows, which even today has to cater for programs written in BASIC
()). Not to say the old system is bad, it's
just not as evolved as some of the newer features being added to the Unity 4.x and
Unity 5.x series, which are based on newer and more enhanced designs, and more
importantly, a new core.
The main drawback of the legacy GUI system is that it is only drawn in screen space
(drawn on the screen instead of within it) on top of any 3D elements or drawing in
your scenes. This is fine if you want menus or overlays in your title but if you want
to integrate it further within your 3D scene, then it is a lot more difficult.
For more information about world space and screen space, see
this Unity Answers article (
questions/256817/about-world-space-and-localspace.html).
So before we can understand how good the new system is, we first need to get to
grips with where we are coming from. (If you are already familiar with the legacy
GUI system, feel free to skip over this section.)
[8]
Chapter 1
A point of reference
Throughout this book, we will refer to the legacy GUI simply as GUI.
When we talk about the new system, it will be referred to as UI or
Unity UI, just so you don't get mixed-up when reading.
When looking around the Web (or even in the Unity support forums),
you may hear about or see references to uGUI, which was the
development codename for the new Unity UI system.
GUI controls
The legacy GUI controls provide basic and stylized controls for use in your titles.
All legacy GUI controls are drawn during the GUI rendering phase from the built-in
OnGUI method. In the sample that accompanies this title, there are examples of all the
controls in the Assets\BasicGUI.cs script.
For GUI controls to function, a camera in the scene must have the
GUILayer component attached to it. It is there by default on any Camera
in a scene, so for most of the time you won't notice it. However, if you
have removed it, then you will have to add it back for GUI to work.
The component is just the hook for the OnGUI delegate handler, to
ensure it has called each frame.
Like the Update method in scripts, the OnGUI method can be called
several times per frame if rendering is slowing things down. Keep this
in mind when building your own legacy GUI scripts.
Label
Texture
Button
Text fields (single/multiline and password variant)
Box
Toolbars
Sliders
ScrollView
Window
[9]
The Label control supports altering its font settings through the use of the guiText
GameObject property (guiText.font) or GUIStyles. (See the following section on
GUIStyles for more detail.)
To set guiText.font in your script, you would simply apply the
following in your script, either in the Awake/Start functions or
before drawing the next section of text you want drawn in another font:
public Font myFont = new Font("arial");
guiText.font = myFont;
The Label control forms the basis for all controls to display text, and as such,
all other controls inherit from it and have the same behaviors for styling the
displayed text.
[ 10 ]
Chapter 1
The Label control also supports using a Texture for its contents, but not both text
and a texture at the same time. However, you can layer Labels and other controls
on top of each other to achieve the same effect (controls are drawn implicitly in the
order they are called), for example:
public Texture2D myTexture;
void Start() {
myTexture = new Texture2D(125, 15);
}
void OnGUI() {
//Draw a texture
GUI.Label(new Rect(125, 15, 100, 30), myTexture);
//Draw some text on top of the texture using a label
GUI.Label(new Rect(125, 15, 100, 30), "Textoverlay");
}
You can override the order in which controls are drawn by setting
GUI.depth = /*<depth number>*/; in between calls; however,
I would advise against this unless you have a desperate need.
The texture will then be drawn to fit the dimensions of the Label field, By default
it scales on the shortest dimension appropriately. This too can be altered using
GUIStyle to alter the fixed width and height or even its stretch characteristics.
GUIStyles and GUISkins are explained in the later GUI styles
and skins section.
Texture drawing
Not specifically a control in itself, the GUI framework also gives you the ability
to simply draw a Texture to the screen Granted there is little difference to using
DrawTexture function instead of a Label with a texture or any other control. (Just
another facet of the evolution of the legacy GUI). This is, in effect, the same as the
previous Label control but instead of text it only draws a texture, for example:
public Texture2D myTexture;
void Start() {
[ 11 ]
You can also provide scaling and alpha blending values when drawing the texture to
make it better fit in the scene, including the ability to control the aspect ratio that the
texture is drawn in.
A warning though, when you scale the image, it affects the
rendering properties for that image under the legacy GUI system.
Scaling the image can also affect its drawn position. You may have
to offset the position it is drawn at sometimes.
For example:
public Texture2D myTexture;
void Start() {
myTexture = new Texture2D(125, 15);
}
void OnGUI() {
GUI.DrawTexture(new Rect(325, 15, 100, 15), myTexture,
ScaleMode.ScaleToFit,true,0.5f);
}
This will do its best to draw the source texture with in the drawn area with alpha
blending (true) and an aspect ratio of 0.5. Feel free to play with these settings
to get your desired effect.
This is useful in certain scenarios in your game when you want a simple way to
draw a full screen image on the screen on top of all the 3D/2D elements, such as
pause or splash screen. However, like the Label control, it does not receive any
input events (see the Button control for that).
[ 12 ]
Chapter 1
This will pick a region from the source texture (myTexture) 50 pixels wide by
5 pixels high starting from position 10, 10 on the texture. It will then draw this to
the Rect region specified.
However, the DrawTextureWithTexCoords function cannot perform
scaling, it can only perform alpha blending! It will simply draw to fit
the selected texture region to the size specified in the initial Rect.
DrawTextureWithTexCoords has also been used to draw individual
sprites using the legacy GUI, which has a notion of what a sprite is.
The controls also support using a Texture for the button content as well by providing
a texture value for the second parameter as follows:
public Texture2D myTexture;
void Start() {
myTexture = new Texture2D(125, 15);
}
void OnGUI() {
if (GUI.Button(new Rect(25, 40, 120, 30), myTexture))
{ }
}
Like the Label, the font of the text can be altered using GUIStyle or by setting the
guiText property of the GameObject. It also supports using textures in the same
way as the Label. The easiest way to look at this control is that it is a Label that
can be clicked.
Description
TextField
TextArea
PasswordField
[ 14 ]
Chapter 1
Using the TextField control is simple, as it returns the final state of the value that has
been entered and you have to pass that same variable as a parameter for the current
text to be displayed. To use the controls, you apply them in script as follows:
string textString1 = "Some text here";
string textString2 = "Some more text here";
string textString3 = "Even more text here";
void OnGUI() {
textString = GUI.TextField(new Rect(25, 100, 100, 30),
textString1);
textString = GUI.TextArea(new Rect(150, 100, 200, 75),
textString2);
textString = GUI.PasswordField(new Rect(375, 100, 90, 30),
textString3, '*');
}
As with the Label and Button controls, the font of the text displayed can be altered
using either a GUIStyle or guiText GameObject property.
Note that text will overflow within the field if it is too large for
the display area, but it will not be drawn outside the TextField
dimensions. The same goes for multiple lines.
[ 15 ]
Note that using the Box control does not affect any controls you draw
upon it. It is drawn as a completely separate control. This statement
will be made clearer when you look at the Layout controls later in
this chapter.
[ 16 ]
Chapter 1
The example will draw the box background and the Label, Text, and Button controls
on top of the box area and looks like this:
The box control can be useful to highlight groups of controls or providing a simple
background (alternatively, you can use an image instead of just text and color).
As with the other controls, the Box control supports styling using GUIStyle.
As with the Label and Button controls, the font of the text displayed can be altered
using either a GUIStyle or guiText GameObject property.
[ 17 ]
Toolbar panels
The basic GUI controls also come with some very basic automatic layout panels:
the first handles an arrangement of buttons, however these buttons are grouped
and only one can be selected at a time.
As with other controls, the style of the button can be altered using a GUIStyles
definition, including fixing the width of the buttons and spacing.
There are two layout options available, these are:
As with other controls, the Toolbar returns the index of the currently selected button
in the toolbar. The buttons are also the same as the base button control so it also
offers options to support either text or images for the button content.
The RepeatButton control however is not supported.
To implement the toolbar, you specify an array of the content you wish to display in
each button and the integer value that controls the selected button, as follows:
private int toolbarInt;
private string[] toolbarStrings ;
Void Start() {
toolbarInt = 0;
toolbarStrings = { "Toolbar1", "Toolbar2", "Toolbar3" };
}
void OnGUI() {
toolbarInt = GUI.Toolbar(new Rect(25, 200, 200, 30),
toolbarInt, toolbarStrings);
}
[ 18 ]
Chapter 1
The main difference between the preceding controls is that you have to pass the
currently selected index value in to the control and it then returns the new value.
The Toolbar when drawn looks as follows:
As stated, you can also pass an array of textures as well and they will be displayed
instead of the text content.
The main difference between SelectionGrid and Toolbar in code is that with
SelectionGrid you can specify the number of items in a single row and the control will
automatically lay out the buttons accordingly (unless overridden using GUIStyle).
The preceding code will result in the following layout:
On their own, they provide a little more flexibility than just using buttons alone.
[ 19 ]
The slimmer Slider and chunkier Scrollbar controls can both work in either
horizontal or vertical modes and have presets for the minimum and maximum
values allowed.
[ 20 ]
Chapter 1
Like Toolbar and SelectionGrid, you are required to pass in the current value and
it will return the updated value. However, unlike all the other controls, you actually
have two style points, so you can style the bar and the handle separately, giving you
a little more freedom and control over the look and feel of the sliders.
Normally, you would only use the Slider control; The main reason the Scrollbar is
available is that it forms the basis for the next control, the ScrollView control.
Here we have a list that has many items that go beyond the drawable area of the
ScrollView control. We then have the two scrollbars to move the content of the
scroll viewer up/down and left/right to change the view. The background content
is hidden behind a viewable mask that is the width and height of the ScrollView
control's main window.
Styling the control is a little different as there is no base style for it; it relies on
the currently set default GUISkin (see the following GUIStyles section). You can
however set separate GUIStyles for each of the sliders but only over the whole
slider, not its individual parts (bar and handle). If you don't specify styles for each
slider, it will also revert to the base GUIStyle.
[ 21 ]
[ 22 ]
Chapter 1
If you want to, you can also nest ScrollView controls within each other.
The ScrollView control also has some actions to control its use like the ScrollTo
command. This command will move the visible area to the coordinates of the virtual
layer, bringing it into focus. (The coordinates for this are based on the top-left
position of the virtual layer; 0,0 being top-left.)
To use the ScrollTo function on ScrollView, you must use it within the Begin and
End ScrollView commands. For example, we can add a button in ScrollView to
public Vector2 scrollPosition = Vector2.zero;
void OnGUI()
{
scrollPosition = GUI.BeginScrollView(
new Rect(10, 10, 100, 50),
scrollPosition,
new Rect(0, 0, 220, 10));
if (GUI.Button(new Rect(120, 0, 100, 20), "Go to Top Left"))
GUI.ScrollTo(new Rect(0, 0, 100, 20));
GUI.EndScrollView();
}
You can also additionally turn on/off the sliders on either side of the control by
specifying the BeginScrollView statement using the alwayShowHorizontal and
alwayShowVertical properties; these are highlighted here in an updated
GUI.BeginScrollView call:
Vector2 scrollPosition = Vector2.zero;
bool ShowVertical = false; // turn off vertical scrollbar
[ 23 ]
<b></b>
This gives text a Bold format, for example:
The <b>quick</b> brown <b>Fox</b> jumped over the <b>lazy Frog</b>
<i></i>
Using this tag will give text an Italic format, for example:
The <b><i>quick</i></b> brown <b>Fox</b><i>jumped</i> over the
<b>lazy Frog</b>
<size></size>
As you can probably guess, this tag will alter the Size of the text it surrounds.
For reference, the default size for the font is set by the font itself.
[ 24 ]
Chapter 1
For example:
The <b><i>quick</i></b> <size=50>brown <b>Fox</b></size> <i>jumped</
i> over the <b>lazy Frog</b>
brown Fox
<color></color>
Lastly, you can specify different colors for text surrounded by the Color tag.
The color itself is denoted using its 8-digit RGBA hex value, for example:
The <b><i>quick</i></b> <size=50><color=#a52a2aff>brown</color>
<b>Fox</b></size> <i>jumped</i> over the <b>lazy Frog</b>
Note that the color is defined using normal RGBA color space
notation (
space) in hexadecimal form with two characters per color, for
example, RRGGBBAA. Although the color property does also
support the shorter RGB color space, which is the same notation
but without the A (Alpha) component, for example,. RRGGBB
brown Fox
(If you are reading this in print, the previous word brown is in the color brown.)
You can also use a color name to reference it but the pallet is quite
limited; for more details, see the Rich Text manual reference page at.
<material></material>
<quad></quad>
These only apply when associated to an existing mesh. The material is one of the
materials assigned to the mesh, which is accessed using the mesh index number
(the array of materials applied to the mesh). When applied to a quad, you can also
specify a size, position (x, y), width, and height to the text.
[ 25 ]
The text mesh isn't well documented and is only here for reference;
as we delve deeper into the new UI system, we will find much better
ways of achieving this.
Grouping controls
The legacy GUI allow you to group controls together on the screen, making all
positions for the group relative to the group's position. This means that if you started
a group at position X 50 and Y 50, then all child control positions within the group
would start at 50,50 when they define their position as 0,0.
Like the ScrollView control, each group has a beginning and an end to define the
scope of all the controls within the group, for example:
void OnGUI() {
//Start a group at position 50, 50. 150 width and 60 height
GUI.BeginGroup(new Rect (50,50,150,60));
//Draw a label with a 10, 10 offset in the group
GUI.Label(new Rect (10, 10, 100, 30), "Label in a Group");
GUI.EndGroup();
}
Here the label is drawn within the group bounds, and as the group starts at X 50,
the Labels screen position will be at X 60 (50 + 10). Anything positioned or
overflowing the group's bounds will not be drawn.
The group, like other controls, can also specify content within the group as text or a
texture with appropriate GUIStyles.
What is odd is that unlike the rest of the controls, if you specify text
content in the function, the default color of text is white, whereas if you
specify text in the content parameter for the BeginGroup function, the
text in the group is black by default. It's also left justified instead
of centered.
Additionally, by default the group does not support Rich Text
Formatting unlike the other controls, so you will need to apply
GUIStyle to change that.
[ 26 ]
Chapter 1
Naming controls
With each control that you implement through script, you can name them as you
place them; this is essential if you want to control flow and access to each field from
the keyboard or to derive logic based on the currently selected/focused control.
Now unlike most other Unity functionality, you cannot directly name controls,
there is no Name field on the properties of the controls as they are just commands
to the GUI system to draw things to the screen, kind of like a rendering pipeline.
So to name GUI controls in Unity, we simply need to tell the GUI system that the
next control we are going to draw has a name, as follows:
string login = "Would you like to play a game?";
void OnGUI() {
GUI.SetNextControlName("MyAwesomeField");
login = GUI.TextField(new Rect(10, 10, 200, 20), login);
}
Getting in focus
With names defined on controls, you could then define which control you were
focusing on. To focus on a specific control, you would simply need to call:
GUI.FocusControl("MyAwesomeField");
This would then change the user's input focus or selection to the specific GUI control
with that name.
Once you have a control in focus, you then discover the name of the specific control
in focus by calling:
string selectedControl = GUI.GetNameOfFocusedControl();
If the control in focus has a name, it will return the name you set for that control.
If no control is in focus or the control in focus has no name, it will return an
empty string.
To start, create a new script called IntermediateGUI in your project (the full sample
can be found in the project available with this book in the code download) and
replace its contents with the following:
using UnityEngine;
[ExecuteInEditMode]
public class IntermediateGUI : MonoBehaviour {
public string username = "Enter username";
public string password = "Enter password";
private bool passwordInError = false;
private string passwordErrorMessage =
"<color=red>Password too short</color>";
}
This gives a basic class with some of the parameters you might expect in a logon
or registration form.
To this we'll add a simple function to validate the password entered to ensure it
meets our stringent security policy:
void CheckUserPasswordAndRegister()
{
if (password.Length < 6)
{
//If the password is not long enough, mark it in error
//and focus on the password field
passwordInError = true;
GUI.FocusControl("PasswordField");
} else
{
passwordInError = false;
GUI.FocusControl("");
//Register User
}
}
[ 28 ]
Chapter 1
GUI.SetNextControlName("UsernameField");
username = GUI.TextField(new Rect(10, 40, 130, 20), username);
GUI.SetNextControlName("PasswordField");
password = GUI.PasswordField(new Rect(10, 70, 130, 20),
password,'*');
if (passwordInError)
{
GUI.Label (new Rect (10, 100, 200, 20),
passwordErrorMessage);
}
if (Event.current.isKey &&
Event.current.keyCode == KeyCode.Return &&
GUI.GetNameOfFocusedControl() == "PasswordField")
{
CheckUserPasswordAndRegister();
}
if (GUI.Button(new Rect(80, 130, 65, 20), "Register"))
{
CheckUserPasswordAndRegister();
}
GUI.EndGroup();
}
Note that the Event keyword here relates to the legacy GUI event
system for handling user input. See the Event section later in this
chapter for more information.
This is NOT to be confused with the UnityEvent system introduced
with the new UI system.
[ 29 ]
In this example, we draw a box, a text field, and a password field together with a
simple button within a group, which is then centered on the screen.
We check whether the user hits the Enter key and whether they are on the password
field (checked using the GUI.GetNameOfFocusedControl() function) and we try to
register them. The same happens if the user clicks on the Register button.
If the user's password is longer than six characters, then they are registered; if not,
then the passwordInError flag is set to True, which causes the additional label to
be drawn, this then warns the user that their password could be broken easily by
a 6-year-old.
Don't forget to add the IntermediateGUI script to an active
GameObject in a scene or Main Camera to see the result!
Tooltips
Each of the GUI controls can also have a tooltip associated with it to display some
additional text when it is either in focus or the mouse is hovering over the control.
Adding a tooltip is simple; you just need to replace the content of the control when it
is being drawn using the GUIContent class. For example, we can update the Register
button in the previous script as follows:
if (GUI.Button(new Rect(80, 130, 65, 20),
new GUIContent("Register", "My Tooltip")))
{
CheckUserPasswordAndRegister();
}
With the tooltip defined, we just then need to display the current tooltip somewhere
on the screen, usually as a label, but it can be any control that can display text (input
fields are not recommended however), so add the following after the button block
but before EndGroup():
GUI.Label (new Rect (10, 120, 65, 20), GUI.tooltip);
This simply gets the content of the current tooltip in focus and returns the tooltip text
for that control.
GUIContent also has several other options for displaying text and
texture variants, so it's worth checking out some more.
[ 30 ]
Chapter 1
The drag state of Window; as in, the window can be dragged by holding
on with a mouse or touch
The draw order of each Window; this allows sorting of draw windows on
top of each other
To create a Window control, you first need to define a new method callback for the
Window using the following signature:
void DoMyWindow(int windowID)
{
}
[ 31 ]
This method is where you will add all your GUI code using the previous examples;
each control is positioned is based off the top-left position of the window when it is
displayed (same as the Group and ScrollView controls described earlier).
Additionally, you can specify any of the previous options for the window,
for example:
void DoMyWindow(int windowID)
{
GUI.Label(new Rect(25, 15, 100, 30), "Label");
// Make the window Draggable
GUI.DragWindow();
}
With your Window method in place, you just need to call the GUI.Window function
to open it along with the property to track the Window's location:
private Rect rctWindow1;
void OnGUI()
{
Rect rctWindow1;
rctWindow1 = GUI.Window(0,
rctWindow1,
DoMyWindow,
"Controls Window");
}
If you want a modal window, then you would need to instantiate the window with
the GUI.ModalWindow function instead of the Window function:
rctWindow1 = GUI.ModalWindow(0, rctWindow1, DoMyWindow, "Modal
Controls Window");
If we take all the controls together (that we have created so far in this chapter),
it would create a Window view, as shown in the following screenshot:
For a complete end-to-end example, please see the code download
package, which has all this defined.
[ 32 ]
Chapter 1
[ 33 ]
A Name
A texture or text color for the different states of the control it's attached to
(Normal, Hover, Active, and Focused)
The border, margin, padding, and overflow sizes for the control
(for each edge)
A Font (with suitable size, style, alignment, word wrapping, and rich
text support options)
It is worth noting that having too many different GUIStyles all over
the place can become very inefficient and hard to maintain. If you
find you are using a lot of GUIStyles then I'd recommend you create
a single script attached to a common object (say Main Camera) in
your scene with all your GUIStyle's defined and have each script take
GUIStyle references from there.
[ 34 ]
Chapter 1
When you attach the preceding script with the GUIStyle property to a GameObject
in your scene, it will look like this in Inspector:
Note that the first time you open it in the editor you will
get NullReferenceException in the console window;
this is just because you haven't configured GUIStyle yet.
If you don't want to apply a style to each and every control directly, you can then
optionally create GUISkin, which contains all the styles for each control type.
This is then applied using the GUI class prior to drawing any controls.
A GUISkin also has some additional options that apply to the GUI, which include:
Custom styles (an array of GUIStyle properties you can then reuse
on controls)
[ 35 ]
To demonstrate, click on the Create button in the project folder view and select
GUISkin, which will give you a new GUISkin asset in the project view. By selecting
it, you will see the following window in Inspector:
As you can see, it contains all the options for altering the style globally for each
control. To use GUISkin, create a new script called GUISkins, then replace its
contents with the following:
using UnityEngine;
[ExecuteInEditMode]
public class GUISkins : MonoBehaviour {
public GUISkin MySkin;
void OnGUI()
{
GUI.skin = mySkin;
GUI.Label(new Rect(25, 15, 100, 30), "Label");
//Draw the rest of your controls
}
}
Then attach the GUISkins script to Main Camera in your current scene
(disabling any other scripts currently attached) and drag the GUISkin you
have created and apply it to the My Skin property of the script in the inspector:
[ 36 ]
Chapter 1
By setting the skin at the beginning of any GUI drawing, any and all controls drawn
will now use your custom skin instead of the Unity default. If you wish, you can use
several skins by just changing the skin before drawing more controls.
For some of the best examples of GUISkins, try installing the Unity Extra GUI Skins
asset (), which is a collection of skin samples
built by Unity themselves (and it's free).
Note that if you want to reuse your own skins in other projects
(or sell more skins through the asset store), then you can export
them using Unity's Export Package option under Assets in the
menu. For more details, check out
Manual/HOWTO-exportpackage.html
[ 37 ]
To access the events you simply need to query the Event.current property to get
the current Event state. (The Event state updates when there is a change, until then
you will get the last/previous state.)
The logon example earlier shows an example for using events, where we detect if
the user has pressed a key and if that key is the Enter key as shown in this script:
if (Event.current.isKey &&
Event.current.keyCode == KeyCode.Return &&
GUI.GetNameOfFocusedControl() == "PasswordField")
{
CheckUserPasswordAndRegister();
}
Along with the events, the GUI class also provides some additional properties you
can query or set in the OnGUI method, namely:
enabled: Is the GUI enabled and displayed on the screen. Can it be used to
changed: This returns true if any controls' values have changed since the last
call of OnGUI.
color: This is the global color tint for the GUI layout.
contentColor: This is the global text color tint for the GUI.
[ 38 ]
Chapter 1
depth: This is the depth order for the current GUI script. This is useful if you
have GUI elements in more than one script and want to layer them.
All of these elements can be used to override all controls or individual controls by
setting them in between controls.
Layout controls
If you prefer not to hand draw the position of every single control in your GUI,
Unity does offer some automatic layout controls from the GUILayout class.
The Layout controls (using GUILayout instead of just GUI) have the same set of
controls as the normal GUI class (hence I'm not going to describe them all over
again), the main difference is that you do not need to specify a Rect area to draw
the control, as it will just be drawn at the first suitable location; any further controls
added will be laid out appropriately with enough spacing between the controls.
You can also control the spacing and even if you want, any empty space between the
controls using the Width, Height, and Spacing properties (Space/FlexibleSpace) of
GUILayout, following the same rules as for GUI controls (setting up the GUILayout
before drawing a control).
If you don't want the layout to take up the maximum space for a control,
you also have the settings for Width (MaxWidth/MinWidth) and Height
(MaxHeight/MinHeight).
The main differences are as follows:
BeginArea
Instead of defining Groups, you define Areas. Apart from the name, they behave
exactly the same. This is the only layout control that takes a Rect parameter to
specify where you want to draw the controls (excluding Windows of course); all
GUILayout controls are then aligned to Area in the same way they are in Group.
It's recommended that when using GUILayout controls that you
place them in an Area for the best effect.
[ 39 ]
Enter Thunderdome
Now that you've seen what Unity has had available for so long with the legacy GUI
(and if you have experienced it you will undoubtedly shudder at this point), it is a
very welcome relief that the UI system has received such an overhaul in Unity 4.6.
It has been a long time coming and very much anticipated!
Note that this section is just a preliminary overview so you know
what's coming. Each section will be described in depth in the
following chapters.
Recognizing the need for change, Unity set upon the path of redesigning the GUI
system from the ground up. They have looked at what games have needed, what the
community has built (even with the limitations and restrictions of not having access
to Unity's core) and then sprinkled some fairy dust and hey presto, the new Unity UI
system was born.
[ 40 ]
Chapter 1
It has been a long, hard road with many bumps in the way, but the journey has
begun (I say begun because the Unity UI journey does not end with Unity 4.6;
it will continue to evolve into Unity 5 and beyond like many other components).
With a keen eye on the future, the new Unity UI system delivers on several core
points, namely:
Extensibility: Each and every control is a script and you can create new
scripts to derive from them and create your own controls.
Uses sprites: The new Unity UI system is predominately built on top of the
new sprite system introduced in Unity 4.3. It has also however extended the
sprite system with some new features as well.
Exposed events: Each control has its own events which you can attach to and
extend upon.
Tight integration with rendering and update loops: Because they are
GameObjects, you can even override the default rendering and updating
of a control.
Animation: Each control can be fully animated using the new Animator
dope sheet and Mecanim. Some controls (such as the button) leverage
Mecanim to do state-driven control. There are even animation specific events.
FREE: Unity UI comes as standard as part of the free license version of Unity
(indie developers rejoice).
Open source: Unity has made the source for the UI system open source and
available for anyone to look at and even offer fixes / new suggestions,
to coders delight.
New layouts
The layout features begin the story of the new Unity UI; they set the stage and
ultimately define where controls will be drawn, in which direction they will be
drawn, and also how they fit within a certain area.
[ 41 ]
Rect Transform
Introduced in 4.3 with the new Sprite functionality, the Rect Transform component
provides a defining region for any 2D element within the Unity system. However,
like most things in 4.6, it has received significant updates allowing more control over
the area it manages as shown here:
It also sports a new button in the editor (called the Rect Tool) to edit and manage
Rect Transform from the scene view, as shown in the following screenshot:
The Canvas
At the core of all Unity UI drawings, is the new Canvas control. It acts as the paint
board for your Unity UI controls (and even other canvases), once rendered the
canvas is drawn to the relative point in your scene.
Thanks to vast improvements this canvas can be drawn in basic 2D overlay mode
(same as the legacy GUI system), in 2D camera space (adding perspective), or
even directly in 3D world space like as any other traditional 3D object (such as a
rendertarget for UI) as shown here:
[ 42 ]
Chapter 1
Groups
In the legacy GUI, groups were defined by the controls themselves;
if you wanted to orientate multiple controls together in a particular fashion,
you simply couldn't.
With the new Unity UI system, you can define several layout groups.
[ 43 ]
Toggle Group
A Toggle Group manages arranges toggle controls in to a group where only one
can be active at a time (Like a Multiple choice selection where only one option can
be chosen).
Canvas Group
A Canvas Group allows you to generically group child UI controls together and
affect several common properties from the group, for example, the Alpha value
of all child items:
Masking
Recognizing the need for generic masking capabilities within the new Unity UI system
(the ability to hide portions of UI within a certain region), they created a new Mask
component. This can be added to any GameObject and any child objects outside the
bounds of the parent GameObject would not be drawn, either partially or fully.
The Image control (highlighted later in the chapter) also includes an additional
masking feature, when the Image Type property of an image is set to Filled;
it gives several additional masking options to gradually bring the image into
view. Just for reference now, we'll go into this in a lot more detail later.
New controls
Something old, something new, something borrowed, something blue.
Obviously when we look at a GUI, there is only so much that is really needed and
Unity has recognized this. Starting with a fresh slate, they have looked at what it
means to create a stunning UI and what you need to build one.
[ 44 ]
Chapter 1
So with this fresh start, here are the new Unity UI controls:
Control
Description
Selectable
The selectable component is the base object for anything that needs
interaction, and it basically turns any other component into a
button. Note that it cannot be used on the same GameObject with
something that is already selectable (button, toggle, and sliderbar).
(only available in
the component list)
Panel
Text
If text is your aim, then this control is for you. It gives you text
options like font, color, font style, and overflow. Can also be set to
resize text to fit the container it is in.
Image
Raw Image
Button
If you need a big red (color optional) button to press, then this
control is for you. The button has received the biggest overhaul
by far with so many options it will likely take a chapter on its
own to explain.
It also includes a new UnityEvent framework that allows you to
create behaviors that can affect other objects or scripts directly from
the editor.
You can even set different colors for different states of the button,
swap out images, or if you wish, use Mecanim and the new
animation system to animate the button between states.
Toggle
Switch it on, switch it off. The toggle takes the button behavior and
extends it as a prime example of what extensibility features are in
the new UI framework. It adds additional properties to the button
framework to identify the checkbox graphic and a grouping option
should you want to group checkboxes (using a Toggle group).
Scrollbar
It slices, it dices, it even slides as well. Your typical scroll bar with
a handle, fully customizable with options to control the direction,
minimum and maximum values, step size, and number of steps to
slide between. Also includes the event system used for buttons for
when the value changes.
Slider
Control extensibility
One very cool feature of the new UI system is that practically every component is
a script, meaning it can be used as the base for any new scripts you create. You can
either use them as is or even extend them further.
In Chapter 6, Working with the UI Source, we will cover the coding behind all these
components including a walk through the open source library. I'll even throw in a
load of examples and reusable components from the community and myself.
Animation
A core tenant of the new UI system (since it is built upon the core of the new 2D
sprite system) was animation. Every single control or component of the new Unity
UI system is able to be fully animated.
Not only that, but it also gives different modes for how properties can be animated,
from static fixed values to dynamic values that will alter and update with the
controls behavior.
[ 46 ]
Chapter 1
I'll point these out again in some of the chapters where you will get the most use out
of them or where they are relevant.
The most notable assets at the time of writing are the following.
TextMeshPro ($65)
This is
TextMeshProAnimation.)
You can find TextMeshPro on the asset store here:
UnityUITextMeshPro.
[ 47 ]
MenuPage ($10)
Not every asset for the new UI has to be a big beast of a tool meant to save you
hours, sometimes you just need something to get you off the ground and using the
new UI with great effect. This is where MenuPage comes in.
Put simply it's a new asset on the store aimed at building menu systems using the
new UI system automatically. They are fully configured, laid out effectively and
offer some advanced features such as fading, transitions, and much more.
What's even better is that all the source code is there and is fully documented/
commented, so you can learn from some of the best coders out there purveying
their wares.
You can find MenuPage on the asset store here:.
Summary
So now we have a deep appreciation of the past and a glimpse into the future.
One thing you might realize is that there is no one stop shop when it comes to
Unity; each feature has its pros and cons and each has its uses. There may still
be cases when it is just easier to use the Unity legacy GUI to achieve an effect
(still using the basic GUI.DrawTexture for a splash screen for example, although
even that is very easy with the new UI system) provided you take the performance
concerns on board with mobile devices. It all comes down to what you want to
achieve and the way you want to achieve it; never dismiss anything just because
it's old (except for GUIText and GUITexture, they are just really really old)
[ 48 ]
Chapter 1
Whistlestop tour of the new Unity UI system and what we can expect from
this title
In the next chapter, we will start with the underlying framework and guts behind
the new GUI system, namely:
The new Rect Transform control (not just for Unity UI)
What Unity have done for scaling and resolution for UIs
The all new and improved Event messaging system for the Unity UI system,
complete with new shiny raycasting features and helpers
It promises to be a fun ride, and once we are through that, then in chapter 3,
Control, Control, You Must Learn Control we can move on to actually building
some UI and then placing it in your game scenes in weird and wonderful ways.
Now stop reading this and turn the page already!!
[ 49 ]
Stay Connected:
Much more than documents.
Discover everything Scribd has to offer, including books and audiobooks from major publishers.Cancel anytime. | https://www.scribd.com/document/254155632/9781783553617-Unity-3D-UI-Essentials-Sample-Chapter | CC-MAIN-2019-51 | refinedweb | 7,836 | 64.14 |
New Pybytes firmware 1.18.1.r9 (Experimental LTE support)
- Xykon administrators last edited by Xykon
Hello everyone,
I have now released a new Pybytes firmware version 1.18.1.r9
This fixes the issue reported here, however I noticed that data sent via LoRa currently doesn't seem to display correctly. I'll ask the Pybytes team to look into this tomorrow.
It is now possible to enable ssl with a single command (for WiFi and LTE connections):
pybytes.enable_ssl()
After a reset, this will automatically create the pycom-ca.pem file if it does not already exist in /flash/cert.
Experimental LTE support (Please make sure your modem is updated to the latest CAT-M1 or NB-IoT firmware as Pybytes may not work with older versions):
To enable connectivity via LTE, you need to manually update the configuration to connect via LTE. If you have not already, first set up your device using WiFi and then use the following to connect via LTE:
The first step is to configure the LTE connection parameters. There are 5 parameters, depending on your connection:
carrier: If you use a carrier for which auto-configuration is available (ex: Verizon), you just need to set this
band: If you did not configure a carrier, it is highly suggested that you specify the band used by the network you are trying to reach. Scanning through all enabled bands can take a very long time.
cid: is a Connection ID. This is carrier specific, for Verizon use cid=3. Most other operators use cid=1 which is the default
apn: Some operators require that you specify an APN name.
reset: If set True this will reset the modem when disconnecting
Some configuration examples:
Verizon:
pybytes.set_config('lte', { "carrier": "verizon", "cid": 3 })
CAT-M1 band 13:
pybytes.set_config('lte', { "band": 13})
NB-IoT band 20:
pybytes.set_config('lte', { "band": 20, "apn": "default.mnc001.mcc001.gprs", "reset": True})
After setting the LTE parameters, you need to tell Pybytes to use the LTE connection. You can either use just the LTE connection:
pybytes.set_config('network_preferences', ["lte"])
Or you can configure multiple network connections. For example, when using
pybytes.set_config('network_preferences', ["wifi", "lte"]), Pybytes will attempt to connect via WiFi first and fall back to LTE if the WiFi network is out of range.
You can check your configuration with
pybytes.print_config()
To activate the new configuration, restart your device.
Update:
I also added some debugging features to Pybytes that are especially useful when tryout out LTE.
To activate this please use the following:
import pycom pycom.nvs_set('pybytes_debug', 1)
You can set various debug levels from 0 (some warnings) to 6 (currently the highest being used).
@jirkakrepl said in New Pybytes firmware 1.18.1.r9 (Experimental LTE support):
If your LTE configuration is correct, your device with a Simcard should connect to Pybytes using LTE.
Then Terminal and Flash OTA update should work too.
Awesome, I'll try it out soon, thanks! LTE OTA was only thing holding us back from a production release.
- jirkakrepl last edited by jirkakrepl
I haven't tested it thoughtfully myself yet. But it is now possible:
- Create LTE configuration in Pybytes
- Create a device and use this LTE configuration
- Use firmware updater to add this device to Pybytes
If your LTE configuration is correct, your device with a Simcard should connect to Pybytes using LTE.
Then Terminal and Flash OTA update should work too.
@jirkakrepl Is this still happening?
- jirkakrepl last edited by
@jirkakrepl Does this mean REPL and firmware/OTA updates will work over cellular natively in pybytes then?
- jirkakrepl last edited by
@eric-waai Hi, we're going to add LTE support to Pybytes at the end of Q1, start Q2.
For anyone else having issues, I had better luck with the following:
"network_preferences": ["lte"], ""lte": {"carrier": "standard"}
This works with Hologram in the US on Verizon.
It connects to MQTT and such:
Pybytes configuration read from /flash/pybytes_config.json LTE init(carrier=standard) LTE attach(band=None, apn=None) LTE connect(cid=1) LTE is_connected() LTE connection established Using MQTT over TLS This is PybytesProtocol.start_MQTT(check_interval=0.5, networkType=0) This is PybytesProtocol.__start_recv_mqtt() Using 8192 bytes as stack size Connected to MQTT mqtt.pybytes.pycom.io This is PybytesProtocol.__check_mqtt_message() Pybytes connected successfully (using the built-in pybytes library) This is pack_info_message() __pack_message: b'\x81\x05\x04\x90\x03\x8a\x04' Sending message:[b'\x81\x05\x04\x90\x03\x8a\x04'] with topic:[None] and finalTopic: [xxxx-xxxx-xxxx-xxxx-xxxx] Now starting user code in main.py
But, the terminal, flash browser, etc... on pybytes do NOT work over LTE, still. Is that expected? It says my device is offline. However, I can talk to the internet just fine from my device.
So I understand, this does not provide LTE support for Pybytes, on the web, just for auto-connecting to LTE? Or should it work?
0_1546860841813_stack_overflow coredump.py never mind,
got it working ;)
got the first stack overflow also
@Xykon
Hi
nice update one question.
if i want to add a fipy in pybytes i can't add the LTE-m as network connection.
as far i can read i have to do it manually, is this optoin to automate this coming to pybytes.
i'm also quite unfamiliar with json can you give an example json file? | https://forum.pycom.io/topic/4185/new-pybytes-firmware-1-18-1-r9-experimental-lte-support/ | CC-MAIN-2021-04 | refinedweb | 895 | 57.16 |
Hello I am working on an assignment and I'm running into issues I was hoping for a little direction...
The purpose is to have user input a phrase and create an acronym out of that phrase. Anything over three words will be ignored.
I'm having issues with the acronym part, I am able to get the first character and figured that I would loop through the user input and grab the character after a space, but that is not working. All I am getting is the first character, which is obvious because I grab that first, but I can't figure out how to "save" the other two characters. Any help is greatly appreciated.
*********UPDATE************************
So thanks to an answer below I have made progress with using the StringBuilder. But, now if I enter "Your Three Words" the Output is: YYYYYTYYYYYWYYYY
Which is progress but I can't understand why it's repeating those first characters so many times??
I edited the code too.
*********UPDATE*****************************
public class ThreeLetterAcronym {
public static void main(String[] args) {
String threeWords;
StringBuilder acronym = new StringBuilder();
Scanner scan = new Scanner(System.in);
System.out.println("Enter your three words: ");
threeWords = scan.nextLine();
for(int count = 0; count < threeWords.length(); count++) {
acronym.append(threeWords.charAt(0));
if(threeWords.charAt(count) == ' ') {
++count;
acronym.append(threeWords.charAt(count));
}
}
System.out.println("The acronym of the three words you entered is: " + acronym);
}
}
You can't save the other characters because char is supposed to store only one character. You can use a StringBuilder in this case
StringBuilder acronym = new StringBuilder();
Then in your loop simply replace it with
String[] threeWordsArray = threeWords.split(" "); for(String word : threeWordsArray) { acronym.append( word.substring(0, 1) ); }
**updated
You store the character at the current index in
space:
char space = threeWords.charAt(count);
Then you compare the value of
space with the integer value
3:
if(space < 3)
This will almost certainly never be true. You are asking for the numeric value of a character. Assuming it is a letter it will be at least
65. I suspect that your intention is to store something different in the variable
space. | http://m.dlxedu.com/m/askdetail/3/766a509ae1aa78ba79a8a4e1fa6e1934.html | CC-MAIN-2019-04 | refinedweb | 357 | 65.22 |
Want to see the full-length video right now for free?
Let's get into the nuts and bolts of TDD.
In this example, we're going to build a calculator through a test-driven process. For our Ruby tests, we're going to use RSpec, a popular testing library with an expressive DSL and excellent community support. We'll use RSpec's autorun feature during this example to run tests every time we update our files. We don't typically use this feature, but it will make checking our work during the Trail faster.
We'll start by writing a test. RSpec uses nested blocks to group tests together.
The outermost block describes the class (
Calculator), and the next level in
describes our method,
#add. One more level in, and we write the spec for our
first behavior inside an
it block.
describe Calculator do describe "#add" do it "adds two numbers" do calculator = Calculator.new expect(calculator.add(1, 1)).to eq(2) end end end
The contents of the spec are mostly the Ruby you already know. RSpec's DSL
provides some methods that give your tests some English readability.
#expect
is how you tell RSpec to perform some verification of test results.
The first run of the test suite gives us an error. This is good! Errors in TDD help us determine what incremental step to take next. The new code should implement the simplest possible logic (within reason) to resolve the error.
First, we add the class, as our error is due to
Calculator not being defined.
Adding the class will then lead to an error about an undefined method
#add.
Implementing
Calculator#add will then lead to an error about an incorrect
number of arguments. Giving
#add arguments will then lead to an error about
the returned value being
nil rather than the sum. Now it's time to implement
our method logic.
class Calculator def add(a, b) end end
Hard-coding
#add to return
15 and make the test pass may seem like a bad
idea, but we're not done yet. Now that our test passes, we'll write another test
that requires a more generalized solution. A second test exposes our hard-coded
return value as an inadequate solution and requires a better implementation to
make both tests pass.
It's not always necessary to resolve tests initially through a hard-coded value, but the initial implementation and the quick iteration to a general implementation illustrates how TDD can guide you to the minimum code needed to deliver the feature.
With the
#add method working as we want, it's time to add a new capability to
our calculator, to return the result of a factorial.
Factorial has two cases: factorial for a number is all of the positive integers
from one up to that number multiplied by each other. Factorial
0, the special
case, is
1. We'll write a test to handle each of these cases:
describe "#factorial" do it "returns 1 when given 0 (0! = 1)" do calc = calculator.new expect(calc.factorial(0)).to eq(1) end it "returns 120 when given 5 (5! = 120)" do calc = calculator.new expect(calc.factorial(5)).to eq(120) end end
We'll resolve errors for each of the tests individually, starting with the
simplest case, factorial
0. First, we define the method, then we give the
method an argument, then we return the expected result.
def factorial(n) 1 end
Our spec passes, and we can move on to the more complicated general case, which
is still failing. A recursive solution is straightforward approach, with an
if
clause guarding against the
0 case.
def factorial(n) if n == 0 1 else n * factorial(n-1) end end
With passing tests, we're green across the board. This state is a great time to do some refactoring, while your understanding of the code is fresh and your test suite is ready to backstop you against regressions.
Now it's time to get your hands dirty with a TDD exercise.
spec.rb.
gem install rspec
rspec spec.rb
# Use TDD principles to build out name functionality for a Person. # Here are the requirements: # - Add a method to return the full name as a string. A full name includes # first, middle, and last name. If the middle name is missing, there shouldn't # have extra spaces. # - Add a method to return a full name with a middle initial. If the middle name # is missing, there shouldn't be extra spaces or a period. # - Add a method to return all initials. If the middle name is missing, the # initials should only have two characters. # # We've already sketched out the spec descriptions for the #full_name. Try # building the specs for that method, watch them fail, then write the code to # make them pass. Then move on to the other two methods, but this time you'll # create the descriptions to match the requirements above. class Person def initialize(first_name:, middle_name: nil, last_name:) @first_name = first_name @middle_name = middle_name @last_name = last_name end # implement your behavior here end RSpec.describe Person do describe "#full_name" do it "concatenates first name, middle name, and last name with spaces" it "does not add extra spaces if middle name is missing" end describe "#full_name_with_middle_initial" describe "#initials" end | https://thoughtbot.com/upcase/videos/red-green-refactor-by-example | CC-MAIN-2020-40 | refinedweb | 887 | 64.61 |
DEBSOURCES
Skip Quicknav
sources / snappy / 1.1.3-3 / framing_format
Snappy framing format description
Last revised: 2013-10-25
This format decribes a framing format for Snappy, allowing compressing to
files or streams that can then more easily be decompressed without having
to hold the entire stream in memory. It also provides data checksums to
help verify integrity. It does not provide metadata checksums, so it does
not protect against e.g. all forms of truncations.
Implementation of the framing format is optional for Snappy compressors and
decompressor; it is not part of the Snappy core specification.
1. General structure
The file consists solely of chunks, lying back-to-back with no padding
in between. Each chunk consists first a single byte of chunk identifier,
then a three-byte little-endian length of the chunk in bytes (from 0 to
16777215, inclusive), and then the data if any. The four bytes of chunk
header is not counted in the data length.
The different chunk types are listed below. The first chunk must always
be the stream identifier chunk (see section 4.1, below). The stream
ends when the file ends -- there is no explicit end-of-file marker.
2. File type identification
The following identifiers for this format are recommended where appropriate.
However, note that none have been registered officially, so this is only to
be taken as a guideline. We use "Snappy framed" to distinguish between this
format and raw Snappy data.
File extension: .sz
MIME type: application/x-snappy-framed
HTTP Content-Encoding: x-snappy-framed
3. Checksum format
Some chunks have data protected by a checksum (the ones that do will say so
explicitly). The checksums are always masked CRC-32Cs.
A description of CRC-32C can be found in RFC 3720, section 12.1, with
examples in section B.4.
Checksums are not stored directly, but masked, as checksumming data and
then its own checksum can be problematic. The masking is the same as used
in Apache Hadoop: Rotate the checksum by 15 bits, then add the constant
0xa282ead8 (using wraparound as normal for unsigned integers). This is
equivalent to the following C code:
uint32_t mask_checksum(uint32_t x) {
return ((x >> 15) | (x << 17)) + 0xa282ead8;
}
Note that the masking is reversible.
The checksum is always stored as a four bytes long integer, in little-endian.
4. Chunk types
The currently supported chunk types are described below. The list may
be extended in the future.
4.1. Stream identifier (chunk type 0xff)
The stream identifier is always the first element in the stream.
It is exactly six bytes long and contains "sNaPpY" in ASCII. This means that
a valid Snappy framed stream always starts with the bytes
0xff 0x06 0x00 0x00 0x73 0x4e 0x61 0x50 0x70 0x59
The stream identifier chunk can come multiple times in the stream besides
the first; if such a chunk shows up, it should simply be ignored, assuming
it has the right length and contents. This allows for easy concatenation of
compressed files without the need for re-framing.
4.2. Compressed data (chunk type 0x00)
Compressed data chunks contain a normal Snappy compressed bitstream;
see the compressed format specification. The compressed data is preceded by
the CRC-32C (see section 3) of the _uncompressed_ data.
Note that the data portion of the chunk, i.e., the compressed contents,
can be at most 16777211 bytes (2^24 - 1, minus the checksum).
However, we place an additional restriction that the uncompressed data
in a chunk must be no longer than 65536 bytes. This allows consumers to
easily use small fixed-size buffers.
4.3. Uncompressed data (chunk type 0x01)
Uncompressed data chunks allow a compressor to send uncompressed,
raw data; this is useful if, for instance, uncompressible or
near-incompressible data is detected, and faster decompression is desired.
As in the compressed chunks, the data is preceded by its own masked
CRC-32C (see section 3).
An uncompressed data chunk, like compressed data chunks, should contain
no more than 65536 data bytes, so the maximum legal chunk length with the
checksum is 65540.
4.4. Padding (chunk type 0xfe)
Padding chunks allow a compressor to increase the size of the data stream
so that it complies with external demands, e.g. that the total number of
bytes is a multiple of some value.
All bytes of the padding chunk, except the chunk byte itself and the length,
should be zero, but decompressors must not try to interpret or verify the
padding data in any way.
4.5. Reserved unskippable chunks (chunk types 0x02-0x7f)
These are reserved for future expansion. A decoder that sees such a chunk
should immediately return an error, as it must assume it cannot decode the
stream correctly.
Future versions of this specification may define meanings for these chunks.
4.6. Reserved skippable chunks (chunk types 0x80-0xfd)
These are also reserved for future expansion, but unlike the chunks
described in 4.5, a decoder seeing these must skip them and continue
decoding.
Future versions of this specification may define meanings for these chunks. | https://sources.debian.org/src/snappy/1.1.3-3/framing_format.txt/ | CC-MAIN-2021-39 | refinedweb | 844 | 62.98 |
Table of Contents
Web clients and servers often pass information around as a simple textual list of key-value pairs.
name=Attila+%42The+Hun%42&occupation=Khan
The encoding is named
application/x-www-form-urlencoded, and it's easy to
understand. Each key-value pair is separated by an
“
&” character. Within a pair, a
key is a series of characters, followed by an
“
=”, followed by a value.
We can obviously represent a key as a String,
but the HTTP specification is not clear about whether a key must
be followed by a value. We can capture this ambiguity by
representing a value as a Maybe String. If we use
Nothing for a value, then there was no value
present. If we wrap a string in
Just, then there
was a value. Using Maybe lets us distinguish
between “no value” and “empty
value”.
Haskell programmers use the name association list for the type [(a, b)], where we can think of each element as an association between a key and a value. The name originates in the Lisp community, where it's usually abbreviated as an alist. We could thus represent the above string as the following Haskell value.
-- file: ch15/MovieReview.hs [("name", Just "Attila \"The Hun\""), ("occupation", Just "Khan")]
In the section called “Parsing an URL-encoded query string”, we'll parse an
application/x-www-form-urlencoded string, and
represent the result as an alist of [(String, Maybe
String)]. Let's say we want to use one of these alists
to fill out a data structure.
-- file: ch15/MovieReview.hs data MovieReview = MovieReview { revTitle :: String , revUser :: String , revReview :: String }
We'll begin by belabouring the obvious with a naive function.
-- file: ch15/MovieReview.hs simpleReview :: [(String, Maybe String)] -> Maybe MovieReview simpleReview alist = case lookup "title" alist of Just (Just title@(_:_)) -> case lookup "user" alist of Just (Just user@(_:_)) -> case lookup "review" alist of Just (Just review@(_:_)) -> Just (MovieReview title user review) _ -> Nothing -- no review _ -> Nothing -- no user _ -> Nothing -- no title
It only returns a MovieReview if the alist contains all of the necessary values, and they're all non-empty strings. However, the fact that it validates its inputs is its only merit: it suffers badly from the “staircasing” that we've learned to be wary of, and it knows the intimate details of the representation of an alist.
Since we're now well acquainted with the Maybe monad, we can tidy up the staircasing.
-- file: ch15/MovieReview.hs maybeReview alist = do title <- lookup1 "title" alist user <- lookup1 "user" alist review <- lookup1 "review" alist return (MovieReview title user review) lookup1 key alist = case lookup key alist of Just (Just s@(_:_)) -> Just s _ -> Nothing
Although this is much tidier, we're still repeating
ourselves. We can take advantage of the fact that the
MovieReview constructor acts as a normal, pure
function by lifting it into the monad, as
we discussed in the section called “Mixing pure and monadic code”.
-- file: ch15/MovieReview.hs liftedReview alist = liftM3 MovieReview (lookup1 "title" alist) (lookup1 "user" alist) (lookup1 "review" alist)
We still have some repetition here, but it is dramatically reduced, and also more difficult to remove.
Although using
liftM3 tidies up our
code, we can't use a
liftM-family function
to solve this sort of problem in general, because they're only
defined up to
liftM5 by the standard
libraries. We could write variants up to whatever number we
pleased, but that would amount to drudgery.
If we had a constructor or pure function that took, say, ten parameters, and decided to stick with the standard libraries you might think we'd be out of luck.
Of course, our toolbox isn't yet empty. In
Control.Monad, there's a function named
ap with an interesting type
signature.
ghci>
:m +Control.Monad
ghci>
:type apap :: (Monad m) => m (a -> b) -> m a -> m b
You might wonder who would put a single-argument pure
function inside a monad, and why. Recall, however, that
all Haskell functions really take only one
argument, and you'll begin to see how this might relate to the
MovieReview constructor.
ghci>
:type MovieReviewMovieReview :: String -> String -> String -> MovieReview
We can just as easily write that type as String ->
(String -> (String -> MovieReview)). If we use
plain old
liftM to lift
MovieReview into the
Maybe monad,
we'll have a value of type Maybe (String -> (String
-> (String -> MovieReview))). We can now see
that this type is suitable as an argument for
ap, in which case the result type will be
Maybe (String -> (String -> MovieReview)). We
can pass this, in turn, to
ap, and continue
to chain until we end up with this definition.
-- file: ch15/MovieReview.hs apReview alist = MovieReview `liftM` lookup1 "title" alist `ap` lookup1 "user" alist `ap` lookup1 "review" alist
We can chain applications of
ap like this as many times as we need to,
thereby bypassing the
liftM family of
functions.
Another helpful way to look at
ap is that it's the monadic equivalent of
the familiar
($) operator: think of
pronouncing
ap as
apply. We can see this clearly when we
compare the type signatures of the two functions.
ghci>
:type ($)($) :: (a -> b) -> a -> b
ghci>
:type apap :: (Monad m) => m (a -> b) -> m a -> m b
In fact,
ap is usually defined as
either
liftM2 id or
liftM2 ($).
Here's a simple representation of a person's phone numbers.
-- file: ch15/VCard.hs data Context = Home | Mobile | Business deriving (Eq, Show) type Phone = String albulena = [(Home, "+355-652-55512")] nils = [(Mobile, "+47-922-55-512"), (Business, "+47-922-12-121"), (Home, "+47-925-55-121"), (Business, "+47-922-25-551")] twalumba = [(Business, "+260-02-55-5121")]
Suppose we want to get in touch with someone to make a personal call. We don't want their business number, and we'd prefer to use their home number (if they have one) instead of their mobile number.
-- file: ch15/VCard.hs onePersonalPhone :: [(Context, Phone)] -> Maybe Phone onePersonalPhone ps = case lookup Home ps of Nothing -> lookup Mobile ps Just n -> Just n
Of course, if we use Maybe as the result type, we can't accommodate the possibility that someone might have more than one number that meet our criteria. For that, we switch to a list.
-- file: ch15/VCard.hs allBusinessPhones :: [(Context, Phone)] -> [Phone] allBusinessPhones ps = map snd numbers where numbers = case filter (contextIs Business) ps of [] -> filter (contextIs Mobile) ps ns -> ns contextIs a (b, _) = a == b
Notice that these two functions structure their
case
expressions similarly: one alternative handles the case where
the first lookup returns an empty result, while the other
handles the non-empty case.
ghci>
onePersonalPhone twalumbaNothing
ghci>
onePersonalPhone albulenaJust "+355-652-55512"
ghci>
allBusinessPhones nils["+47-922-12-121","+47-922-25-551"]
Haskell's
Control.Monad module defines a
typeclass, MonadPlus, that lets us abstract the
common pattern out of our
case expressions.
-- file: ch15/VCard.hs class Monad m => MonadPlus m where mzero :: m a mplus :: m a -> m a -> m a
The value
mzero represents an empty result,
while
mplus combines two results into one.
Here are the standard definitions of
mzero and
mplus for Maybe and
lists.
-- file: ch15/VCard.hs instance MonadPlus [] where mzero = [] mplus = (++) instance MonadPlus Maybe where mzero = Nothing Nothing `mplus` ys = ys xs `mplus` _ = xs
We can now use
mplus to get
rid of our
case expressions entirely. For variety, let's
fetch one business and all personal phone numbers.
-- file: ch15/VCard.hs oneBusinessPhone :: [(Context, Phone)] -> Maybe Phone oneBusinessPhone ps = lookup Business ps `mplus` lookup Mobile ps allPersonalPhones :: [(Context, Phone)] -> [Phone] allPersonalPhones ps = map snd $ filter (contextIs Home) ps `mplus` filter (contextIs Mobile) ps
In these functions, because we know that
lookup returns a value of type
Maybe, and
filter returns a
list, it's obvious which version of
mplus
is going to be used in each case.
What's more interesting is that we can use
mzero and
mplus to write
functions that will be useful for any
MonadPlus instance. As an example, here's the
standard
lookup function, which returns a
value of type Maybe.
-- file: ch15/VCard.hs lookup :: (Eq a) => a -> [(a, b)] -> Maybe b lookup _ [] = Nothing lookup k ((x,y):xys) | x == k = Just y | otherwise = lookup k xys
We can easily generalise the result type to any instance of MonadPlus as follows.
-- file: ch15/VCard.hs lookupM :: (MonadPlus m, Eq a) => a -> [(a, b)] -> m b lookupM _ [] = mzero lookupM k ((x,y):xys) | x == k = return y `mplus` lookupM k xys | otherwise = lookupM k xys
This lets us get either no result or one, if our result type is Maybe; all results, if our result type is a list; or something more appropriate for some other exotic instance of MonadPlus.
For small functions, such as those we present above, there's
little benefit to using
mplus. The
advantage lies in more complex code and in code that is
independent of the monad in which it executes. Even if you
don't find yourself needing MonadPlus for your own
code, you are likely to encounter it in other people's
projects.
Even though the
mplus function
contains the text “plus”, you should not think of
it as necessarily implying that we're trying to add two
values.
Depending on the monad we're working in,
mplus may implement an
operation that looks like addition. For example,
mplus in the list monad is implemented as
the
(++) operator.
ghci>
[1,2,3] `mplus` [4,5,6][1,2,3,4,5,6]
However, if we switch to another monad, the obvious similarity to addition falls away.
ghci>
Just 1 `mplus` Just 2Just 1
Instances of the MonadPlus typeclass must follow a few simple rules, in addition to the usual monad rules.
An instance must short circuit if
mzero appears on the left of a bind expression.
In other words, an expression
mzero >>= f
must evaluate to the same result as
mzero
alone.
-- file: ch15/MonadPlus.hs mzero >>= f == mzero
An instance must short circuit if
mzero
appears on the right of a sequence
expression.
-- file: ch15/MonadPlus.hs v >> mzero == mzero
When we introduced the
fail function in the section called “The Monad typeclass”, we took pains to warn against its
use: in many monads, it's implemented as a call to
error,
which has unpleasant consequences.
The MonadPlus typeclass gives us a gentler
way to fail a computation, without
fail or
error blowing
up in our faces. The rules that we introduced above allow us
to introduce an
mzero into our code wherever we
need to, and computation will short circuit at that
point.
In the
Control.Monad module, the standard
function
guard packages up this idea in a
convenient form.
-- file: ch15/MonadPlus.hs guard :: (MonadPlus m) => Bool -> m () guard True = return () guard False = mzero
As a simple example, here's a function that takes a number
x and computes its value modulo some other
number
n. If the result is zero, it
returns
x, otherwise the current monad's
mzero.
-- file: ch15/MonadPlus.hs x `zeroMod` n = guard ((x `mod` n) == 0) >> return x
In the section called “Using the state monad: generating random values”, we showed how to use the State monad to give ourselves access to random numbers in a way that is easy to use.
A drawback of the code we developed is that it's leaky: someone who uses it knows that they're executing inside the State monad. This means that they can inspect and modify the state of the random number generator just as easily as we, the authors, can.
Human nature dictates that if we leave our internal workings exposed, someone will surely come along and monkey with them. For a sufficiently small program, this may be fine, but in a larger software project, when one consumer of a library modifies its internals in a way that other consumers are not prepared for, the resulting bugs can be among the hardest of all to track down. These bugs occur at a level where we're unlikely to question our basic assumptions about a library until long after we've exhausted all other avenues of inquiry.
Even worse, once we leave our implementation exposed for a while, and some well-intentioned person inevitably bypasses our APIs and uses the implementation directly, we create a nasty quandary for ourselves if we need to fix a bug or make an enhancement. Either we can modify our internals, and break code that depends on them; or we're stuck with our existing internals, and must try to find some other way to make the change we need.
How can we revise our random number monad so that the fact
that we're using the State monad is hidden? We
need to somehow prevent our users from being able to call
get or
put. This is not difficult to
do, and it introduces some tricks that we'll reuse often in
day-to-day Haskell programming.
To widen our scope, we'll move beyond random numbers, and
implement a monad that supplies unique values of
any kind. The name we'll give to our monad
is Supply. We'll provide the execution function,
runSupply, with a list of values; it will
be up to us to ensure that each one is unique.
-- file: ch15/Supply.hs runSupply :: Supply s a -> [s] -> (a, [s])
The monad won't care what the values are: they might be random numbers, or names for temporary files, or identifiers for HTTP cookies.
Within the monad, every time a consumer asks for a value,
the
next action will take the next one from
the list and give it to the consumer. Each value is wrapped in
a Maybe constructor in case the list isn't long
enough to satisfy the demand.
-- file: ch15/Supply.hs next :: Supply s (Maybe s)
To hide our plumbing, in our module declaration we only
export the type constructor, the execution function, and the
next action.
-- file: ch15/Supply.hs module Supply ( Supply , next , runSupply ) where
Since a module that imports the library can't see the internals of the monad, it can't manipulate them.
Our plumbing is exceedingly simple: we use a
newtype
declaration to wrap the existing State
monad.
-- file: ch15/Supply.hs import Control.Monad.State newtype Supply s a = S (State [s] a)
The
s parameter is the type
of the unique values we are going to supply, and
a is the usual type parameter that
we must provide in order to make our type a monad.
Our use of
newtype for the Supply
type and our module header join forces to prevent our clients
from using the State monad's
get and
set actions.
Because our module does not export the
S data
constructor, clients have no programmatic way to see that we're
wrapping the State monad, or to access it.
At this point, we've got a type, Supply, that
we need to make an instance of the Monad type
class. We could follow the usual pattern of defining
(>>=) and
return, but this would be pure boilerplate code. All we'd be
doing is wrapping and unwrapping the State monad's
versions of
(>>=) and
return using our
S value
constructor. Here is how such code would look.
-- file: ch15/AltSupply.hs unwrapS :: Supply s a -> State [s] a unwrapS (S s) = s instance Monad (Supply s) where s >>= m = S (unwrapS s >>= unwrapS . m) return = S . return
Haskell programmers are not fond of boilerplate, and sure enough, GHC has a lovely language extension that eliminates the work. To use it, we add the following directive to the top of our source file, before the module header.
-- file: ch15/Supply.hs {-# LANGUAGE GeneralizedNewtypeDeriving #-}
Usually, we can only automatically derive instances of a
handful of standard typeclasses, such as Show and
Eq. As its name suggests, the
GeneralizedNewtypeDeriving extension broadens our
ability to derive typeclass instances, and it is specific to
newtype declarations. If the type we're wrapping is an
instance of any typeclass, the extensions can
automatically make our new type an instance of that typeclass
as follows.
-- file: ch15/Supply.hs deriving (Monad)
This takes the underlying type's implementations of
(>>=)
and
return, adds the necessary wrapping and unwrapping with
our
S data constructor, and uses the new versions
of those functions to derive a Monad instance for
us.
What we gain here is very useful beyond just this example.
We can use
newtype to wrap any underlying type; we selectively
expose only those typeclass instances that we want; and we
expend almost no effort to create these narrower, more
specialised types.
Now that we've seen the
GeneralizedNewtypeDeriving technique, all that
remains is to provide definitions of
and
runSupply.
-- file: ch15/Supply.hs next = S $ do st <- get case st of [] -> return Nothing (x:xs) -> do put xs return (Just x) runSupply (S m) xs = runState m xs
If we load our module into ghci, we can try it out in a few simple ways.
ghci>
:load Supply[1 of 1] Compiling Supply ( Supply.hs, interpreted ) Ok, modules loaded: Supply.
ghci>
runSupply next [1,2,3]Loading package mtl-1.1.0.0 ... linking ... done. (Just 1,[2,3])
ghci>
runSupply (liftM2 (,) next next) [1,2,3]((Just 1,Just 2),[3])
ghci>
runSupply (liftM2 (,) next next) [1]((Just 1,Nothing),[])
We can also verify that the State monad has not somehow leaked out.
ghci>
:browse Supplydata Supply s a next :: Supply s (Maybe s) runSupply :: Supply s a -> [s] -> (a, [s])
ghci>
:info Supplydata Supply s a -- Defined at Supply.hs:17:8-13 instance Monad (Supply s) -- Defined at Supply.hs:17:8-13
If we want to use our Supply monad as a source of random numbers, we have a small difficulty to face. Ideally, we'd like to be able to provide it with an infinite stream of random numbers. We can get a StdGen in the IO monad, but we must “put back” a different StdGen when we're done. If we don't, the next piece of code to get a StdGen will get the same state as we did. This means it will generate the same random numbers as we did, which is potentially catastrophic.
From the parts of the
System.Random
module we've seen so far, it's difficult to reconcile these
demands. We can use
getStdRandom, whose
type ensures that when we get a StdGen, we put
one back.
ghci>
:type getStdRandomgetStdRandom :: (StdGen -> (a, StdGen)) -> IO a
We can use
random to get back a new
StdGen when they give us a random number. And we
can use
randoms to get an infinite list
of random numbers. But how do we get both an infinite list of
random numbers and a new
StdGen?
The answer lies with the RandomGen type
class's
split function, which takes one
random number generator, and turns it into two generators.
Splitting a random generator like this is a most unusual thing
to be able to do: it's obviously tremendously useful in a pure
functional setting, but essentially never either necessary or
provided by an impure language.
Using the
split function, we can use
one StdGen to generate an infinite list of random
numbers to feed to
runSupply, while we
give the other back to the IO monad.
-- file: ch15/RandomSupply.hs import Supply import System.Random hiding (next) randomsIO :: Random a => IO [a] randomsIO = getStdRandom $ \g -> let (a, b) = split g in (randoms a, b)
If we've written this function properly, our example ought to print a different random number on each invocation.
ghci>
:load RandomSupply[1 of 2] Compiling Supply ( Supply.hs, interpreted ) [2 of 2] Compiling RandomSupply ( RandomSupply.hs, interpreted ) Ok, modules loaded: RandomSupply, Supply.
Recall that our
runSupply function
returns both the result of executing the monadic action and
the unconsumed remainder of the list. Since we passed it an
infinite list of random numbers, we compose with
fst to ensure that we don't get drowned
in random numbers when ghci tries to print the
result.
The pattern of applying a function to one element of a pair, and constructing a new pair with the other original element untouched, is common enough in Haskell code that it has been turned into standard code.
In the
Control.Arrow module are two
functions,
first and
second, that perform this
operation.
ghci>
:m +Control.Arrow
ghci>
first (+3) (1,2)(4,2)
ghci>
second odd ('a',1)('a',True)
(Indeed, we already encountered
second, in the section called “JSON typeclasses without overlapping instances”.) We can use
first to golf our definition of
randomsIO, turning it into a
one-liner.
-- file: ch15/RandomGolf.hs import Control.Arrow (first) randomsIO_golfed :: Random a => IO [a] randomsIO_golfed = getStdRandom (first randoms . split)
In the previous section, we saw how to hide the fact that we're using a State monad to hold the state for our Supply monad.
Another important way to make code more modular involves separating its interface—what the code can do—from its implementation—how it does it.
The standard random number generator in
System.Random is known to be quite slow. If we use
our
randomsIO function to provide it with
random numbers, then our
next action will
not perform well.
One simple and effective way that we could deal with this is to provide Supply with a better source of random numbers. Let's set this idea aside, though, and consider an alternative approach, one that is useful in many settings. We will separate the actions we can perform with the monad from how it works using a typeclass.
-- file: ch15/SupplyClass.hs class (Monad m) => MonadSupply s m | m -> s where next :: m (Maybe s)
This typeclass defines the interface that any supply monad must implement. It bears careful inspection, since it uses several unfamiliar Haskell language extensions. We will cover each one in the sections that follow.
How should we read the snippet
MonadSupply s
m in the typeclass? If we add parentheses, an
equivalent expression is
(MonadSupply s) m, which
is a little clearer. In other words, given some type variable
m that is a Monad, we can make
it an instance of the typeclass MonadSupply s.
unlike a regular typeclass, this one has a
parameter.
As this language extension allows a typeclass to
have more than one parameter, its name is
MultiParamTypeClasses. The parameter
s serves the same purpose as the
Supply type's parameter of the same name: it
represents the type of the values handed out by the
next function.
Notice that we don't need to mention
(>>=) or
return in the definition of MonadSupply s,
since the type class's context (superclass) requires that a
MonadSupply s must already be a
Monad.
To revisit a snippet that we ignored earlier,
| m
-> s is a functional
dependency, often called a
fundep. We can read the vertical bar
| as “such that”, and the arrow
-> as “uniquely determines”. Our
functional dependency establishes a
relationship between
m
and
s.
The availability of functional dependencies is governed by
the
FunctionalDependencies language pragma.
The purpose behind us declaring a relationship is to help the type checker. Recall that a Haskell type checker is essentially a theorem prover, and that it is conservative in how it operates: it insists that its proofs must terminate. A non-terminating proof results in the compiler either giving up or getting stuck in an infinite loop.
With our functional dependency, we are telling the type
checker that every time it sees some monad
m being used in the context of a
MonadSupply s, the type
s is
the only acceptable type to use with it. If we were to omit
the functional dependency, the type checker would simply give
up with an error message.
It's hard to picture what the relationship between
m and
s really means, so
let's look at an instance of this typeclass.
-- file: ch15/SupplyClass.hs import qualified Supply as S instance MonadSupply s (S.Supply s) where next = S.next
Here, the type variable
m is replaced
by the type S.Supply s. Thanks to our functional
dependency, the type checker now knows that when it sees a
type S.Supply s, the type can be used as an
instance of the typeclass MonadSupply s.
If we didn't have a functional dependency, the type checker would not be able to figure out the relationship between the type parameter of the class MonadSupply s and that of the type Supply s, and it would abort compilation with an error. The definition itself would compile; the type error would not arise until the first time we tried to use it.
To strip away one final layer of abstraction, consider the
type S.Supply Int. Without a functional
dependency, we could declare this an instance of
MonadSupply s. However, if we tried to write
code using this instance, the compiler would not be able to
figure out that the type's Int parameter needs to
be the same as the typeclass's
s
parameter, and it would report an error.
Functional dependencies can be tricky to understand, and once we move beyond simple uses, they often prove difficult to work with in practice. Fortunately, the most frequent use of functional dependencies is in situations as simple as ours, where they cause little trouble.
If we save our typeclass and instance in a source file
named
SupplyClass.hs, we'll need to add
a module header such as the following.
-- file: ch15/SupplyClass.hs {-# LANGUAGE FlexibleInstances, FunctionalDependencies, MultiParamTypeClasses #-} module SupplyClass ( MonadSupply(..) , S.Supply , S.runSupply ) where
The
FlexibleInstances extension is necessary
so that the compiler will accept our instance declaration.
This extension relaxes the normal rules for writing instances
in some circumstances, in a way that still lets the compiler's
type checker guarantee that it will terminate. Our need for
FlexibleInstances here is caused by our use of
functional dependencies, but the details are unfortunately
beyond the scope of this book.
Finally, notice that we're re-exporting the
runSupply and Supply names
from this module. It's perfectly legal to export a name from
one module even though it's defined in another. In our case,
it means that client code only needs to import the
SupplyClass module, without also importing the
Supply module. This reduces the number of
“moving parts” that a user of our code needs to
keep in mind.
Here is a simple function that fetches two values from our Supply monad, formats them as a string, and returns them.
-- file: ch15/Supply.hs showTwo :: (Show s) => Supply s String showTwo = do a <- next b <- next return (show "a: " ++ show a ++ ", b: " ++ show b)
This code is tied by its result type to our Supply monad. We can easily generalize to any monad that implements our MonadSupply interface by modifying our function's type. Notice that the body of the function remains unchanged.
-- file: ch15/SupplyClass.hs showTwo_class :: (Show s, Monad m, MonadSupply s m) => m String showTwo_class = do a <- next b <- next return (show "a: " ++ show a ++ ", b: " ++ show b)
The State monad lets us plumb a piece of mutable state through our code. Sometimes, we would like to be able to pass some immutable state around, such as a program's configuration data. We could use the State monad for this purpose, but we could then find ourselves accidentally modifying data that should remain unchanged.
Let's forget about monads for a moment and think about what
a function with our desired characteristics
ought to do. It should accept a value of some type
e (for environment)
that represents the data
that we're passing in, and return a value of some
other type
a as its result. The
overall type we want is e -> a.
To turn this type into a convenient Monad
instance, we'll wrap it in a
newtype.
-- file: ch15/SupplyInstance.hs newtype Reader e a = R { runReader :: e -> a }
Making this into a Monad instance doesn't take much work.
-- file: ch15/SupplyInstance.hs instance Monad (Reader e) where return a = R $ \_ -> a m >>= k = R $ \r -> runReader (k (runReader m r)) r
We can think of our value of type
e as an environment
in which we're evaluating some expression. The
return action
should have the same effect no matter what the environment is,
so our version ignores its environment.
Our definition of
(>>=) is a little more complicated, but
only because we have to make the environment—here the
variable
r—available both in the
current computation and in the computation we're chaining
into.
How does a piece of code executing in this monad find out
what's in its environment? It simply has to
ask.
-- file: ch15/SupplyInstance.hs ask :: Reader e e ask = R id
Within a given chain of actions, every invocation of
ask will return the same value, since the
value stored in the environment doesn't change. Our code
is easy to test in ghci.
ghci>
runReader (ask >>= \x -> return (x * 3)) 2Loading package old-locale-1.0.0.0 ... linking ... done. Loading package old-time-1.0.0.0 ... linking ... done. Loading package random-1.0.0.0 ... linking ... done. 6
The Reader monad is included in the standard
mtl library, which is usually bundled with GHC.
You can find it in the
Control.Monad.Reader module.
The motivation for this monad may initially seem a little thin,
because it is most often useful in complicated code. We'll
often need to access a piece of configuration information
deep in the bowels of a program; passing that information in as
a normal parameter would require a painful restructuring of our
code. By hiding this information in our monad's plumbing,
intermediate functions that don't care about the configuration
information don't need to see it.
The clearest motivation for the Reader monad will come in Chapter 18, Monad transformers, when we discuss combining several monads to build a new monad. There, we'll see how to gain finer control over state, so that our code can modify some values via the State monad, while other values remain immutable, courtesy of the Reader monad.
Now that we know about the Reader
monad, let's use it to create an instance of our
MonadSupply typeclass. To keep our example simple,
we'll violate the spirit of MonadSupply here: our
next action will always return the same
value, instead of always returning a different value.
It would be a bad idea to directly make the Reader type an instance of the MonadSupply class, because then any Reader could act as a MonadSupply. This would usually not make any sense.
Instead, we create a
newtype based on
Reader. The
newtype hides the fact that we're
using Reader internally. We must now make our type
an instance of both of the typeclasses we care about. With the
GeneralizedNewtypeDeriving extension enabled, GHC
will do most of the hard work for us.
-- file: ch15/SupplyInstance.hs newtype MySupply e a = MySupply { runMySupply :: Reader e a } deriving (Monad) instance MonadSupply e (MySupply e) where next = MySupply $ do v <- ask return (Just v) -- more concise: -- next = MySupply (Just `liftM` ask)
Notice that we must make our type an instance of MonadSupply e, not MonadSupply. If we omit the type variable, the compiler will complain.
To try out our MySupply type, we'll first create a simple function that should work with any MonadSupply instance.
-- file: ch15/SupplyInstance.hs xy :: (Num s, MonadSupply s m) => m s xy = do Just x <- next Just y <- next return (x * y)
If we use this with our Supply monad and
randomsIO function, we get a different
answer every time, as we expect.
ghci>
(fst . runSupply xy) `fmap` randomsIO-15697064270863081825448476392841917578
ghci>
(fst . runSupply xy) `fmap` randomsIO17182983444616834494257398042360119726
Because our MySupply monad has two layers of
newtype wrapping, we can make it easier to use by writing a
custom execution function for it.
-- file: ch15/SupplyInstance.hs runMS :: MySupply i a -> i -> a runMS = runReader . runMySupply
When we apply our
xy action
using this execution function, we get the same answer every
time. Our code remains the same, but because we are executing
it in a different implementation of MonadSupply,
its behavior has changed.
ghci>
runMS xy 24
ghci>
runMS xy 24
Like our MonadSupply typeclass and
Supply monad, almost all of the common Haskell
monads are built with a split between interface and
implementation. For example, the
get and
put functions that we introduced as
“belonging to” the State monad are
actually methods of the MonadState typeclass; the
State type is an instance of this class.
Similarly, the standard Reader monad is an
instance of the MonadReader typeclass, which
specifies the
ask method.
While the separation of interface and implementation that
we've discussed above is appealing for its architectural
cleanliness, it has important practical applications that will
become clearer later. When we start combining monads in Chapter 18, Monad transformers, we will save a lot of effort through the use of
GeneralizedNewtypeDeriving and typeclasses.
The blessing and curse of the IO monad is that it is extremely powerful. If we believe that careful use of types helps us to avoid programming mistakes, then the IO monad should be a great source of unease. Because the IO monad imposes no restrictions on what we can do, it leaves us vulnerable to all kinds of accidents.
How can we tame its power? Let's say that we would like to guarantee to ourselves that a piece of code can read and write files on the local filesystem, but we want our monad to allow. This is a simple matter of wrapping each IO with a HandleIO data constructor.
-- file: ch15/HandleIO.hs openFile :: FilePath -> IOMode -> HandleIO Handle openFile path mode = HandleIO (System.IO.openFile path mode) hClose :: Handle -> HandleIO () hClose = HandleIO . System.IO.hClose hPutStrLn :: Handle -> String -> HandleIO () hPutStrLn h s = HandleIO (System.IO.hPutStrLn h s)
We can now use our restricted HandleIO monad to perform I/O.
-- file: ch15/HandleIO.hs safeHello :: FilePath -> HandleIO () safeHello path = do h <- openFile path WriteMode hPutStrLn h "hello world" hClose h
To run this action, we use
runHandleIO.
ghci>
:load HandleIO[1 of 1] Compiling HandleIO ( HandleIO.hs, interpreted ) Ok, modules loaded: HandleIO.
ghci>
runHandleIO (safeHello "hello_world_101.txt">
:m +System.Directory
ghci>
removeFile "hello_world_101.txt"
If we try to sequence an action that runs in the HandleIO monad with one that is not permitted, the type system forbids it.
ghci>
runHandleIO (safeHello "goodbye" >> removeFile "goodbye")<interactive>:1:36: Couldn't match expected type `HandleIO a' against inferred type `IO ()' In the second argument of `(>>)', namely `removeFile "goodbye"' In the first argument of `runHandleIO', namely `(safeHello "goodbye" >> removeFile "goodbye")' In the expression: runHandleIO (safeHello "goodbye" >> removeFile "goodbye")
There's one small, but significant, problem with our HandleIO monad: it doesn't take into account the possibility that we might occasionally need an escape hatch. If we define a monad like this, it is likely that we will occasionally need to perform an I/O action that isn't allowed for by the design of our monad.
Our purpose in defining a monad like this is to make it easier for us to write solid code in the common case, not to make corner cases impossible. Let's thus give ourselves a way out.
The
Control.Monad.Trans module defines a
“standard escape hatch”, the MonadIO
typeclass. This defines a single function,
liftIO, which lets us embed an
IO action in another monad.
ghci>
:m +Control.Monad.Trans
ghci>
:info MonadIOclass (Monad m) => MonadIO m where liftIO :: IO a -> m a -- Defined in Control.Monad.Trans instance MonadIO IO -- Defined in Control.Monad.Trans
Our implementation of this typeclass is trivial: we just wrap IO with our data constructor.
-- file: ch15/HandleIO.hs import Control.Monad.Trans (MonadIO(..)) instance MonadIO HandleIO where liftIO = HandleIO
With judicious use of
liftIO, we can
escape our shackles and invoke IO actions where
necessary.
-- file: ch15/HandleIO.hs tidyHello :: FilePath -> HandleIO () tidyHello path = do safeHello path liftIO (removeFile path)
The disadvantage of hiding IO in another monad is that we're still tied to a concrete implementation. If we want to swap HandleIO for some other monad, we must change the type of every action that uses HandleIO.
As an alternative, we can create a typeclass that specifies the interface we want from a monad that manipulates files.
-- file: ch15/MonadHandle.hs {-# LANGUAGE FunctionalDependencies, MultiParamTypeClasses #-} module MonadHandle (MonadHandle(..)) where import System.IO (IOMode(..)) class Monad m => MonadHandle h m | m -> h where openFile :: FilePath -> IOMode -> m h hPutStr :: h -> String -> m () hClose :: h -> m () hGetContents :: h -> m String hPutStrLn :: h -> String -> m () hPutStrLn h s = hPutStr h s >> hPutStr h "\n"
Here, we've chosen to abstract away both the type of the monad and the type of a file handle. To satisfy the type checker, we've added a functional dependency: for any instance of MonadHandle, there is exactly one handle type that we can use. When we make the IO monad an instance of this class, we use a regular Handle.
-- file: ch15/MonadHandleIO.hs {-# LANGUAGE FunctionalDependencies, MultiParamTypeClasses #-} import MonadHandle import qualified System.IO import System.IO (IOMode(..)) import Control.Monad.Trans (MonadIO(..), MonadTrans(..)) import System.Directory (removeFile) import SafeHello instance MonadHandle System.IO.Handle IO where openFile = System.IO.openFile hPutStr = System.IO.hPutStr hClose = System.IO.hClose hGetContents = System.IO.hGetContents hPutStrLn = System.IO.hPutStrLn
Because any MonadHandle must also be a
Monad, we can write code that manipulates files
using normal
do notation, without caring what monad it will
finally execute in.
-- file: ch15/SafeHello.hs safeHello :: MonadHandle h m => FilePath -> m () safeHello path = do h <- openFile path WriteMode hPutStrLn h "hello world" hClose h
Because we made IO an instance of this type class, we can execute this action from ghci.
ghci>
safeHello "hello to my fans in domestic surveillance>
removeFile "hello to my fans in domestic surveillance"
The beauty of the typeclass approach is that we can swap one underlying monad for another without touching much code, as most of our code doesn't know or care about the implementation. For instance, we could replace IO with a monad that compresses files as it writes them out.
Defining a monad's interface through a typeclass has a
further benefit. It lets other people hide our implementation
in a
newtype wrapper, and automatically derive instances of
just the typeclasses they want to expose.
In fact, because our
safeHello
function doesn't use the IO type, we can even use
a monad that can't perform I/O. This
allows us to test code that would normally have side effects
in a completely pure, controlled environment.
To do this, we will create a monad that doesn't perform I/O, but instead logs every file-related event for later processing.
-- file: ch15/WriterIO.hs data Event = Open FilePath IOMode | Put String String | Close String | GetContents String deriving (Show)
Although we already developed a Logger type
in the section called “Using a new monad: show your work!”, here we'll use the
standard, and more general, Writer monad. Like
other
mtl monads, the API provided by
Writer is defined in a typeclass, in this case
MonadWriter. Its most useful method is
tell, which logs a value.
ghci>
:m +Control.Monad.Writer
ghci>
:type telltell :: (MonadWriter w m) => w -> m ()
The values we log can be of any Monoid type. Since the list type is a Monoid, we'll log to a list of Event.
We could make Writer [Event] an instance of MonadHandle, but it's cheap, easy, and safer to make a special-purpose monad.
-- file: ch15/WriterIO.hs newtype WriterIO a = W { runW :: Writer [Event] a } deriving (Monad, MonadWriter [Event])
Our execution function simply removes the
newtype
wrapper we added, then calls the normal Writer
monad's execution function.
-- file: ch15/WriterIO.hs runWriterIO :: WriterIO a -> (a, [Event]) runWriterIO = runWriter . runW
When we try this code out in ghci, it gives us a log of the function's file activities.
ghci>
:load WriterIO[1 of 3] Compiling MonadHandle ( MonadHandle.hs, interpreted ) [2 of 3] Compiling SafeHello ( SafeHello.hs, interpreted ) [3 of 3] Compiling WriterIO ( WriterIO.hs, interpreted ) Ok, modules loaded: SafeHello, MonadHandle, WriterIO.
ghci>
runWriterIO (safeHello "foo")((),[Open "foo" WriteMode,Put "foo" "hello world",Put "foo" "\n",Close "foo"])
The writer monad uses the monoid's
mappend function every time we use
tell. Because
mappend for lists is
(++), lists are not a good practical
choice for use with Writer: repeated appends are
expensive. We use lists above purely for
simplicity.
In production code, if you want to use the
Writer monad and you need list-like behaviour,
use a type with better append characteristics. One such type
is the difference list, which we introduced in the section called “Taking advantage of functions as data”. You don't need to roll your own
difference list implementation: a well tuned library is
available for download from Hackage, the Haskell package
database. Alternatively, you can use the Seq
type from the
Data.Sequence module, which we
introduced in the section called “General purpose sequences”.
If we use the typeclass approach to restricting IO, we may still want to retain the ability to perform arbitrary I/O actions. We might try adding MonadIO as a constraint on our typeclass.
-- file: ch15/MonadHandleIO.hs class (MonadHandle h m, MonadIO m) => MonadHandleIO h m | m -> h instance MonadHandleIO System.IO.Handle IO tidierHello :: (MonadHandleIO h m) => FilePath -> m () tidierHello path = do safeHello path liftIO (removeFile path)
This approach has a problem, though: the added MonadIO constraint loses us the ability to test our code in a pure environment, because we can no longer tell whether a test might have damaging side effects. The alternative is to move this constraint from the typeclass, where it “infects” all functions, to only those functions that really need to perform I/O.
-- file: ch15/MonadHandleIO.hs tidyHello :: (MonadIO m, MonadHandle h m) => FilePath -> m () tidyHello path = do safeHello path liftIO (removeFile path)
We can use pure property tests on the functions that lack MonadIO constraints, and traditional unit tests on the rest.
Unfortunately, we've substituted one problem for another: we can't invoke code with both MonadIO and MonadHandle constraints from code that has the MonadHandle constraint alone. If we find that somewhere deep in our MonadHandle-only code, we really need the MonadIO constraint, we must add it to all the code paths that lead to this point.
Allowing arbitrary I/O is risky, and has a profound effect on how we develop and test our code. When we have to choose between being permissive on the one hand, and easier reasoning and testing on the other, we usually opt for the latter. | http://book.realworldhaskell.org/read/programming-with-monads.html | CC-MAIN-2015-11 | refinedweb | 7,173 | 59.53 |
Homework 11
Due by 11:59pm on Thursday, 11/10:
Homework Questions
Question 1: In Order
Write a function that yields the entries of a valid binary search tree in sorted order.
def in_order(t): """ Yields the entries of a valid binary search tree in sorted order. >>> b = BTree(5, BTree(3, BTree(2), BTree(4)), BTree(6)) >>> list(in_order(b)) [2, 3, 4, 5, 6] >>> list(in_order(bst([1, 3, 5, 7, 9, 11, 13]))) [1, 3, 5, 7, 9, 11, 13] >>> list(in_order(BTree(1))) [1] """ "*** YOUR CODE HERE ***"
Hint: The
yield fromexpression is helpful if you want to yield all the values from another sequence.
Use OK to test your code:
python3 ok -q in_order
Question 2: Generate Permutations
Given a list of unique elements, a permutation of the list is a
reordering of the elements. For example,
[2, 1, 3],
[1, 3, 2], and
[3, 2, 1] are all permutations of the list
[1, 2, 3].
Implement
permutations, a generator function that takes in a
lst and outputs
all permutations of
lst, each as a list (see doctest for an example).
def permutations(lst): """Generates all permutations of sequence LST. Each permutation is a list of the elements in LST in a different order. The order of the permutations does not matter. >>> sorted(permutations([1, 2, 3])) [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] >>> type(permutations([1, 2, 3])) <class 'generator'> >>> sorted(permutations((10, 20, 30))) [[10, 20, 30], [10, 30, 20], [20, 10, 30], [20, 30, 10], [30, 10, 20], [30, 20, 10]] >>> sorted(permutations("ab")) [['a', 'b'], ['b', 'a']] """ if not lst: yield [] return "*** YOUR CODE HERE ***"
The order in which you generate permutations is irrelevant.
Hint: If you had the permutations of
lstminus one element, how could you use that to generate the permutations of the full
lst?
Use OK to test your code:
python3 ok -q permutations
permutationswill be used as part of the AutoStyle study in the next question. Participation in AutoStyle is completely optional; you will receive full credit for this homework by completing questions 1 and 2.
Question 3: Run AutoStyle
This question is optional.
Once you have passed all the tests, invoke AutoStyle by running the command:
python3 ok --style -q permutations
AutoStyle will provide hints to help improve code style and composition. The process will take about 1 hour and must be completed in a single sitting.
When running AutoStyle, please don't place any
If you run into any problems, please make a private post on Piazza tagged
under the folder
autostyle and include a screenshot of the error as well as
a copy of your code. | http://inst.eecs.berkeley.edu/~cs61a/fa16/hw/hw11/ | CC-MAIN-2018-05 | refinedweb | 452 | 54.46 |
#include "ntw.h"
#include "ntw.h"
Go to the source code of this file.
A dialog is a child window, usually used for simple yes/no/cancel user interaction. It can be made modal to force user interaction before the program continues. It can contain a single widget.
Gets dialog's modal status.
Gets dialog's title.
Create dialog widget.
A dialog is usually a modal window that takes the focus from the parent. Use it for simple yes/no/cancel user interaction. The width and height may be specified, but are not guaranteed.
Sets dialog's modal status.
Sets dialog's title. | http://ntw.sourceforge.net/Docs/CServer/dialog_8h.html | CC-MAIN-2018-05 | refinedweb | 103 | 64.17 |
Hema,
here's an example code based on the more modern Apache POI (which - in
contrast to the JXL library - is also able to deal with .xlsx files):
from org.apache.poi.hssf.usermodel import HSSFWorkbook
from java.io import FileInputStream
filename = rc.lookup("qftest", "suite.dir") + "/mytable.xls"
fis = FileInputStream(filename)
workbook = HSSFWorkbook(fis)
fis.close()
sheet = workbook.getSheet("Deal Audit");
TValue = 0
col = ord("R") - ord("A")
for row in range(9, 20 + 1):
cell = sheet.getRow(row - 1).getCell(col)
TValue += cell.getNumericCellValue()
print TValue
Best regards,
Robert
Am 27.07.2015 15:56, schrieb Hema Nagaraj:
Team,
Please help me in writing Jython script to find SUM of range of cells in
Excel
Where testfile is the File name , here I have given dummy path, “Deal
Audit” is the sheet name.
I have worked earlier on excel for verifying cell data, but finding
difficulty in this scenario.
*Scenario: Trying to add a range of rows ranging from R9 to R20 in excel
and store Total in Variable “TValue”*
Below is the script :
from jxl import *
from java.io import File
testFile = "<Path><xls file>"
workbook = Workbook.getWorkbook(File(testFile))
sheet = workbook.getSheet("Deal Audit")
Rvalue = sheet.range(R9:R20)
rc.logMessage(str(RValue), dontcompactify=True, report=True, nowrap=False)
TValue = workbook.worksheetfunction.sum(Rvalue)
rc.logMessage(str(TValue), dontcompactify=True, report=True, nowrap=False)
Thanks,
Hema
_______________________________________________
qftest-list mailing list
qftest-list@?.de
QFS
Support
About QFS
© 2018 QFS GmbH | https://www.qfs.de/en/qf-test-mailing-list-archive-2015/lc/2015-msg00063.html | CC-MAIN-2018-17 | refinedweb | 245 | 52.26 |
If you need a DTD in a hurry, create it from an XML instance using Trang, Relaxer, DTDGenerator, or xmlspy.
Several free Java tools are available that can generate a DTD based on an XML instance or instances. James Clark's Trang () can, among other things, convert an XML document to a DTD, as can Relaxer (). Michael Kay's DTDGenerator (), once part of the Saxon project, consists of a single Java class that is dedicated to XML-to-DTD conversion. This hack walks you through the steps to generate a DTD from a simple instance using each of these tools.
You can download the current Trang JAR (trang.jar) from, then place the JAR in the working directory. The Trang archive comes with a manual (trang-manual.html) that provides details on how to use Trang. I will cover only what is needed to create a DTD in this section. (If you need help with Java, refer to [Hack #10] .)
To create a DTD from time.xml, run this command:
java -jar trang.jar -I xml -O dtd time.xml generated.dtd
The -I switch indicates the type of input (XML), and -O indicates the type of output (DTD). time.xml is the input file and generated.dtd is the output file. You could simplify this command by skipping the -I and -O options, which will produce the same result:
java -jar trang.jar time.xml generated.dtd
The file generated.dtd looks like this:
<?xml encoding="UTF-8"?> <!ELEMENT time (hour,minute,second,meridiem,atomic)> <!ATTLIST time xmlns CDATA #FIXED '' timezone #REQUIRED> <!ELEMENT hour (#PCDATA)> <!ATTLIST hour xmlns CDATA #FIXED ''> <!ELEMENT minute (#PCDATA)> <!ATTLIST minute xmlns CDATA #FIXED ''> <!ELEMENT second (#PCDATA)> <!ATTLIST second xmlns CDATA #FIXED ''> <!ELEMENT meridiem (#PCDATA)> <!ATTLIST meridiem xmlns CDATA #FIXED ''> <!ELEMENT atomic EMPTY> <!ATTLIST atomic xmlns CDATA #FIXED '' signal #REQUIRED>
Trang automatically declares an xmlns attribute for every element in an effort to be namespace-friendly. Trang apparently orders the declarations it outputs according to the order in which they appear in the source.
With Relaxer installed [Hack #37], you can type this command to generate a DTD from time.xml:
relaxer -dir:out -dtd time.xml
Relaxer automatically uses the filename of the input file (time.xml) as the filename for the output file (time.dtd). So to keep from clobbering the existing time.dtd, Relaxer places the output file in the subdirectory out. If the subdirectory does not exist, Relaxer creates it. The result of this command, the file out/time.dtd, is shown here:
<!-- Generated by Relaxer 1.0 --> <!-- Tue Mar 02 17:21:20 MST 2004 --> <!ELEMENT hour (#PCDATA)> <!ELEMENT time (hour, minute, second, meridiem, atomic)> <!ATTLIST time timezone CDATA #REQUIRED> <!ELEMENT minute (#PCDATA)> <!ELEMENT atomic EMPTY> <!ATTLIST atomic signal CDATA #REQUIRED> <!ELEMENT meridiem (#PCDATA)> <!ELEMENT second (#PCDATA)>
Relaxer can consider the content models of more than one XML document in order to produce a DTD. Try this:
relaxer -dir:out -dtd time1.xml time.xml
Relaxer uses the name of the first file in the list for its output filename, so the output file will be out/time1.dtd, which follows:
<!-- Generated by Relaxer 1.0 --> <!-- Tue Mar 02 17:28:30 MST 2004 --> <!ELEMENT hour (#PCDATA)> <!ELEMENT time (hour, minute, second, meridiem, atomic?)> <!ATTLIST time timezone CDATA #REQUIRED> <!ELEMENT minute (#PCDATA)> <!ELEMENT atomic EMPTY> <!ATTLIST atomic signal CDATA #REQUIRED> <!ELEMENT meridiem (#PCDATA)> <!ELEMENT second (#PCDATA)>
The content for atomic is zero or one (?), as seen on the bold line. This is because atomic does not appear in time1.xml. Therefore, Relaxer interprets it as being an optional element rather than a required one.
The DTDGenerator JAR file came with the files for the book. To generate a DTD from time.xml with this utility, type the following command while in the working directory:
java -cp dtdgen.jar DTDGenerator time.xml
The result of the command is sent to standard output:
<!ELEMENT atomic EMPTY > <!ATTLIST atomic signal NMTOKEN #REQUIRED > <!ELEMENT hour ( #PCDATA ) > <!ELEMENT meridiem ( #PCDATA ) > <!ELEMENT minute ( #PCDATA ) > <!ELEMENT second ( #PCDATA ) > <!ELEMENT time ( hour, minute, second, meridiem, atomic ) > <!ATTLIST time timezone NMTOKEN #REQUIRED >
It appears that DTDGenerator orders the declarations according to how they are stored on the stack. To redirect the output of DTDGenerator to a file, do this:
java -cp dtdgen.jar DTDGenerator time.xml > somesuch.dtd
You can also generate a DTD from an XML document with xmlspy (). This example demonstrates how to do this in xmlspy 2004 Enterprise Edition (Release 3).
Start xmlspy, and use File Open to open time.xml in the working directory.
Choose DTD/Schema Generate DTD/Schema. The Generate DTD/Schema dialog box appears (Figure 5-3). The DTD radio button is selected by default. Click OK.
You are then asked if you want to assign the generated DTD to the document. Click Yes. This adds a document type declaration to the XML document.
Then you are asked to save the DTD. Give it the name spytime.dtd and click the Save button. Overwrite spytime.dtd if it already exists in the working directory (it should).
With File Save As, save time.xml?now with a document type declaration?as spytime.xml.
Choose XML Validate or press F8 to validate spytime.xml against spytime.dtd (Figure 5-4).
If you have xmlspy available, it provides one of the quickest and easiest ways to generate a DTD for an XML document. | https://etutorials.org/XML/xml+hacks/Chapter+5.+Defining+XML+Vocabularies+with+Schema+Languages/Hack+73+Create+a+DTD+from+an+Instance/ | CC-MAIN-2021-31 | refinedweb | 898 | 63.15 |
A null pointer is a pointer which points nothing.
Some uses of the null pointer are:
a) To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet.
b) To pass a null pointer to a function argument when we don’t want to pass any valid memory address.
c) To check for null pointer before accessing any pointer variable. So that, we can perform error handling in pointer related code e.g. dereference pointer variable only if it’s not NULL.
Begin. Declare a pointer p of the integer datatype. Initialize *p= NULL. Print “The value of pointer is”. Print the value of the pointer p. End.
#include <stdio.h> int main() { int *p= NULL;//initialize the pointer as null. printf("The value of pointer is %u",p); return 0; }
The value of pointer is 0. | https://www.tutorialspoint.com/null-pointer-in-c | CC-MAIN-2022-05 | refinedweb | 143 | 68.47 |
Reproduced:
Was wonderful, Mo Kanwan, backup collection
- Network independent papers --------------------------
1001 to modify the hostname (Chen Xu)
vi / etc / sysconfig / network, modify the HOSTNAME an act "HOSTNAME = hostname" (without this line? then add this line right), then run the command "hostname host name." Generally have to modify / etc / hosts file in the host name. In this way, whether you reboot, the host name is successfully modified.
1002 Red Hat Linux boot to a text interface (do not start xwindow) (Chen Xu)
vi / etc / inittab
id: x: initdefault:
x = 3: text x = 5: graphic
1003 linux automatic updates problem (hutuworm, NetDC, Chen Xu)
For redhat, in find patch 6.1 later with a tool up2date, it can determine what needs to upgrade the rpm package, then automatically downloaded from the redhat site and complete the installation.
In addition to kernel upgrade outside the rpm: up2date-u
Upgrades, including kernel, including the rpm: up2date-u-f
The latest redhat and fedora yum command can be used to upgrade or yumex graphical front-end update.
Upgrade Gentoo update portage tree: emerge-sync
Update / install packages: emerge [package name] (such as installing vim: emerge vim)
Debian with other distributions have a lot of difference, to do with the Debian server maintenance more convenient. Debian to upgrade the software:
apt-get update
apt-get upgrade
Premise: configured the network and / etc / apt / sources.list, you can also use apt-setup settings.
1004 windows to see linux partition under software (Chen Xu, hutuworm)
Paragon.Ext2FS.Anywhere.2.5.rar and explore2fs-1.00-pre4.zip
Today, many Linux distributions install by default built on LVM partitions, so explore2fs are the times began to support LVM2:
1005 mount usage (sakulagi, sxsfxx, aptkevin)
fat32 partition mount-o codepage = 936, iocharset = cp936 / dev/hda7 / mnt / cdrom
ntfs partition mount-o iocharset = cp936 / dev/hda7 / mnt / cdrom
iso file mount-o loop / abc.iso / mnt / cdrom
Floppy mount / dev/fd0 / mnt / floppy
USB flash mount / dev/sda1 / mnt / cdrom
Scsi hard disk in a computer, if the above command to mount usb flash memory, it will mount to the / boot partition. This situation, you should use fdisk-l / dev / sd? To see in the end is a usb flash drive in which the device (usually be sdb or sdc). Such as a machine, is sdc1 above.
All / etc / fstab mount-a content
You can specify the file format "-t format", format for vfat, ext2, ext3 and so on.
Access DVD mount-t iso9660 / dev / dvd / mnt / cdrom or mount-t udf / dev / dvd / mnt / cdrom
Note: dvd format is generally one of iso9660 or udf
LINUX in 1006 in vmware the FAT partition using the local hard disk (Chen Xu)
FAT partition will be the local share, and then hang in VMWARE using SMBFS. Can be the following line into / etc / fstab in:
/ / Win_ip / D $ / mnt / d smbfs defaults, auto, username = win_name, password = win_pass, codepage = 936, iocharest = gb2312 0 0
One win_ip is the IP address of your windows;
D $ is inside your windows shared D drive share name;
/ Mnt / d is to mount the partition to the linux directory;
win_name and win_pass inside your WINDOWS user can read the partition, such as your administrator name and password.
If you run the / etc / rc.d / init.d / netfs, then the start time will automatically mount the partition.
1007.a delete a file called-a (Chen Xu)
rm. /-a
rm --a tells rm This is the last option, see getopt
ls-i lists inum, and then find.-inum inum_of_thisfile-exec rm '{}' \;
1007.b delete the file named \ a file (Chen Xu)
rm \ \ a
1007.c delete the name with the / and '\ 0' file (Chen Xu)
These characters are not allowed by the normal file system characters, but may be generated in the file name, such as a unix NFS file system used on the Mac
1 solution, the NFS file system is not linked to the filter '/' character to delete system files with special file name.
2 error file name can also be other files to remove the directory, ls-id display the directory containing the file inum, umount the file system,
clri clear the directory inum, fsck, mount, check your lost + found, rename the file in it.
Preferably through WINDOWS FTP in the past you can delete any file name of the files!
1007.d delete invisible character with the name of the file (Chen Xu)
Lists the file name and dump to a file: ls-l> aaa
Then edit the contents of the file add the contents of the rm command to delete the file format as:
vi aaa
[Rm-r *******
]
The file with execute permission chmod + x aaa
Executive $ aaa
1007.e delete files with zero size files (Chen Xu)
rm-i `find. /-size 0`
find. /-size 0-exec rm {} \;
Or
find. /-size 0 | xargs rm-f &
Or
for file in * # define their own type of file to delete
do
if [!-s $ {file}]
then
rm $ {file}
echo "rm $ file Success!"
fi
done
1008 redhat setting wheel mouse (mc1011)
Into X, choose the configuration of the mouse, select the wheel mouse (ps / 2) on it,
If the mouse to behave abnormally, restart the computer.
(Or su, vi / etc/X11/XF86Config, the PS / 2 into ImPS / 2)
1009 installation of xwindow (Chen Xu)
CD-ROM with the linux boot, choose to upgrade, and then select individual packages, can be installed
1010 to delete linux partition (Chen Xu)
Make a partition magic boot floppy, start to delete, or start with a win2000 boot CD, then delete.
1011 How to quit man (Chen Xu)
q
1012 does not compile the kernel, mount ntfs partition (Chen Xu, hutuworm, qintel)
Original rh8, or compile the kernel was not upgraded
1 on google.com search and download the kernel-ntfs-2.4.18-14.i686.rpm
2. Rpm-ivh kernel-ntfs-2.4.18-14.i686.rpm
3. Mkdir / mnt / c
4. Mount-t ntfs / dev/hda1 / mnt / c
Or
Read only:
Read / Write:
1013 tar-volume compression and consolidation (WongMokin, Waker)
500M per roll, for example
tar-volume compression: tar cvzpf - somedir | split-d-b 500m
merge multi-volume tar: cat x *> mytarfile.tar.gz
1014 using the lilo / grub recover forgotten when the root password (Chen Xu)
Three ways:
1 in the system into single-user state, the direct use passwd root to change the
2 with the installation CD to boot the system, the linux rescue the state, the original / partition mount up, the practice is as follows:
cd / mnt
mkdir hd
mount-t auto / dev / hdaX (original / partition where the partition number) hd
cd hd
chroot. /
passwd root
This can get
3. This machine's hard drive to win, hanging on to other linux system, using the same approach and the second
rh8 one. lilo
1. In the event of lilo: prompt, type linux single
Screen display lilo: linux single
(2) enter directly into the linux command line
3. # Vi / etc / shadow
The first line, that is the beginning of the line root root: and after the next: first the contents of the deleted
The first line is similar to
root ::......
Save
4. # Reboot reboot, root password is empty two. Grub
1. Grub screen appears, select using the arrow keys that you usually start a linux (do not choose dos yo), then press e
2 once again selected using the arrow keys that you usually start a linux (like kernel / boot/vmlinuz-2.4.18-14 ro root = LABEL = /), then press e
3 changes you now see the command line, add single, results are as follows:
kernel / boot/vmlinuz-2.4.18-14 single ro root = LABEL = /
4 carriage return, then press the b key to start, you can go directly to the linux command line
5. # Vi / etc / shadow
The first line, that is the beginning of the line root root: and after the next: first the contents of the deleted
The first line is similar to
root ::......
Save
6. # Reboot reboot, root password is empty
1015 to ctrl + alt + del fails (Chen Xu)
vi / etc / inittab
The ca:: ctrlaltdel: / sbin / shutdown-t3-r now comment out this line, you can
1016 to see the redhat version is 7 or 8 (hutuworm)
cat / proc / version or cat / etc / redhat-release or cat / etc / issue
1017 rpm file in which the (Warriors)
On found on, or get rpm-qf filename
1018 man or info information saved as a text file (Chen Xu)
In tcsh, for example:
man tcsh | col-b> tcsh.txt
info tcsh-o tcsh.txt-s
1019 using the existing two files to generate a new file (Chen Xu)
Prerequisites: Each file must not contain any duplicate rows
1 Remove the two files and set (keep a copy of duplicate rows only)
2 Remove the intersection of two files (leaving only two files exist in the file)
3 Delete the intersection, leaving the other line
1. Cat file1 file2 | sort | uniq
2. Cat file1 file2 | sort | uniq-d
3. Cat file1 file2 | sort | uniq-u
1020 set the com1 port, com1 port via HyperTerminal to log in (Chen Xu)
Recognizing the / sbin / agetty, edit / etc / inittab, add
7:2345: respawn: / sbin / agetty / dev/ttyS0 9600
9600bps is because this is generally associated router default rate, can also be set
19200,38400,57600,115200
Modify / etc / securetty, add a line: ttyS0, to ensure that the root user can log on to restart the machine, you can unplug the mouse, keyboard, monitor (start to look better output) of the
1021 Delete all files and subdirectories under the directory (Chen Xu)
rm-rf directory name
1022 View system information (Chen Xu)
cat / proc / cpuinfo - CPU (ie vendor, Mhz, flags like mmx)
cat / proc / interrupts - interrupt
cat / proc / ioports - Device IO Port
cat / proc / meminfo - memory information (ie mem used, free, swap size)
cat / proc / partitions - all partitions of all devices
cat / proc / pci - PCI device information
cat / proc / swaps - all the information Swap partition
cat / proc / version - Linux version number is equivalent to uname-r
uname-a - look at the system kernel and other information
1023 to remove the extra carriage return (Chen Xu)
sed 's / ^ M / /' test.sh> back.sh, note that ^ M is a knock ctrl_v ctrl-m to get or dos2unix filename
1024 switch X desktop (lnx3000)
If you are a graphical login to log on linux, then click on the login screen session (tasks) that you can choose gnome and kde. If you are text log, then perform switchdesk gnome or switchdesk kde, then startx to get into gnome or kde.
(Or vi ~ /. Xinitrc, add or modify as exec gnome-session or exec startkde,
Then startx starts X)
1025 generic sound card driver (lnx3000)
OSS ALSA
1026 to change the redhat system language / character set (beming/mc1011)
Modify / etc/sysconfig/i18n documents, such as
LANG = "en_US", xwindow will display English interface,
LANG = "zh_CN.GB18030", xwindow Chinese language interface will be displayed.
Another method
cp / etc/sysconfig/i18n $ HOME/.i18n
Modify $ HOME/.i18n documents, such as
LANG = "en_US", xwindow will display English interface,
LANG = "zh_CN.GB18030", xwindow Chinese language interface will be displayed.
This can change the individual's interface language, without affecting other users
(Debian does not support GB18030 (RH of zysong font is copyrighted)
Now does not seem to Free the GBK and GB18030 font
vi. bashrc
export LANG = zh_CN.GB2312
export LC_ALL = zh_CN.GB2312)
1027 screen is set to 90 (Chen Xu)
stty cols 90
1028 use the md5sum file (Chen Xu)
md5sum isofile> hashfile, the md5sum file and hashfile file content comparison, validation hash value is consistent md5sum-c hashfile
1029 more than one extract the zip file (Chen Xu)
unzip "*", note the quotation marks can not be less
1030 view pdf file (Chen Xu)
Use xpdf or install acrobat reader for linux
1031 Find the file permission bits of S (Chen Xu)
find.-type f \ (-perm -04000-o-perm -02000 \)-exec ls-lg {} \;
1032 install Chinese input method (Chen Xu, hutuworm)
To redhat8 example, xwindow its terminal under needless to say, the default on install, use ctrl-space breath.
Now discuss the pure console, go to download zhcon-0.2.1.tar.gz, on any directory, tar xvfz zhcon-0.2.1.tar.gz, cd zhcon-0.2 .1,. / configure, make, make install. Installation is complete, in order, run the zhcon, want to exit, run exit.
1033 back to the pop-up CD-ROM (beike)
# Eject-t
1034 cd iso file made CD-ROM (mentally handicapped)
cp / dev / cdrom xxxx.iso
1035 quick start viewing hardware detection (mentally handicapped)
dmesg | more
1036 view hard disk usage (Chen Xu)
df-k to K units display
df-h to display user-friendly units, which can be b, k, m, g, t..
1037 view directory size (Chen Xu)
du-sh dirname
-S Display only a total of
-H to K, M, G unit, to improve the readability of information. KB, MB, GB is 1024 for the conversion unit,-H in 1000 as a conversion unit.
1038 Find a file or delete the process being used (wwwzc)
fuser filename
fuser-k filename
1039 installation software (Chen Xu)
rpm-ivh aaa.rpm
tar xvfz aaa.tar.gz; cd aaa;. / configure; make; make install
1040 character mode set / delete environment variables (Chen Xu)
set under bash: export variable name = variable value to delete: unset variable name
set under csh: setenv variable value variable name to delete: unsetenv variable name
1041 ls how to see hidden files (ie. At the beginning of the file) (eyelid pig)
ls-a
l. (for redhat)
1042 rpm files install gone (Chen Xu)
rpm-qpl aaa.rpm
1043 using src.rpm (Chen Xu)
rpmbuild - rebuild *. src.rpm
1044 vim does not display color or display color (Chen Xu, sakulagi)
First, make sure to install vim-enhanced package, then, vi ~ /. Vimrc; if syntax on, the display color, syntax off, the color is not displayed.
In addition, about vi's syntax color, another point is the terminal type (the environment variable TERM) settings. Example, usually set to xterm or xterm-color to use syntax color. Especially from Linux to other remote landing on Unix.
1045 linux real-time or time-sharing operating system (Chen Xu)
Time-sharing
1046 make bzImage-j j-mean (wind521)
-J is mainly used when your system hardware resources are relatively large, relatively affluent, you can use this to speed up the compilation speed, such as-j 3
1047 how no source packages (Chen Xu)
You do not have the source code, you put your CD on the rpm-i * kernel * source *. rpm installed, you can see your source code.
1048 to modify the system time (Chen Xu, laixi781211, hutuworm)
date-s "2003-04-14 cst", cst refers to the time zone, time set with the date-s 18:10
Changes into CMOS clock-w writes
hwclock - systohc
set the hardware clock to the current system time
1049 to mount on the windows boot partition (Chen Xu)
Automatically linked to the windows drive d / mnt / d, and with vi to open / etc / fstab, add the following line
/ Dev/hda5 / mnt / d vfat defaults, codepage = 936, iocharset = cp936 0 0
Notice served by hand to create a / mnt / d directory
1050 linux how to use so much memory (Chen Xu)
In order to improve system performance and do not waste memory, linux and more memory to do the cache, to improve the io speed
1051 FSTAB final configuration items inside the last two numbers mean (lnx3000)
The first is called fs_freq, used to determine which file systems need to perform dump operations, 0 is not required;
The second is called fs_passno, fsck program when the system detects the disk to restart the sequence number
1 is the root file system, 2 is the other file system. fsck disk detected by serial number, 0 means that the file system is not being detected
ext2 file system dump perform the backup operation
detect and repair the file system fsck
1052 linux in the user's password must have a certain length, and in line with the complexity (eapass)
vi / etc / login.defs, change PASS_MIN_LEN
1053 linux in the translation software (Chen Xu, hutuworm)
StarDict xdict
dict the next there is a console tool, to dict.org DICT protocol dictionary on the check 11, for example: dict RTFM
1054 not to display sleep (Chen Xu)
setterm-blank 0
setterm-blank n (n is the waiting time)
1055 queries with dat yesterday's date (gadfly)
date - date = 'yesterday'
1056 xwindow how to screen shot (Chen Xu)
Ksnapshot or gimp
1057 Souvenir extract (Chen X
unzip example.zip
tar-jvxf some.bz, is to tar the zvxf into jvxf
zip / tar rh8 under a graphical interface software file-roller can do this. Also you can use unzip *. zip unlock the zip file, unrar *. rar unlock the rar file, unrar but the general system does not own, to go to download.
# Rpm2cpio example.rpm │ cpio-div
# Ar p example.deb data.tar.gz | tar zxf -
Alien offers. Tgz,. Rpm,. Slp and. Deb compression format such as converting between:
sEx provides almost all of the visible interface to extract the compressed format:
1057-2 tar compression, decompression usage (platinum)
Extract: x
Compression: c
For gz: z
For bz2: j
For display: v
Extract examples
gz file: tar xzvf xxx.tar.gz
bz2 files: tar xjvf xxx.tar.bz2
Compression Example
gz file: tar czvf xxx.tar.gz / path
bz2 files: tar cjvf xxx.tar.bz2 / path
1058 in a multi-level directory for a file method (Qinghai Lake)
find / dir-name filename.ext
du-a | grep filename.ext
locate filename.ext
1059 not to ordinary users to change their own password (myxfc)
[Root @ xin_fc etc] # chmod 511 / usr / bin / passwd
They want the ordinary user to change password
[Root @ xin_fc etc] # chmod 4511 / usr / bin / passwd
1060 graphics card is good enough for how to do (win_bigboy)
To, under xfree86 4.3 installed on it.
1061 Super remove formatting tools (mentally handicapped)
PQMagic secure than the establishment of a small tool to delete format: sfdisk.exe for msdos
1062 How to make xmms play list to display the correct Chinese (myxfc)
-*-*-*-*-*- Iso8859-1,-misc-simsun-medium-r-normal - 12-*-*-*-*-*- gbk-0, *- r-
Put this thing to completely copy the font inside your methods of operation:
Right-click anywhere in xmms player tool will see an "Options" and select "Preferences" Select "fonts"
Then a complete copy of the font above the "Playlist" and "user x font
1063 redhat linux play mp3 files (hehhb)
Xmms can not play with the original MP3 (silent), to install an RPM package: rpm-ivh xmms-mp3-1.2.7-13.p.i386.rpm. Open xmms, ctl-p, the first column in the font small box in the upper half of the tick, and then select the "fixed (misc) gbk-0 13"-point font to display Chinese song names. In the audio output plug-in, select "open audio system driver 1.2.7 [lioOSS.so], can play MP3 files properly.
1064 Installation of Chinese fonts (hehhb)
First download ~ George / sm.sh
(Reference:)
SimSun18030.ttc the Microsoft Web site to download,
030.asp it is a msi file to install the mswindows used, installed after the fonts in the windows directory
Directory you can find it. The simsun.ttc, SimSun18030.ttc, tahoma.ttf, tahomabd.ttf
Copied to / usr / local / temp, then download the files into the shell in this directory, then open the terminal
cd / usr / local / temp
chmod 755 sm.sh
. / Sm.sh
1065 load windows partition FAT32, FAT16 file system (hehhb, NetDC)
As root, enter the KDE, click on the desktop "start" icon in the / mnt directory, create the following folder: c, d, e, f, g, usb. The district were used as the windows and usb flash drives.
With a text editor to open / etc / fstab file by adding the following:
/ Dev/hda1 / mnt / c vfat iocharset = gb2312, umask = 0, codepage = 936 0 0
/ Dev/hda5 / mnt / d vfat iocharset = gb2312, umask = 0, codepage = 936 0 0
/ Dev/hda6 / mnt / e vfat iocharset = gb2312, umask = 0, codepage = 936 0 0
/ Dev/hda7 / mnt / f vfat iocharset = gb2312, umask = 0, codepage = 936 0 0
/ Dev/hda8 / mnt / g vfat iocharset = gb2312, umask = 0, codepage = 936 0 0
/ Dev / cdrom / mnt / cdrom udf, iso9660 noauto, iocharset = gb2312, owner, kudzu, ro 0 0
/ Dev/sda1 / mnt / usb vfat iocharset = gb2312, umask = 0, codepage = 936 0 0
Save and exit. Reboot to normal access to FAT32 or FAT16 format partition, partition solution shown WINDOWS Chinese file name and CD-ROM under the garbage problem. One of six rows, each row separated by the Tab key. Note that this method can only mount on Fat partition format, sda1 is the stick.
In addition, if it is garbled, you can change iocharset = utf8.
1066 under X use Wubi and Pinyin, location input (hmkart)
Fcitx from download the rpm package can be installed
1067 in Linux, how to extract rar files (hmkart)
Download rar for Linux 3.2.0, make open, extract
Then you can use unrar e youfilename.rar extract rar files
1068 hard drive installation how to add / delete the rpm package (sakulagi)
redhat-config-packages - isodir = <PATH>
You can specify the directory where the iso file
1069 characters under the control volume (grub007, outer Lonely)
Using aumix. In addition, the volume level you want to save oss, the steps are:
1, adjust the volume with aumix volume for your satisfaction
2, with the root user to enter / usr / lib / oss under (oss the default installation directory)
3, execution. / Savemixer. / Mixer.map
4, ok, later oss open after the first step is to adjust the volume you had.
ps: read the README of the directory can get more useful information.
1070 using dd to do iso (grub007)
dd if = / dev / cdrom of = / tmp / aaa.iso
1071 removed a few days ago everything (including the directory name and files in the directory) (shally5)
find.-ctime +3-exec rm-rf {} \;
Or
find. /-mtime +3-print | xargs rm-f-r
1072 where the user's crontab (hutuworm)
/ Var / spool / cron / username next to a file named
1073 to run the program as a different user (Chen Xu)
su - username-c "/ path / to / command"
Sometimes need to run the special status of the program, you can do to su
1074 How to empty a file (Chen Xu)
> Filename
1075 Why OpenOffice can not be displayed Chinese (allen1970)
Change the font settings
tools-> options-> font replacement
Andale Sans UI -> simsun
1076 How to backup Linux system (Purge)
Symantec Ghost 7.5 Ext3 native support for later copy
1077 linux on the partition magic (wwwzc)
Partition under Linux a useful tool: parted
Real-time resize partitions, delete / create partitions.
1078 / proc / sys / sem What does it mean in each? (Sakulagi)
/ Proc / sys / sem as follows
2503200032128
These four parameters were SEMMSL (each user has the maximum number of semaphore), SEMMNS (maximum number of semaphore system), SEMOPM (per semop system call a few), SEMMNI (the maximum number of semaphore sets system)
1079 Grub boot menu bigmem smp up all mean? (Lnx3000)
smp: (symmetric multiple processor) symmetric multi-processor mode
bigmem: support more than 1G of memory optimized kernel
up: (Uni processor) single-processor mode
1080 Oracle of the installation process why the garbled? (Lnx3000)
Now Oracle installer support of the Chinese problem, use only English interface to install, running runinstaller before execution: export LANG = C; export LC_ALL = C
1081 linux files and directories under the color mean anything (sakulagi, mentally handicapped)
Blue directory; green represent an executable file; red archives; light blue indicates a link file; Gray said other documents; red flashing indicates a problem linked file; yellow is the device file, including block, char, fifo.
With dircolors-p to see the default color settings, including a variety of colors and the "bold", underline, blinking and other definitions.
1082 to see how many activities of the httpd script (Chen Xu)
#! / Bin / sh
while (true)
do
pstree | grep "* \ [httpd \] $" | sed 's / .*- \ ([0-9] [0-9] * \) \ * \ [httpd \] $ / \ 1 /'
sleep 3
done
1083 How to add a hard drive (nice)
First, shut down, physically connect the hard disk if the IDE hard drive, pay attention to the main, from the disk set; If a SCSI hard drive, pay attention to selecting an unused ID.
Second, the power to check the hard disk has not been detected linux
dmesg | grep hd * (ide hard drive)
dmesg | grep sd * (SCSI drives)
Or less / var / log / dmesg
If you do not detect your new hard drive, reboot, check the connections to see if there are bios did not recognize it.
Third, the partition you can use fdisk, Sfdisk or parted (GNU partitioning tool, linux under partition magic)
Fourth, the format
mkfs
Fifth, to modify fstab
vi / etc / fstab
1084 linux partition under the label to see how ah (q1208c)
e2label / dev / hdxn, where x = a, b, c, d. ...; n = 1,2,3 ...
1085 RH8, 9 after installing How to add new language packs (nice)
A .8.0 in
1 into the first CD-ROM
2.cd / mnt / cdrom / Redhat / RPMS
3.rpm-ivh ttfonts-ZH_CN-2.11-29.noarch.rpm (Simplified Chinese, you can use the tab key to the padded back section, so as not to make a mistake)
4.rpm-ivh ttfonts-ZH_TW-2.11-15.noarch.rpm (Traditional Chinese)
If you want to install Japanese, Korean, try the second disc ttfonts *. rpm.
Two .9.0 in
9.0 is not the first disk in the third disk. Rpm package names are:
ttfonts-zh_CN-2.12-1.noarch.rpm (Simplified Chinese)
ttfonts-zh_TW-2.11-19.noarch.rpm (Traditional Chinese)
1086 terminal screen capture (tsgx)
cat / dev / vcsX> screenshot of which, X represents the first X terminals can run script screen.log, record on-screen information to screen.log years. For a record of your exit end. This is also a good way to screen capture.
This is seen on a debian cookbook. Can be used on the RH9. Not tested on other systems.
1087 for a program to continue running after logout (NetDC, eyelid pig)
# Nohup program name &
Or use the disown command can also be
1088 man command not in the path, how to view the file non-standard man (Chen Xu)
nroff-man / usr/man/man1/cscope.1 | more
1089 cp to display the progress (Chen Xu)
cp-r-v dir1 dir2
cp-a-d-v dir1 dir2
1090 edit / etc / inittab after the direct effect (Chen Xu)
# Init q
1091 for several consecutive linux command error stop (Chen Xu)
command1 & & command2 & & command3
1092 how to install grub to the mbr (Chen Xu, NetDC)
grub> root (hd0, 0)
grub> setup (hd0)
You can also use # grub-install / dev / hda to install grub.
1093 installation, the grub (lilo) write linux partition boot sector or master boot sector (MBR) (Chen Xu)
If you want to boot directly into a computer operating system boot menu to put grub (lilo) to write the MBR, if you write to linux partition boot sector is to use the bootdisk. Proposal writing MBR, convenient point, as that writes MBR unsafe, how to explain it? Every once installed win98, MBR will be changed once you feel unsafe do what?
1094 how to make multi-system co-exist (Chen Xu)
98, then use lilo (grub) boot, 2k/nt boot multiple systems using osloader
1095 how the graphical interface and console (Character Interface) switch back and forth between (Chen Xu)
a. graphical interface to the console: Ctr + Alt + Fn (n = 1,2,3,4,5,6).
b. The switch between the console: Alt + Fn (n = 1,2,3,4,5,6).
c. console to graphics: Alt + F7
1096 Redhat linux common commands (Chen Xu)
<1> ls: directory listing.
Usage: ls or ls dirName, arguments:-a show all files,-l List files in detail.
<2> mkdir: build directory.
Usage: mkdir dirName, parameters:-p build multi-level directory, such as: mkdir a / b / c / d / e / f-p
<3> mount: Mount the partition or image file (. Iso,. Img) file.
Usage:
a. disk partition: mount deviceName mountPoint-o options, which deviceName is the disk partition's device name, such as / dev/hda1, / dev / cdrom, / dev/fd0, mountPoint is the mount point, it is a directory, options are parameters, if the partition is linux partition, generally do not have-o options, if the windows partition that options can be iocharset = cp936, so windows partition in the Chinese file name can be displayed. Use cases: for example, / dev/hda5 is linux partition, I want to hook it up to a directory (such as it is not a directory a first mkdir a), mount / dev/hda5 a, so what is the directory where a partition hda5 in the things, such as hda1 is the windows partition, we should hook it up to b on, mount / dev/hda1 b-o iocharset = cp936.
b. image: mount fileName mountPoint-o loop, fileName is the image file name (*. iso, *. img), others do not say, as above. Use Case: If I have a a.iso CD image file, mount a.iso a-o loop, so you can browse into the directory a a.iso the contents, *. img file use the same.
<4> find: Find files.
Usage: find inDir-name filename, inDir is the directory in which you want to find, filename is the name of the file you are looking for (you can use wildcards), when the filename with wildcards best single quotation marks, or sometimes error, use case: find.-name test *, in the current directory to find files starting with test.
<5> grep: find the file specified string.
Usage: grep string filename, the filename (can be wildcard) in the search string (best to use double quotation marks). Parameters:-r filename in all subdirectories of where to find. Use Case: grep hello *. c-r in the current directory (including subdirectories) in all. C files to find hello.
<5> vi: Editor.
Usage: vi filename. filename that you want to edit text files. With the implementation of vi filename, you may find that you can not edit the text, do not worry, this is because not enter the vi editor, press a or i can enter edit mode, and enter the edit mode you can edit the text after the. To exit the edit mode, press the Esc key on it. The following operations are performed in non-edit mode. Find text: I / you want to find the text and press Enter. Exit: type: and q and press Enter, if you modify the text, then you use: q! Enter to exit. Save: Input: w enter, if it is read-only file to use: w!. Save and exit: enter: wq enter, if it is read on: wq! Enter. Cancel: Press u on it, press the Cancel step, according to cancel several more steps. Copy and paste line of text: Move the cursor to the line to be copied anywhere, by yy (that is, double click on the y), move the cursor where you want to paste the previous line, according to p, just that line of text will be line where the cursor into the next line, the original line after the cursor down one row all the rows automatically. Copy and paste multiple lines of text: copy the line with similar, but to enter into yy the number of rows to be copied followed by yy, behind the same operation. Move the cursor to the specified line: input: and a line number and enter, such as the move to line 123: 123 Enter, move to the end: $ Enter.
1097 linux how to close a text interface pc speakers (labrun)
The / etc / inputrc in the set bell-style none before the # removed, or echo "set bell-style none">> ~ /. Bashrc
Lead to reinstall windows 1098 can not boot linux solution (nice)
If you do not re-partition, get linux boot disk (or the first installation CD-ROM) boot into rescue mode. First, find the original / partition mount in any place. redhat usually / mnt / sysimage. execute "chroot / mnt / sysimage". if it is grub, type grub-install / dev / hd * (based on availability); If it is lilo, type lilo-v, and then restart. If the partition is changed, corresponding to modify / etc / lilo.conf and / boot / grub / grub.conf and then execute the command.
Why LINUX installed after 1099 win2K very slow (lnx3000, nice)
Old problem, you can see in 2000 is not a Linux logical, but can not access?
In Disk Management, the select the disk, right-click -> Change "Drive Letter and Path" -> "delete" on it, pay attention not to delete the disk!
1100 release of the linux iso file to burn to CD method (Chen Xu)
Borrow the windows in the nero software, select the image file to burn, choose iso file, burn to!
1101 linux Way to burn iso (hutuworm) Method One : Use xcdroast, choose to create CD-ROM , Select the ISO file , Burn ! See Method Two : Command to find burner : cdrecord --scanbus Output is : 0,0,0 0) 'ATAPI ' 'CD-R/RW 8X4X32 ' '5.EZ' Removable CD-ROM Burn command : cdrecord -v speed=8 dev=0,0,0 hutuworm.iso Method Three : Can burn with k3b CD/DVD k3b Home : ( In fact k3b is a graphical interface , Burn a CD using the cdrecord, Burn a DVD using the dvd+rw-tools ) 1102 How to do when the screen changes take ( Pig eyelid ) When you accidentally cat is not a text file when the , Then the screen will become flowers, you can double-click "Enter" Key, then hit "reset", Then the screen back to normal .... 1103 How to uninstall the package that specific package name (diablocom) We all know the command to delete the package is rpm-e XXX, but when we do not know XXX The exact spelling, you can use rpm -q -a Query all installed packages or use rpm -qa |grep xxxx Check out the name of the 1104 Memory for use under linux /tmp Folder (yulc) In the / etc / fstab to add a line : none /tmp tmpfs default 0 0 Or in the / etc / rc.local add mount tmpfs /tmp -t tmpfs -o size=128m Note :size=128m That / tmp maximum usable 128m Either way, as long as linux Reboot, / tmp files all disappear under the 1105 List only directories with ls (yulc) ls -lF | grep ^d ls -lF | grep /$ ls -F | grep /$ 1106 In the command line following the IP address of the machine , And not get card information (yulc) ifconfig |grep "inet" |cut -c 0-36|sed -e 's/[a-zA-Z: ]//g' hostname -i 1107 Modify / etc / profile or $HOME/.profile How effective immediately after the file (peter333) #source /etc/profile ( Or source .profile) 1108 bg And the use of fg ( Chen Xu ) Enter ctrl + z, the current task will be suspended and a suspended , Number on the screen while the process of return, this time with "bg % Process number ", will perform this process in the background , But with " fg % Process number "will be able to make this process into the foreground to perform . In addition, job command is used to view the current bg Process 1109 ctrl+s And ctrl+q( Chen Xu ) ctrl-s To suspend sending data to the terminal screen as dead as , You can use the ctrl-q to resume 1110 Catalog statistics script ( Chen Xu ) Save as total.sh, then total.sh Absolute path, the path under the statistics can be the size of a directory Code : #!/bin/sh du $1 --max-depth=1 | sort -n|awk '{printf "%7.2fM ----> %s\n",$1/1024,$2}'|sed 's:/.*/\([^/]\{1,\}\)$:\1:g' 1111 grep Process does not show itself ( Chen Xu ) #ps -aux|grep httpd|grep -v grep grep -v grep You can cancel the show itself, the process performed grep ,-v Parameter is not displayed process name listed 1112 Enter a keyword to delete the directory containing the file (WongMokin) find /mnt/ebook/ -type f -exec grep " Enter keyword " {} \; -print -exec rm {} \; 1113 Cron does not allow feedback to the task , The cases of five minutes to check a mail (WongMokin) 0-59/5 * * * * /usr/local/bin/fetchmail > /dev/null 2>&1 1114 Extract the rpm file under the current directory ( Chen Xu ) cat kernel-ntfs-2.4.20-8.i686.rpm | rpm2cpio | pax -r 1115 Postscript or merge two Remove the apache manual Directory of all. En suffix name ( Chen Xu ) Into the manual directory Code :find ./ -regex .*\.en|awk -F. '{ printf "mv %s.%s.%s.%s %s.%s.%s\n",$1,$2,$3,$4,$1,$2,$3}'|sh 1117 How to play multiple X(noclouds) startx Default order display :0.0 From the first X, by passing a parameter to the Xserver Can play a more X: # startx -- :1.0 # startx -- :2.0 ... Then switch Ctrl-Alt-F7/F8 ... . 1118 Let a program to continue running after logout (noclouds, Chen Xu ) # <cmd> # disown Or nohup command & 1119 See Linux startup screen display information ( Chen Xu ) After starting with the command dmesg to view 1120 So that vi does not ring (sakulagi) echo "set vb /proc/sys/ Finally, enter the unzipped directory, run the installation command . # cd vmware-linux-tools # ./install.pl 1154 Originally equipped with Linux and Windows XP, After a reinstall of Windows XP , Linux and found that Windows XP Start menu, how to solve ( Chen Xu ) First, boot the CD, enter rescue Models, GRUB, A grub prompt grub>, And then typing the following statement, restart just fine . root (hd0,2),setup (hd0) 1155 Installed a Linux server , Would like to compile your own kernel, step by step down ,GRUB Also added to it, but there "kernel Panic:VFS:Unable to mount root fs on 0:00" Error, how does that matter ?( Chen Xu ) Under normal circumstances initrd file on the desktop this is not necessary , But in a SCSI device server is a must . Possible because the compile time, did not produce the file initrd , So there will be above error. Users can use mkinitrd Command to generate a initrd.img file , Then add GRUB, try to restart . 1156 How to set user login welcome message ?( Chen Xu ) Modify / etc / motd file , Entered, write the text, will enable users to Telnet Properly logged in, execute Shell Before the corresponding message . motd Is the "messages of the day", that is, the meaning of the day information . Administrators can be entered, write to note or a formal notification to alert the user . 1157 I downloaded rcs5.7, with ./configure && make && make install When the error is as follows :./conf.sh: testing permissions ... ./conf.sh: This command should not be run with superuser permissions. I logged in as root user to install compiled , Why is it so ?( Chen Xu ) Some software is really taking into account that security and other reasons can not be compiled with the root user . Then just compile with other users, to make install This step, if the software is not installed in the compilation of the user's home directory when , Need to use the su command to convert root Users then perform make install. 1158 I failed in installing USBView , Details are as follows : #rpm -ivh usbview-1.0-9.src.rpm warning:usbview-1.0-9.src.rpm:V3 DSAsignature:NOKEY,key IDab42a60e ( Chen Xu ) This line of code to install the failure is because your system is not installed the appropriate key to verify signatures. To make the package by checking , You can import Red Hat's public key to solve , Specific way is to run the following command at Shell : #rpm -import /usr/share/rhn/RPM-GPG-KEY ( Attention to the case ) 1159 How to prevent a critical file is modified ?( Chen Xu ) Under Linux , Some of the configuration file is not allowed anyone ( Include root) Modified order to prevent deletion or modification , You can set the file "can not modify the bit (immutable) ". Command is as follows : # chattr +i /etc/fstab If you need to modify the following command is used : # chattr -i /etc/fstab 1160 How to limit a user can start the processes ?( Chen Xu ) First determine what / etc / pam.d / login file the following line in the presence of : session required /lib/security/pam_limits.so Then edit / etc / security / limits.conf, in which the user can set the process limit the number of .CPU Utilization and memory usage, etc., such as hard nproc 20 Refers to the 20 process limit , Concrete can be seen man. 1161 How to limit the size of Shell Command History ?( Chen Xu ) By default, bash in the file $HOME/.bash_history Holds up to 500 commands in the record . Sometimes, depending on the systems, the default number of records in different . System, each user's home directory has a file such order to the system's security , Is strongly recommended that users limit the size of the file the user can edit /etc/profile File, modify the following options : HISTFILESIZE=30 Or HISTSIZE=30 This command will record the number reduced to 30 bar . 1162 I want to turn the information displayed when retained to check the computer out of the problem areas , Ask how to do ?( Chen Xu ) Can enter the following command : #dmesg > bootmessage The boot command will redirect output to display information in a file bootmessage . 1163 I want to log out when you remove the command record, may I ask how to do ?( Chen Xu ,mhxkcu) Edit / etc / skel / .bash_logout file , Add the following line : rm -f $HOME/.bash_history In this way, the system when all users log off command will delete the record . If only for a specific user, such as root User settings, the user can only modify the main directory /$HOME/.bash_logout File, you can add the same line . 1164 Kernel support ntfs Steps (platinum, Chen Xu ) 1. # cd /usr/src/linux-2.4 2. # make menuconfig 3. Select File System under the NTFS file system support (read only) As M 4. # uname -a 2.4.21-27.0.2.EL 5. # vi Makefile Ensure that the first few acts VERSION = 2 PATCHLEVEL = 4 SUBLEVEL = 21 EXTRAVERSION = -27.0.2.EL 6. # make dep 7. # make modules SUBDIRS=fs/ntfs 8. # mkdir /lib/moduels/2.4.21-27.0.2.EL/kernel/fs/ntfs 9. # cp -f fs/ntfs/*.o /lib/moduels/2.4.21-27.0.2.EL/kernel/fs/ntfs/ 10. # depmod -a 11. # modprobe ntfs 12. # lsmod Ensure ntfs inside 1165 How to use ssh tunneling ( Chen Xu ) This article discusses the Linux operating system, all machines are . For example, my machine is A, the intermediate server B, Target server is C. From A can ssh To B, from B Can ssh to C, But A can not be directly ssh To C. Now demonstrate the use of ssh tunneling technology from A Transfer files directly to the C. 1. ssh -L1234:C:22 root@B input B's password 2. scp -P1234 filename root@localhost: input C's password 1166 Use the rpm command no response , How to solve ( Beginners Photography ) rm -rf /var/lib/rpm/__db.* 1167 To log on to the same server send a message to all users ( Chen Xu ) 1) Enter the wall and enter 2) Enter the message to be sent 3) End of the press "Control-d" key , Information that is displayed in the user's control window 1168 Enter a short message to a single user ( Chen Xu ) 1) Input write username, the user name appears in multiple terminals , After the user name can be added tty, to indicate in which tty Under the user . 2) Enter the message to be sent . 3) End of the press "Control-d" key , Information that is displayed in the user's control window . 4) For the party receiving messages, you can set whether to allow people to send messages to you . Instruction format :mesg n[y] %write liuxhello! Everybody, I'llcome. % User Control window displays the message :Message from liux on ttyp1 at 10:00-hello! Everybody, I'llcome.EOF When using the CDE or OpenWindows Other window system, each window is seen as a single login : If the user is logged more than once then send the message directly to the control window . 1169 Send a message file to a single user ( Chen Xu ) If there is a longer message will be sent to several users, with papers : 1) Create a text message to send the file filename. 2) Enter write username<filename Enter, with cat Command creates a file containing a short message : % cat >messagehello! Everybody, I'llcome. % write liux<messagewrite:liux logged in more than once-write to console % User log in more than one window, the message displayed in the control window Message from liux on ttyp1 at 10:00-hello! Everybody, I'llcome.EOF 1170 On the remote machine to send a message to all users ( Chen Xu ) Use rwall( Write to all remote ) Command while sending a message to all users of the network . rwall hostname file When using the CDE or OpenWindows Other window system, each window is seen as a single login ; If the user is logged more than once then send the message directly to the control window . 1171 To the network to send a message to all users ( Chen Xu ) Send a message to all users of the network 1) Enter rwall-n netgroup and Enter 2) Enter the message to be sent 3) End of the press "Control-d" key , Messages that each user in the system to display the control window, the following are the system administrator send an announcement to the network group Eng Examples of each user : % rwall -n EngSystem will be rebooted at 11:00.(Control-d) % User control in the message window :Broadcast message from root on console-System will be rebooted at 11:00.EOF Note : You can also rwall hostname( Host Name ) Command to all users of the system . 1172 I need to compile the kernel, the kernel source, where ?(platinum) 1. General release of the plate has, for example RedHat, Usually in the second. On the third 2.4 Called the kernel kernel-source-2.4.xx-xx.rpm 2.6 Called the kernel kernel-devel-2.6.xx-xx.rpm 2. To download a copy of your favorite 1173 The top of the results output to a file (bjweiqiong) top -d 2 -n 3 -b >test.txt Can be the result of every top 2 Seconds, print 3 Times, so the back page of the process can also be seen 1174 vim Full-sensitive approach to change ( Chen Xu ) Cursor on the text at the beginning gUG All letters become uppercase guG All letters become lowercase g~G All letters, uppercase lowercase change , Change uppercase lowercase 1175 How to upgrade installation ubuntu( Chen Xu ) With ubuntu 7.04->7.10 Example . mount -o loop /media/ubuntu-7.10-alternate-i386.iso /cdrom gksu "sh /cdrom/cdromupgrade" If agent : export http_proxy=; gksu "sh /cdrom/cdromupgrade" 1176 File uneven segmentation method (qintel) $dd if=source of=target.1 bs=1M count=10 $dd if=source of=target.2 bs=1M skip=10 source And is divided into target.1 target.2 Two documents, which target.1 For the source of the former 10M Part :target.2 For the source of the minus 10M After some . 1177 I do not care to under Windows swap Partition formatted, is there any command to restore the ( Chen Xu ) Established using the mkswap command swap Partition, then use swapon Command to enable swap partition . The use of the command, for example, the following : # mkswap /dev/sda7 # swapon /dev/sda7 1178 How to modify a file to prevent others ( Chen Xu ) The system in some of the key documents and important personal information, you can file permissions to protect , For example, the file attribute to 600 addition , If you are using a Linux ext2 Or ext3 file system , You can also use "chattr" command , With i attributes to the file , Even if the root user can not modify or delete these files directly , To prevent accidental changes from happening. The specific command as follows : # chattr +i passwd I use the following command to remove property : # chattr - i passwd 1179 Batch change the extension ( Bai Qingjie ) for i in *.mp3; do mv $i `basename $i .mp3`.bak ;done To will. Mp3 at the end of the file is renamed .mp3.bak Ending
-- Network-related articles -------------------------- 2001 To allow apache's default character set into Chinese ( Chen Xu ) vi httpd.conf, Find AddDefaultCharset ISO-8859-1 line apache Version if it is 1.*, To AddDefaultCharset GB2312 If 2.0.1-2.0.52, to AddDefaultCharset off Then run / etc / init.d / httpd restart restart apache To take effect . Note : For the 2.0.53 or later , Does not require any configuration, can support Chinese . 2002 Permanent change ip( Chen Xu ) ifconfig eth0 New ip Then edit / etc/sysconfig/network-scripts/ifcfg-eth0, modify ip 2003 From the remote display on Linux Windows Desktop (lnx3000) Install rdesktop package 2004 Manually add the default gateway ( Chen Xu ) As the root user , Execution : route add default gw Gateway IP Want to change the gateway 1 vi /etc/sysconfig/network-scripts/ifcfg-eth0 Change GATEWAY 2 /etc/init.d/network restart 2005 redhat 8.0 And on msn qq( Chen Xu ) Download the version of Gaim 0.58 : gaim-0.58-2.i386.rpm Download plug-QQ for gcc2.9 Version : libqq-0.0.3-ft-0.58-gcc296.so.gz The downloaded file into the / temp directory , Then the system will delete the existing Gaim , That the terminal emulator, type the command :rpm -e gaim. Start the installation Open a terminal emulator, to run the following command to install Gaim 0.58 Version, that is : cd /temp ( Into the temp directory ) rpm -ivh gaim-0.58-2.i386.rpm ( Installing software ) When the installation is successful, you can GNOME Or KDE desktop build Gaim Icons . Plug-ins to install QQ , That is, type the command : gunzip libqq-0.0.3-ft-0.58-gcc296.so.gz ( Unzip the file ) cp libqq-0.0.3-ft-0.58-gcc296.so /usr/lib/gaim ( Gaim plugin to copy the library directory ) Software settings When you first start Gaim 0.85 version , The login screen will appear. First choice " Plug-ins "in the plug-in dialog box, click " Load ", respectively, libmsn.so And libqq-0.0.3-ft-0.58-gcc296.so file into , Confirm and close and then select " All accounts, "In the account editor to click " Increase ", when there account page changes , We can enter their own QQ or MSN Number, and fill in login name QQ Number or MSN mail , Fill in the corresponding QQ or password MSN Password, Alias fill out their own nickname , QQ or select the appropriate protocol MSN, The other set by default to when the log after the completion of all the settings used . As the MS. msn The agreements often escalated, resulting in linux And on gaim msn Plug-ins must be upgraded, there is no foolproof solution to the current , Please forgive me 2006 Find out what the program is now running 22 ports ( Chen Xu ) lsof -i 2007 View this machine IP,gateway, dns( Chen Xu ) IP: Log in as root , Execute ifconfig. Which eth0 Is the first NIC, lo is the default device Gateway: Log in as root , Execute netstat-rn, to 0.0.0.0 The beginning of a line of Gateway is the default gateway You can also view / etc / sysconfig / network file , Inside the specified address ! DNS: more /etc/resolv.conf, Content specified as follows : nameserver 202.96.69.38 nameserver 202.96.64.38 2008 RH8.0 Ping command line to change the TTL Value (cgweb,lnx) Method 1( Effective after restart ): #sysctl -w net.ipv4.ip_default_ttl=N (N=0~255), If N>255, Then ttl=0 Method 2( Invalid after reboot ): #echo N(N As 0-255) > /proc/sys/net/ipv4/ip_default_ttl 2009 On the LINUX IP Forward (houaq) Edit / etc / sysctl.conf, such as , Will net.ipv4.ip_forward = 0 Becomes net.ipv4.ip_forward = 1 Take effect after the restart, with sysctl -a View shows 2010 mount Other windows machines on the LAN to share a directory ( Chen Xu ) mount -t smbfs -o username=guest,password=guest //machine/path /mnt/cdrom 2011 Allow | Prohibited by root SSH Land (Fun-FreeBSD) Modify sshd_config:PermitRootLogin no|yes 2012 Allow direct root telnet Land ( Chen Xu ,platinum) Method 1: Edit / etc / pam.d / login, to remove auth required /lib/security/pam_securetty.so This sentence Method 2: vi /etc/securetty Add pts/0 pts/1 ... 2013 Received in linux adsl Equipment (wind521) Need a functioning Linux + at least one card + Application of broadband equipment has been completed, but has been opened . There are several currently on the market about ADSL equipment , They work the way some of the subtle differences . Is accomplished through the virtual dial-up Internet access in the process, that is, using pppoe Equipment to carry out the virtual dial-up called omnidirectional cat, is a power automatically dial after work , Our interface is then left to RJ45, Dalian are generally left to our gateway 10.0.0.2, The device most likely to deal with, and finally assigned to the user directly to a fixed IP, Is relatively easier to deal with all 1. The first is the need for dial-up : These types of devices through eth interfaces to communicate with the computer , So first make the connection hardware, especially broadband cat , Must confirm the correct ( Otherwise, not a moment to not be my thing ) Then start the system, verify that the system is installed on rp-pppoe This software ( By rpm -qa|grep pppoe To find ), If not installed users in the CD or go online down By one, after the installation , As the root user to perform adsl-setup, This information into a set state adsl , Asked to enter a user name for broadband and other information to confirm there is no problem , Accepted until the last ( Which are the E text , However, a look that can understand, relatively simple , About a firewall setting, I generally do not have , Select 0, we can consider specific ). After configuration, the root Users to perform adsl-start, this will be adsl Dial-up work, it will look normal on-line , If you have any specific questions, take a look the log (/var/log/messages) Which tells you what . Stopped adsl, implementation adsl-stop On it ( Very simple ) 2. Easier to deal with the other two : All the cats : As long as your network card's IP settings to a 10 Segment of the IP, and gateway refers to all the cats IP, On (10.0.0.2), Basically do not have much of a problem Fixed IP: As configuring the network card as the local children, will IP, Gateway, DNS is an application to fill in on press can handle a 2014 To automatically synchronize time linux (shunz) vi /etc/crontab With a : 00 0 1 * * root rdate -s time.nist.gov 2015 linux What online resources ( Chen Xu ) Foreign(flying-dance big big pig).[url][/url] Domestic 2016 Change sshd port ( Chen Xu ) In the / etc / ssh / sshd_config add a line :Port 2222,/etc/init.d/sshd restart Restart the daemon 2017 To change the telnet port ( Chen Xu ) The / etc / services file telnet The port number corresponding to the value you want 21 ,/etc/init.d/xinetd restart Restart the daemon 2018 Terminal mode problem (sakulagi) export TERM=vt100 2019 Imitation HyperTerminal, LINUX in the procedure to connect the router and switch (alstone) minicom 2020 ssh Can not fail to automatically break up (wind521, Pig eyelid ) Modify your HOME directory .bash_profile File, together with export TMOUT=1000000 ( In seconds ) Then run source .bash_profile 2021 What to do with the intrusion detection tool ( Chen Xu ) snort 2022 Linux Memory leak detection program under the tools ( Chen Xu ) cchecker Or efence library can 2023 linux How to monitor all the data card through the machine ( Chen Xu ) tcpdump Or iptraf 2024 Why do a lot of commands as root say command not found( Chen Xu ) You telnet up , Then su to root Of it, to change to change your su Command format, should be su - root 2025 Close the user's POP3 access (tiansgx) The POP3 port closed on it . In the file / etc / services to find the line pop-3 110/tcp Before this line to add a '#', It commented on it . 2026 linux The following play a flash animation (myxfc) linux The following play a flash animation with this thing , Will not cause the browser to turn off ( Well with other plug-ins ) First, download the flash player animation linux Plug-ins ... /flash_linux.tar.gz tar zxvf flash_linux.tar.gz Open the package, see Linux Folder In linux, there are two files file cheek libflashplayer.so And shockwaveflash.class, these two files are copied to your browser's plug-in ( Not the same as the browser, plug-ins may not be the same location ) /usr/lib/mozilla-1.0.1/plugins, On it 2027 Lock wu-ftp user directory (wangla) Edit ftpaccess file restricted-uid * This is a very important limiting ftp Users in their own directory . 2028 How to prevent the server telnet( Zhiqiu leaf ) Must start the telnet service on the server && Server firewall should be set to low priority 2029 Prevent anyone from wheel Group . 2030 How to make the lynx browser to browse Chinese website (Ghost_Vale) View Simplified Chinese website on the following set of changes Save options to disk: [X] Display and Character Set Display character set : [Chinese________________________] Assumed document character set(!): [iso-8859-1______] CJK mode (!) : [ON_] Then moved to the bottom of the press Accept Changes Enter Save on it Of course, your system can only be to support Simplified Chinese 2031 Card activated, but not on the net , How to do ?(Slock, Pig eyelid ) traceroute, Look in the end is that one is standing in the way of . 1.ping Own 2.ping Gateway 3.ping DNS 4.traceroute DNS If everything is normal nslookup ping sina Of address traceroute sina Of address Basically you can know the result 2032 With the next redhat9 samba,win2000 Access, win98 can not access ?(squall2003) If it is necessary to modify the registry wind98 :HKEY_LOCAL_MACHINE/system/correntcontrolset/services/Vxd/VNETSUP Built under a D value :EnablePlainTextpasswd, Key 1 2033 How to get network card's MAC address ( Chen Xu ,hutuworm) arp -a | awk '{print $4}' ifconfig eth0 | head -1 | awk '{print $5}' 2034 How to get the IP address of network card The next card to bind multiple ip . A network card bound to another multi-ip law (hotbox) In the / etc / sysconfig / network-scripts / Create a file :ifcfg-ethX-rangeX ("X" For the card number ) File content : IPADDR_START=<start ip> IPADDR_END=<end ip> CLONENUM=0 To 256 ip 2037 How to bind a ip two network cards (hutuworm) 192.168.0.88 is the assumption 192.168.1.0/24( Pig eyelid ) It is equivalent with 192.168.1.0/255.255.255.0 , Just said in different ways .... 2039 linux Under the command clear arp table (NetDC) #arp -d -a( For bsd) for HOST in `arp | sed '/Address/d' | awk '{ print $1}'` ; do arp -d $HOST; done 2040 Protocol from the server using ntp time synchronization (NetDC) ntpdate NTP-SERVER Case :ntpdate 172.16.2.1 2041 host Command usage ( Chen Xu ) host Can be used to query the domain name, it can get more information host -t mx example.com You can check out for example.com MX Records, and handling mail The host name host -l example.com Will return all registered domain names under the example.com host -a example.com This will show all the host domain name information . 2042 Immediately so that LINUX support NAT(platinum) echo 1 > /proc/sys/net/ipv4/ip_forward iptables -t nat -I POSTROUTING -j MASQUERADE 2043 rh8.0 Set rcp usage under (zhqh1) | http://www.codeweblog.com/q-reproduced-wonderful-word-linux/ | CC-MAIN-2015-40 | refinedweb | 10,022 | 57.91 |
Groovy Development
About this Article
Unlike many of my previous articles, I decided not to make this a click-along. There is so much to talk about in the Groovy language that I did not want to get too sidetracked in explaining the SQL database setup, or creating a framework to demonstrate it all.
I can tell you, however, that this information is based on my own experience constructing such a framework for a project at work. We needed a quick and easy way to construct translators (importers and exporters, if you prefer) for getting data in and out of a database schema. In many cases, the export (or import) was to (or from) an XML file.
To illustrate, the system constructed was a workflow system that interfaced with external agencies using various XML formats. Using the data in the database, an XML schedule file was formed and sent out to the company members, who would then examine it and provide a response, also in XML. The response had some identifying information relating to the data originally sent out, and then could contain a number of different responses. For one, a problem with the data could be signaled, and it might be specific to a certain series in the outgoing schedule, or even an individual value. For another, our system needed a certain "response code" field to be set based on the response data code in combination with the anomalies signaled.
For example, if the response code is G29, and one of the data series is marked as having inconsistent values, our response code is -210. Otherwise, if G29 is marked, but no data is identified as problematic, set the response code to -200 (really, these are made-up numbers, but hopefully they show the kind of business rule that was needed).
So, we are faced with the possibility of using a simple and fast mapping tool to get the data in, and then doing a separate post-processing step to apply all of the business logic, or of using a more sophisticated language for the whole process, with Java being high on the list because the rest of the application is already written in Java.
What Is Groovy?
Around the same time we were looking at this problem, I was following the development of a new language called Groovy (a name that is the language's worst enemy, in my opinion, because I was the one who had to pitch the use of something called "Groovy" to write our translation engine and it was a hard sell because of the name alone). Groovy also can be referred to as JSR-241, which is far more boring, but also much more acceptable in a corporate setting.
Groovy is a scripting language that is largely compatible with Java syntax. (And when I say that, I mean that there are very few things you can write in Java that will break Groovy, one curious and notable exception being the for loop that has been simplified.) You can either interpret or compile Groovy, and compiled Groovy code can be packaged up into jars that look just like Java code, but will run slower than Java.
Why Use Groovy?
So, if the language has such similar syntax to Java and is slower, why not just use Java? Well, just because Groovy can understand straight Java code, it doesn't mean that is all it can understand. Normal Java requires a lot of strong typing and compile time checking that mean that (unless you use reflection) many of the neat shortcuts that dynamic scripting languages are hard or require a lot of extra code (like reflection code).
Although Groovy will compile strongly typed code quite happily, you can also drop the typing, so that something like:
String myStr = "Hello world";
can become
myStr = "Hello world";
Also, a method definition like:
public int myMethod(boolean flag, String greeting, double mult) {
can become
def myMethod(flag, greeting, mult) {
Also, things such as loops have been simplified a great deal:
for(int i=0; i<100; i++) {
becomes
for (i in 0..99) {
Ok, so nothing earth shattering so far, but Groovy doesn't stop there. For one thing, it has all sorts of shorthand syntax that saves a lot of time. Some examples (but not all by far) include:
- Native list and map syntax
- Closures (you can think of a closure very loosely as a method with no name or formal definitiona code block, if you prefer)
- Excellent iteration syntax ( list.each(), for (i in 1..10) )
- Incredibly concise XML and SQL syntax support, including Markup
All of these features will be covered in this article, but it is this last point that really convinced me to to try Groovy for our translators. As it turned out, it was a very good choice.
Getting Groovy
OK, before going any further, you may be wondering where you can find Groovy.
Groovy's home is, and the latest version can be found at (the link is already sorted with most recent at the top).
Installation is easy; just choose the gz or zip file (depending on your preferencenote also that you can pick up the src distros if you want to; but to start with, grab one that does not have src in the name) and unpack it onto your machine somewhere. I then recommend adding the bin directory to your PATH environment variable so that the machine can execute the compiler and shells. Try it from the command line by typing groovysh; you should see something like this:
Lets get Groovy! ================ Version: 1.0-jsr-03 JVM: 1.4.2_06-b03 Type 'exit' to terminate the shell Type 'help' for command help Type 'go' to execute the statements
Type exit to get out of ityou are ready to go Groovy.
The Console and JEdit
Groovy has a very useful tool, called the Groovy Console, that comes with it. You can start it by typing GroovyConsole at the command line and you should see a window come up with an upper and a lower pane. The upper pane can be used to type in Groovy code to try out, and the bottom pane is the groovy shell and shows execution traces. Note that any output to standard out or standard error will go not to the bottom pane, but to the standard output in the command line window.
The Groovy console is extremely useful. If you are trying to develop some snippet of useful, Groovy code, this is the place to do it. Once you have edited the code you want to run, just go to the Actions menu and select Run. It will either run the code snippet, or explain to you why it couldn't. It's very basic compared with a full Java IDE, but it is very useful to just try out some ideas.
In this example, you have some code that could be Java (except from the test part not needing to be enclosed in a public static void main() construct). If you run it, you should see "Hello Dr. Livingstone" written to the standard output in the command line you called GroovyConsole from.
I would also like to mention JEdit here; if you have never used JEdit, I strongly recommend it. You can download it from and it has Groovy syntax coloring. Again, this is a far cry from a full IDE environment but those will be improved over time. In the meantime, I tend to use either JEdit or NetBeans with the Groovy plugin available from and there is also an Eclipse plugin for Groovy available at.
Moving on to the real meat of the article... As a Groovy neophyte, the first problem I found was that the documentation is a bit sparse at the moment. It is for this reason that I want to delve into at least those features of the language that I found useful for the translators I wrote, in the hope that it will provide a starting point for people and give them a bit of a leg up. I am sure there will be holes because I treat Groovy like most other things I deal with on a daily basisa tool to solve a problem, and often once I have solved the problem, I move on to the next problem and come back to the tool later.
Page 1 of 3
| http://www.developer.com/lang/article.php/3548721/Groovy-Development.htm | CC-MAIN-2015-22 | refinedweb | 1,405 | 64.24 |
I cannot get the following code to compile:
The problem is the V2.push_back(array[i])The problem is the V2.push_back(array[i])Code:include <vector> #include <iostream> using namespace std; int WeirdProduct( const vector<float> & V1, const vector<float> & V2) { int product = 1, minsize; if( V1.size() < V2.size()) minsize = V2.size(); for(int i=0; i < minsize; i++) if( V2[i] < 0 ) product = product * i; return product; } void main () { const vector<float> V1(4); const vector<float> V2; float array[]={42.3,21.5,-3.1,-4.2,155.8,33.7,-1.9}; for(int i=0; i<=7; i++) V2.push_back(array[i]); WeirdProduct(V1,V2); }
line in void main. The error received when trying to compile is :
weird.cpp: In function `int main(...)':
weird.cpp:21: passing `const vector<float,allocator<float> >' as `this' argument of `voi
d vector<float,allocator<float> >:
ush_back(const float &)' discards qualifiersush_back(const float &)' discards qualifiers
Which I presume is an issue with data types of some sort. I am trying to insert the data from a c style array into a vector array via the for loop based upon the value of i, any help would be much appreciated.
Code tags added by Kermi3 | https://cboard.cprogramming.com/cplusplus-programming/27500-vector-t-help.html | CC-MAIN-2017-34 | refinedweb | 206 | 58.48 |
Creating an OpenSearch Description File in Windows Federated Search
Describes how to create an OpenSearch Description (.osdx) file to connect external data stores to the Windows Client via the OpenSearch protocol. Federated search enables users to search a remote data store and view the results from within Windows Explorer.
This topic contains the following sections:
- OpenSearch Description File
- Standard Elements in Windows Federated Search
- Extended Elements in Windows Federated Search
- Previews
- Open File Location Menu Item
- Additional Resources
- Related topics
OpenSearch Description File
An OpenSearch Description (.osdx) file for Windows Federated Search must abide by the following rules:
- Be a valid OpenSearch Description document, as defined by the OpenSearch 1.1 specification.
- Provide a URL template with either an RSS or an Atom format type.
- Use the .osdx file name extension, or be associated with the .osdx file name extension when downloading from the web. For example, a server is not required to use .osdx. A server can return the file with any file name extension, such as .xml for example, and treated as if it were an .osdx file if it uses the correct MIME Type for OpenSearch Description documents (.osdx files).
- Provide a ShortName element value (recommended).
Mininum Required Child Elements
The following example .osdx file consists of ShortName and
Url elements, which are the minimum required child elements.
Standard Elements in Windows Federated Search
In addition to the minimum child elements, federated search supports the following standard elements.
Shortname
Windows uses the ShortName element value to name the .searchconnector-ms (search connector) file that is created when the user opens the .osdx file. Windows ensures that the generated file name uses only characters that are allowed in Windows file names. If no ShortName value is provided, the .searchconnector-ms file tries to use the file name of the .osdx file instead.
The following code illustrates how to use the ShortName element in an .osdx file.
Description
Windows uses the Description element value to populate the file description shown in the Windows Explorer details pane when a user selects a .searchconnector-ms file.
URL Template for RSS/Atom Results
The .osdx file must include one Url format element and template attribute (a URL template) that returns results in either RSS or Atom format. The format attribute must be set to
application/rss+xml for RSS formatted results, or
application/atom+xml for Atom formatted results, as shown in the following code.
Note The Url format element and template attribute are commonly known as a URL template.
URL Template for web Results
If there is a version of the search results that can be viewed in a web browser, you should provide a Url format=
text/html element, and template attribute, as shown in the following code.
If you provide a Url format="text/html" element and template attribute, a button appears in the Windows Explorer command bar, as shown in the following screen shot, that enables the user to open a web browser to view the search results when the user performs a query.
The roll-over of the query back to the data store's web UI is important in some scenarios. For example, a user may want to view more than 100 results (the default number of items the OpenSearch provider requests). If so, the user may also want to use search features that are available only on the data store's website, such as re-querying with a different sort order, or pivoting and filtering the query with related metadata.
URL Template Parameters
The OpenSearch provider performs always the following actions:
- Uses the URL template to send the request to the web service.
- Attempts to replace the tokens found in the URL template before sending the request to the web service, as follows:
- Replaces the standard OpenSearch tokens that are listed in the following table.
- Removes any tokens that are not listed in the following table.
Paged Results
You may want to limit the number of results returned per request. You can opt to return a "page" of results at a time, or to have the OpenSearch provider get additional pages of results either by item number or page number. For example, if you send twenty results per page, the first page you send starts at item index 1 and at page 1; the second page you send starts at item index 21 and at page 2. You can define how you want the OpenSearch provider to request items by using either the
{startItem} or the
{startPage} token in the URL template.
Paging Using the Item Index
An item index identifies the first result item in a page of results. If you want clients to send requests using an item index, you can use the
{startIndex} token in your Url element template attribute, as shown in the following code.
The OpenSearch provider then replaces the token in the URL with a starting index value. The first request starts with the first item, as illustrated in the following example:
The OpenSearch provider can get additional items by changing the
{startIndex} parameter value and issuing a new request. The provider repeats this process until it gets enough results to satisfy its limit, or reaches the end of the results. The OpenSearch provider looks at the number of items returned by the web service in the first page of results, and sets the expected page size to that number. It uses that number to increment the
{startIndex} value for subsequent requests. For example, if the web service returns 20 results in the first request, then the provider sets the expected page size to 20. For the next request, the provider replaces
{startIndex} with the value of 21 to get the next 20 items.
Note If a page of results returned by the web service has fewer items than the expected page size, then the OpenSearch provider assumes it has received the last page of results and stops making requests.
Paging Using the Page Index
A page index identifies the specified page of results. If you want clients to send requests using a page number, you can use the
{startPage} token in your Url format element template attribute to indicate that, as illustrated in the following example:
The OpenSearch provider then replaces the token in the URL with a page number parameter. The first request starts with the first page, as shown in the following example:
Note If a page of results returned by the web service has fewer items than the expected page size, then the OpenSearch provider assumes it has received the last page of results and stops making requests.
Page Size
You may want to configure your web service to permit a request to specify the size of the pages by using some parameter in the URL. A request must be specified in the .osdx file by using the
{count} token, as follows:
The OpenSearch provider can then set the desired page size, in number of results per page, as shown in the following example:
By default the OpenSearch provider makes requests using a page size of 50. If you want a different page size, then do not provide a
{count} token, and instead place the desired number directly in the Url template element.
The OpenSearch provider determines the page size based on the number of results returned on the first request. If the first page of results received has fewer items than the count requested, the provider resets the page size for any subsequent page requests. If subsequent page requests return fewer items than requested, the OpenSearch provider assumes that it has reached the end of the results.
Extended Elements in Windows Federated Search
In addition to the standard elements, federated search supports the following extended elements: MaximumResultCount and ResultsProcessing.
Because these extended child elements are not supported in the OpenSearch v1.1 specification, they must be added by using the following namespace:
Maximum Result Count
By default, search connectors are limited to 100 results per user query. This limit can be customized by including the MaximumResultCount element within the OSD file as shown in the following example:
The preceding example declares the namespace prefix
ms-ose in the top-level OpenSearchDescription element, and then uses it as a prefix in the element name. This declaration is required because the MaximumResultCount is not supported in the OpenSearch v1.1 specification.
Property Mapping
When results are returned by the web service as an RSS or Atom feed, the OpenSearch provider must map the item metadata in the feeds to properties that the Windows Shell can use. The following screen shot illustrates how the OpenSearch provider maps some of the default RSS elements.
Default Mappings
The default mappings of RSS XML elements to Windows Shell system properties, are listed in the following table. XML paths are relative to the item element. The
"media:" prefix is defined by the Yahoo Search Namespace namespace.
Note In addition to the default mappings of standard RSS or Atom elements, you can map other Windows Shell system properties by including additional XML elements in the Windows namespace for each of the properties. You can also map elements from other existing XML namespaces such as MediaRSS, iTunes, and so forth, by adding custom property mapping in the .osdx file.
Custom Property Mappings
You can customize the mapping of elements from your RSS output to Windows Shell system properties by specifying the mapping in the .osdx file.
The RSS output specifies:
- An XML namespace, and
- For any child element of an item, an element name to map against.
The .osdx file identifies a Windows Shell property for each element name in a namespace. The property mappings that you define in your .osdx file override the default mappings, if they exist, for those specified properties.
The following diagram illustrates how an RSS extension maps to Windows properties (canonical name).
Example RSS results and OSD Property Mapping
The following example RSS output identifies as the XML namespace with the prefix "example". This prefix must appear again before the email element.
In the following example .osdx file, the XML email element maps to the Windows Shell property System.Contact.EmailAddress.
<OpenSearchDescription xmlns="" xmlns: ... <ms-ose:ResultsProcessing <ms-ose:PropertyMapList> <ms-ose:PropertyMap <ms-ose:Source <ms-ose:Property </ms-ose:Source> </ms-ose:PropertyMap> </ms-ose:PropertyMapList> </ms-ose:ResultsProcessing> ... </OpenSearchDescription>
There are some properties that cannot be mapped because values for them are either overridden later or are not editable. For example, System.ItemFolderPathDisplay or System.ItemPathDisplayNarrow cannot be mapped because they are calculated from the URL value provided in either the link or enclosure elements.
Thumbnails
Thumbnail image URLs can be provided for any item by using the media:thumbnail url="" element. The ideal resolution is 150 x 150 pixels. The largest thumbnails supported are 256 x 256 pixels. Providing larger images takes more bandwidth for no extra benefit to the user.
Open File Location Context Menu
Windows provides a shortcut menu named Open file location for result items. If the user selects an item from that menu, the "parent" URL for the selected item is opened. If the URL is a web URL, such as
http://..., the web browser is opened and navigated to that URL. Your feed should provide a custom URL for each item to ensure that Windows opens a valid URL. This can be accomplished by including the URL within an element inside the item's XML, as illustrated in the following example:
<rss version="2.0" xmlns: ... <item> <title>Someone</title> <link></link> <win:System.ItemFolderPathDisplay> </win:System.ItemFolderPathDisplay> </item> ...
If this property is not explicitly set in the item's XML, the OpenSearch provider sets it to the parent folder of the URL of the item. In the example above, the OpenSearch provider would use the link value, and set the System.ItemFolderPathDisplay Windows Shell property value to
"".
Customize Windows Explorer Views with Property Description Lists
Some Windows Explorer view layouts are defined by property description lists, or proplists. A proplist is a semicolon-delimited list of properties, such as
"prop:System.ItemName; System.Author", that is used to control how your results appear in Windows Explorer.
The UI areas of Windows Explorer that can be customized by using proplists are illustrated in the following screen shot:
Each area of Windows Explorer has an associated set of proplists, which themselves are specified as properties. You can specify custom proplists for individual items in your result sets or for all items in a set of results.
To specify a unique proplist for an individual item:
- In your RSS output, add a custom element representing the proplist you want to customize. For example, the following example sets the list for the details pane:
To apply a property to every item in the search results without modifying the RSS output, specify a proplist within an ms-ose:PropertyDefaultValues element in the .osdx file, as shown in the following example:
<ms-ose:ResultsProcessing <ms-ose:PropertyDefaultValues> <ms-ose:Propertyprop:~System.ItemNameDisplay;System.Photo.DateTaken; ~System.ItemPathDisplay;~System.Search.AutoSummary;System.Size;System.Author;System.Keywords</ms-ose:Property> </ms-ose:PropertyDefaultValues> </ms-ose:ResultsProcessing>
Content View Mode Layout of Properties
The list of properties specified in the System.PropList.ContentViewModeForSearch and System.PropList.ContentViewModeForBrowse proplists determines what is shown in Content view mode. For more information about property lists, see PropList.
The properties are laid out according to the numbers shown in the following layout pattern:
If we use the following list of properties,
Then we see the following display:
Note For the best readability, the properties shown in the right-most column should be labeled.
Property List Flags
Only one of the flags defined in the proplists documentation applies to the display of items in Content View mode layouts:
"~". In the previous examples, the Windows Explorer view labels some of the properties, such as
Tags: animals; zoo; lion. That is the default behavior when you specify a property in the list. For example, the proplist has
"System.Author" which is displayed as
"Authors: value". When you want to hide the property label, place a
"~" in front of the property name. For example, if the proplist has
"~System.Size", the property is displayed as just a value, without the label.
Previews
When the user selects a result item in Windows Explorer and the preview pane is open, the content of the item is previewed.
The content to show in the preview is specified by a URL, that is determined as follows:
- If the System.WebPreviewUrl Windows Shell property is set for the item, then use that URL.
Note The property needs to be provided in the RSS by using the Windows Shell namespace, or explicitly mapped in the .osdx file.
- If not, then use the link URL instead.
The following flowchart shows this logic.
It is possible to use a different URL for the preview than for the item itself. This means that if you provide different URLs for the link URL and the enclosure or
media:content URL, Windows Explorer uses the link URL for previews of the item but uses the other URL for file type detection, opening, downloading, and so forth.
How Windows Explorer determines what URL to use:
- If you provide a mapping to System.ItemFolderPathDisplay, then Windows Explorer uses that URL
- If you do not provide a mapping, then Windows Explorer identifies whether the link and enclosure URLs are different. If so, then Windows Explorer uses the link URL.
- If the URLs are the same or if there is only a link URL, then Windows Explorer parses the link to find the parent container by removing the file name from the full URL.
Note If you recognize that the URL parsing would result in dead links for your service, you should provide an explicit mapping for the property.
Open File Location Menu Item
When a right-clicks an item, the Open file location menu command appears. This command takes the user to the container for or location of that item. For example, in a SharePoint search, selecting this option for a file in a document library would open the document library root in the web browser.
When a user clicks Open file location, Windows Explorer attempts to find a parent container, by using the logic shown in the following flowchart:
- Following Best Practices in Windows Federated Search
- Deploying Search Connectors in Windows Federated Search
Send comments about this topic to Microsoft
Build date: 10/27/2012 | http://msdn.microsoft.com/en-us/library/dd940453(VS.85).aspx | CC-MAIN-2013-20 | refinedweb | 2,748 | 52.29 |
I believe my problem has to do with points. The whole story is I am trying to create a blackjack program for my class. I planned on creating 2 linked lists, one empty one with the deck of cards. As cards are dealt they are put into the second linked list and taken from the first so that they are not repeated.
After creating what I thought was a working linked list I wrote the code to populate the linked list. Card is a structure with data members. One int 0-3 for suit and another int 0-12 denoting rank. It compiles, however upon debugging I get an error saying
First-chance exception at 0x00411964 in BlackJack.exe: 0xC0000005: Access violation reading location 0x00000008.
Unhandled exception at 0x00411964 in BlackJack.exe: 0xC0000005: Access violation reading location 0x00000008.
The program breaks at line 60, q->next=start->next
I'm fairly sure this is an issue with my usage of pointers as I'm very new to them.I'm fairly sure this is an issue with my usage of pointers as I'm very new to them.Code:void LinkedList::insert(Card C1) { Node *q; q = new Node; q->next=start->next; q->C=C1; start->next=q; }
The entire code is as follows
Code:#include <conio.h> #include <iostream> using namespace std; struct Card { int suit; int rank; }; ///////////////////////////////////////Begining of Linked List///////////////// class LinkedList { private: struct Node { Card C; Node *next; }*start,*start2,*end; public: LinkedList(); void insert(Card C1); Card fetch(int N); void shuffle(); }; LinkedList::LinkedList() { start = NULL; start2=NULL; } ////////////////////////////////Insert///////////////////////// void LinkedList::insert(Card C1) { Node *q; q = new Node; q->next=start->next; q->C=C1; start->next=q; } ////////////////////////////////////////////////Fetch////////////////////////// Card LinkedList::fetch(int N) { int counter=-1; Node *q,*t; q = start; while (counter!=N) { t=q; q=q->next; } if(q->next!=NULL) { start2->next=q; t->next = q->next; return q->C; } else { start2->next=q; t->next=NULL; return q->C; } } ////////////////////////////Remake Deck void LinkedList::shuffle() { LinkedList empty; while (start2->next!=NULL) { empty.insert(start2->next->C); start2=start2->next; } } int main() { Card c,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,D1,D2,D3,D4,D5,D6,D7; LinkedList l1; int counter1=0,counter2=0; ///////////////populate list/////////////// while (counter1!=4) { while (counter2!=13) { c.suit=counter1; c.rank=counter2; l1.insert(c); ++counter2; } counter2=0; ++counter1; } P1=l1.fetch(2); cout<<P1.suit<<endl<<P1.rank; cout<<"Hello world"; _getche(); } | http://cboard.cprogramming.com/cplusplus-programming/113833-issue-points.html | CC-MAIN-2014-52 | refinedweb | 413 | 73.68 |
Inactive records: the value objects your app deserves
Hop into a typical Rails app’s source code or git history and you’ll see that its ActiveRecord::Base subclasses are a real nexus of behaviour and logic. You’ll likely find yourself reaching over to these classes and making changes as you work on any part of the app. They have a lot of responsibility, and in many ways, they feel like the backbone of a Rails app.
These classes also have another characteristic that can spread design difficulties throughout your app: they have mutable state. Your ActiveRecord subclasses can:
- Be created brand new with empty attributes,
- Come freshly loaded from the database,
- Have their attributes modified in memory but not yet persisted to the database,
- Hold invalid attributes,
- Have their associations preloaded from the database…
- Or not!
- Or even have new associations built in memory but not yet persisted to the database.
This is a scary list. If you’re working with an ActiveRecord object, you never really know what you’re working with.
These issues don’t originate in the ActiveRecord library alone. They come part and parcel along with the “active record” pattern on which the library is modelled. As Bob Martin puts it:
It creates confusion about these two very different styles of programming. A database table is a data structure. It has exposed data and no behavior… [But] many people put business rule methods in their Active Record classes; which makes them appear to be objects. This leads to a dilemma. On which side of the line does the Active Record really fall? Is it an object? Or is it a data structure?
This conflation of roles leads to incredibly complex behaviour and an enormous amount of responsibility situated in a very small number of classes at the core of your app. This is not what we want.
As I mentioned in my last post, we’ve switched to ROM for database persistence in our apps. But this doesn’t mean we’ve stopped modelling our entities entirely. Instead, we’ve taken these previously active records and made them inactive. We’ve turned them into value objects.
What’s a value object? A value object is one whose notion of equality is based on the values of the attributes it contains, not its object identity. Most importantly, a good value object is immutable: you cannot change any attribute within an existing value object.
Many of the definitions for value objects use examples like monetary values or date ranges. However, this is not the extent of their usefulness for modelling data. In our apps, some of the things we have as value objects are Article, ArticleWithContributors, and Category. These are the app’s main domain entities, and exactly the kind of things you might otherwise expect to find as ActiveRecord subclasses.
Building value objects in Ruby is straightforward. We need to satisfy these two requirements:
- Make the objects immutable. Don’t provide attr writers or any other methods to mutate the object’s internal state.
- Provide equality methods that use the object’s attributes.
Here’s how a simple one looks:
require "dry-equaliser"
class Article
include Dry::Equalizer(:id, :title, :body)
attr_reader :id, :title, :body
def initialize(attrs = {})
@id = attrs.fetch(:id)
@title = attrs.fetch(:title)
@body = attrs.fetch(:body)
end
end
We build a lot of these, so we use dry-types to reduce boilerplate and give us stricter type expectations (more on that in a future article):
require "types"
class Article < Dry::Types::Struct
attribute :id, Types::Strict::Int
attribute :title, Types::Strict::String
attribute :body, Types::Strict::String
end
An added bonus of a value object made using a Dry::Types::Struct is that it cannot be initialized with invalid data. In this case, an Article is an Article is an Article. It’ll work as advertised, every single instance, every single time.
(Technically, these examples are entities rather than strict value types, because we include the record IDs in their attributes, which you’d expect to be the key indicator of equality. However, in practice, Dry::Types::Struct instances still check for equality across all attributes, and in our apps we only ever instantiate these objects from known-good database data, which means they still behave effectively as value objects. So let’s continue!)
Value objects like this allow you to work much more confidently in building your app. You know exactly what information they will contain and the behaviour they offer will be as narrow and explicit as you make it. Working with complex app entities now becomes as easy as working with any other simple data type in Ruby.
Value objects bring safety and simplicity anywhere you use them. In your views, for example, once you know what shape these values will take, you can work with any of their attributes without hesitation. Multiple nil checks become a thing of the past (and when you do have a potentially nullable attribute, you can make it explicitly so). Wrapping these value objects with view-specific presenters becomes more straightforward too, since there’s no need to hide any API that’s not appropriate for consumption within views.
Once you’ve built an expressive collection of domain entities as value objects, the benefits can spread throughout your app at large. You can then use them to pass around your app’s entities to any sort of functional or “service” objects that express your app’s high-level behaviour. Because the entities are now inert, you can be confident in passing them around from place to place without worrying about any unexpected side effects being triggered along the way.
Embracing this change will require other parts of your app to come along for the ride. For example, you’ll most likely want repositories or data mappers to handle your database querying and persistence. You’ll also want to provide specific objects to handle the work of validating form posts and then creating or updating records, before returning them back to your app as valid entity value objects.
This is a change from how you see most Ruby web apps today, but it’s a positive change. Keeping your app’s entities modelled as inactive value objects encourages you to spread your app’s “active” behaviour appropriately around a greater number of other single-responsibility objects. This will only make your app easier to understand and easier to change over time.
In next week’s instalment, I’ll look at why you should use functional objects to model your app’s high-level logic (and return a few value objects in the process).
Read part 1 of this series: My past and future Ruby | https://medium.com/notes-from-icelab/inactive-records-the-value-objects-your-app-deserves-db0a1a7f606f | CC-MAIN-2017-51 | refinedweb | 1,121 | 53.81 |
I need to update a caffe model from an existing caffe model where I will drop last two layers. It is needed to reduce caffe model size so that it would be easier and lesser size to deploy. Say my existing caffe model is A1.caffemodel which has 5 convolution layers and 3 fully connected layers. I want to generate a new model from it named B1.caffemodel which will have 5 convolution layers and 1 fully connected layer (last 2 fc layers discarded).
I appreciate your all valuable suggestions and helpful code snippet.
Net<float> caffe_net("B.prototxt", caffe::TEST);
caffe_net.CopyTrainedLayersFrom("A.caffemodel");
caffe::NetParameter net_param;
caffe_net.ToProto(&net_param);
caffe::WriteProtoToBinaryFile(net_param, "B.caffemodel");
Fully connected layers can indeed be very heavy. Please look at section "3.1 Truncated SVD for faster detection" at Girshick, R Fast-RCNN ICCV 2015 describing how to use SVD trick to significalntly reduce the burden of fully connected layers. Hence, you can replace your three fully connected layers with 6 very thin layers.
Steps to go from model
A to
B:
Create
B.prototxt that has the 5 convolution layers with the same
"name"s as
A.
Give the single fully connected layer in
B a new
"name" that does not exist in
A.
in python
import caffe B = caffe.Net('/path/to/B.prototxt', '/path/to/weights_A.caffemodel', caffe.TEST) B.save('/path/to/weights_B.caffemodel')
Now you have weights for
B that are the same as the weights of
A for all convolutional layers and random for the new single fully connected layer.
fine tune model
B starting from
'/path/to/weights_B.caffemodel' to learn the weights for the new single fully connected layer. | https://codedump.io/share/FwU2kPHASg0d/1/layer-drop-and-update-caffe-model | CC-MAIN-2016-50 | refinedweb | 284 | 51.04 |
In this tutorial, you’ll learn All the important C Programming Basics, used for Programming in C Language.
This C programming basics section explains a simple “Hello World” C program.
Also, it covers basic topics as well, which is to be known by any C programmer before writing a C program
If you are looking for C programs, please click here “C programs” for C Programming Basics continue below.
- C programming basic commands to write a C program.
- A simple C program with output and explanation.
- Steps to write C programs and get the output.
- Creation, Compilation, and Execution of a C program
* How to install C compiler and IDE tool to run C programming codes.
- The basic structure of a C program
* Example C program to compare all the sections
* Description of each section of the C program
- C programs ( Click here for more C programs ) with definition and output – C program for a Prime number, Factorial, Fibonacci series, Palindrome, Swapping 2 numbers with and without temp variable, sample calculator program and sample bank application program etc.
Programming Basics to write a C Program
Below are few commands and syntax used in C programming to write a simple C program. Let’s see all the sections of a simple C program line by line.
Program to Print Hello World!
Below C program is a very simple and basic program in the C programming language. This C program displays “Hello World!” in the output window. And, all syntax and commands in C programming are case sensitive. Also, each statement should be ended with semicolon (;) which is a statement terminator.
#include int main() { /* Our first simple C basic program */ printf("Hello World! "); getch(); return 0; }
Output
Hello World!
Prerequisite
- If you want to create, compile and execute C programs on your own, you have to install C compiler on your machine. Then, you can start to execute your own C programs on your machine.
- You can refer below link for how to install C compiler and compile and execute C programs on your machine.
- Once C compiler is installed on your machine, you can create, compile and execute C programs as shown in below link.
- If you don’t want to install C/C++ compilers on your machine, you can refer online compilers which will compile and execute C/C++ and many other programming languages online and display outputs on the screen. Please search for online C/C++ compilers in Google for more details.
Basic Structure of a C Program
Structure of C program is defined by the set of rules called protocol, to be followed by a programmer while writing C program. All C programs are having sections/parts which are mentioned below.
- Documentation section
- Link Section
- Definition Section
- Global declaration section
- Function prototype declaration section
- Main function
- User-defined function definition section
Program to Compare all the Sections
You can compare all the sections of a C program with the below C program.
#include <stdio.h> /* Link section */ int total = 0; /* Global declaration, definition section */ int sum (int, int); /* Function declaration section */ int main () /* Main function */ { printf ("This is a C basic program \n"); total = sum (1, 1); printf ("Sum of two numbers : %d \n", total); return 0; } int sum (int a, int b) /* User defined function */ { return a + b; /* definition section */ }
Output:
This is a C basic program Sum of two numbers: 2
Description for each Section of the C Program
- Let us see each section of a C basic program in detail below.
- Please note that a C program may have all below-mentioned sections except main function and link sections.
- Also, a C program structure may be in below-mentioned order.
C Programs with Definition, Example Program, and Output:
If you have enough basic knowledge of C programming language and all concepts, you can refer following C programs.
Please click here “C programs” for referring below programs.
- C program for the Prime number
- C program for Factorial
- C program for Fibonacci series
- C program for Palindrome
- C program for Swapping 2 numbers with and without the temp variable
- Sample calculator program and bank application program etc.
Important Basics Points to Remember in C Programming
- C programming is a case-sensitive programming language.
- Each C programming statement is ended with a semicolon (;) which are referred to as a statement terminator.
- printf( ) command is used to print the output onto the screen.
- C programs are compiled using C compilers and displays output when executed.
Ask your questions and clarify your/others doubts on C Programming Basics by commenting. Documentation | https://coderforevers.com/c/c-programming-basics/ | CC-MAIN-2019-39 | refinedweb | 761 | 51.48 |
Hi,On Thu, 2008-08-21 at 09:17 +0200, Vegard Nossum wrote:> I resubmit this, which was posted a month ago, with no responses from> the maintainer (and no recent fixes in this area either). I have not> tested it myself, but I am reasonably confident that this is an> obviously correct fix. I guess it would not hurt to exercise it as well.> > Zdenek: Have recent kernels also been showing this behaviour? Did the> patch fix the problem for you? You said something about a new issue> showing up, do you think that was related to this patch?> > Also, just one question (since I'm newbie at this): Is it dangerous to> register the &dev_attr_trigger device file before we put the device on> the list or initialize it completely? If so, the initialization should> probably be moved all to the top before the file is made public.This patch isn't quite right since whilst it fixes one race, it opens upa number of other potential problems. We definitely should have the ledlisted in leds_list before calling the various functions and theexisting init order is correct in that sense.I suspect your problem is caused by something calling a triggerregistration between the point its added to the list and theinit_rwsem(). The best solution is to move the init_rwsem() to earlierin the function. Yes, that means some ifdef ugliness but so be it. Couldyou see whether you still see the problem with the patch below?Cheers,Richarddiff --git a/drivers/leds/led-class.c b/drivers/leds/led-class.cindex 559a408..c9d8219 100644--- a/drivers/leds/led-class.c+++ b/drivers/leds/led-class.c@@ -113,6 +113,9 @@ int led_classdev_register(struct device *parent, struct led_classdev *led_cdev) if (rc) goto err_out; +#ifdef CONFIG_LEDS_TRIGGERS+ init_rwsem(&led_cdev->trigger_lock);+#endif /* add to the list of leds */ down_write(&leds_list_lock); list_add_tail(&led_cdev->node, &leds_list);@@ -121,8 +124,6 @@ int led_classdev_register(struct device *parent, struct led_classdev *led_cdev) led_update_brightness(led_cdev); #ifdef CONFIG_LEDS_TRIGGERS- init_rwsem(&led_cdev->trigger_lock);- rc = device_create_file(led_cdev->dev, &dev_attr_trigger); if (rc) goto err_out_led_list; | http://lkml.org/lkml/2008/8/21/95 | CC-MAIN-2014-15 | refinedweb | 338 | 54.12 |
07 March 2012 06:03 [Source: ICIS news]
By Psyche Gong
SINGAPORE (ICIS)--Bitumen supply in east ?xml:namespace>
Squeezed by spikes in crude feedstock cost, mainstream local producers are reducing bitumen output and switching to produce other products like fuel oil that brings better margins, they said.
The price of Duri crude, a reference in calculating bitumen producers’ feedstock cost, has increased from $112.51/bbl at the beginning of 2012 to $128.07/bbl on 6 March, up by 13.8%, according to C1 Energy data, an ICIS service in
The strong crude prices have battered bitumen margins as low as yuan (CNY) 26/tonne (€4/tonne) in late February from CNY248/tonne in early January, C1 Energy data showed.
“We may get resistance from buyers if we push prices too fast, so only thing we can to is to cut production,” a source from PetroChina Fuel Oil Co said.
The tight supply has sent up bitumen prices in east
Market sources are predicting further price rise in coming weeks as production fails to catch up with demand.
“Price may continue to rise since supply is getting even tighter in March, on the other hand some roads will start getting paved,” a trader said.
March production in the east region will be about 394,000 tonnes in total, but around 11,000 tonnes or 28% will be used in blending coking feedstock, leaving the remainder insufficient to satisfy rising demand from end users in road-paving, market sources said.
Sinopec has cut bitumen output from its Zhenhai and Jinling plants by 20% from February to 90,000 tonnes and 40,000 tonnes respectively in March, traders said citing company’s effort to minimize losses and support the prices.
Similarly for the same reasons PetroChina has trimmed bitumen production from its Wenzhou plant to 45,000 tonnes in March, falling by 6.25% from February, according to a company source.
PetroChina’s Jiangyin plant will also produce 50% less bitumen in March against February’s 48,000 tonnes, the source added.
( | http://www.icis.com/Articles/2012/03/07/9538937/east-china-bitumen-supply-tightens-in-march-on-low-production.html | CC-MAIN-2014-41 | refinedweb | 342 | 56.69 |
Qt Console Application Problems
- mahmoud899
Hello, I am having difficulties to understand why my program is being executed wrong. When I run the program, the console screen appears and awaits from me to enter a number, and when I enter a number then press enter, it then prints the following:
Hello World
Please Enter Your Age
Your Age is
56
Any suggestions as why is this happening?? Thank You,
@
#include <QTextStream>
int main(int argc, char *argv[])
{
int age;
QTextStream output(stdout); QTextStream input(stdin); output << "Hello World\n\n"; output << "Please Enter Your Age:\n"; input >> age; output << "Your Age is: \n"; output << age;
}
@
What about:
@QFile myStdOut;
file.open(stdout, QIODevice::WriteOnly | QIODevice::Unbuffered);
QTextSTream output(&myStdOut)
output << "Hello World\n\n";
output << "Please Enter Your Age:\n";
input >> age;@
--
Note however:
The "stdout" and "stderr" streams have their own buffering too! If they are connected directly to a "real" console, this is disabled automatically. But as soon as the output of a console application gets redirect, e.g. your console application is created as a child process via QProcess, you will notice the buffering! That means, regardless of the QTextStream or QFile buffering, you should be doing this, in order to make sure outputs aren't delayed:
@for(int i = 0; i <= 100; i++)
{
//Do some work that takes time
doSomeWork(i);
//Write current progress fprintf(stdout, "Progress: %d %%\n", i); //required flushing! fflush(stdout);
}@
- mahmoud899
Thank you for all of your replies, the output.flush() worked well. | https://forum.qt.io/topic/26450/qt-console-application-problems | CC-MAIN-2018-39 | refinedweb | 251 | 56.59 |
:
- I had no prior experience with Rails.
- The methods employed herein are from the perspective of a “.NET guy” using his knowledge to write something in Rails.
If you happen to be a .NET guy like me and you happen to be tasked with writing or porting from a Rails environment, this article should be helpful. I implemented every major feature in Nerd Dinner (Ajax, JSON, jQuery, etc.) in what I have called Rails Dinner (a play on words re: Nerd Dinner). With that in mind, let’s get to porting Nerd Dinner to Rails!
A Quick Word About Tests
If you are familiar with a typical Rails project, tests are an integral part of the process. Just as Rails was built from the ground up with MVC in mind, unit tests are right there front and center.
However…..
Being that this is my first Rails application with the initial goal of building an application based on an existing ASP.NET MVC exemplar, I opted to set testing aside. In concept, tests in Rails are just like tests in ASP.NET MVC. For demonstration purposes, I will illustrate the mechanics of defining and running unit tests. You will see that the Rails framework provides facilities for test fixtures in order to place a database in a known good state. By default, Rails will configure a separate test environment so as not to disturb your production and development environments. Later in this article, I will discuss how Rails manages the test, development and production environments.
Testing, whether it is unit or integration testing is a first class citizen in the Rails environment. Under normal circumstances, in a TDD (Test Driven Development) scenario, you would:
- Write a test (that would initially fail)
- Write code
- Run the test/modify the code as needed until the test passes
- Repeat the process (Red, Yellow, Green Development)
When I first created the Nerd Dinner Rails project, it created a test folder. There are test fixtures and stub test classes ready to be used. You can find a nice overview of testing in Rails here:
If you continue to go down the Rails route, and if you are a fan of BDD (Behavior Driven Development), you will definitely want to check out Cucumber:. You can find a nice overview of Cucumber here:.
Cucumber provides the ability to write tests in the language of the domain. That, in a nutshell, is my mea culpa as it pertains to testing and how integral it is re: idiomatic Ruby on Rails.
Nerd Dinner, ASP.NET MVC and Rails - the Intersection
Nerd Dinner is not defined so much by its data, but rather, by the way it illustrates the ASP.NET MVC implementation. The business problem Nerd Dinner addresses is fairly trivial. There are any number of ways you can keep track of events and attendees. What is interesting about Nerd Dinner is how it illustrates, in a very simple way, the power and flexibility of the ASP.NET MVC Framework. In very short order, Nerd Dinner, in addition to the ASP.NET MVC Framework itself, illustrates how to incorporate jQuery, Ajax, JSON and forms authentication in an ASP.NET MVC application.
It is often said that ASP.NET MVC was inspired by Rails. Because I had not looked at Rails, I never understood or appreciated that point. While attending the 2009 DevLink Conference in Nashville, TN, I had an eye-opening experience. At the closing session, Richard Campbell and Carl Franklin recorded a live session of .NET Rocks! (). The main topic of the show discussed whether software development has become too complicated.
Getting back to DevLink, during the Q and A portion of the .NET Rocks! episode, a guy named Leon Gersing came to the microphone and said, among other things, that the panel was not qualified to render it’s opinions on Ruby and Rails for the simple reason that they had not worked in that environment. I thought, “Wow, how refreshing is this?” Subsequently, Carl and Richard hosted Leon as a guest on .NET Rocks! (episode 482 - “Leon Gersing is Having a Love Affair with Ruby,”). You can find Leon’s Web site at and follow him on Twitter @FallenRougue.
Leon’s comments at DevLink and his .NET Rocks! appearance inspired me to check Rails out. In the summer and fall 2009, I had already written a number of blog posts concerning Nerd Dinner. I had already integrated NHibernate/Fluent NHibernate, Structure Map and various jQuery plug-ins into the base Nerd Dinner application. With a good understanding of Nerd Dinner, I figured, why not? Why not re-write Nerd Dinner in Rails from the ground up, using the ASP.NET MVC version as the specification! How hard could it be? As it turned out, after about a week, it was not that difficult. To be candid, I didn’t develop a Rails app of high pedigree given that tests were not central to the effort. Nevertheless, the job got done!
The process had challenges. Those challenges however, were borne more out of my “noob” status re: Rails. As for Ruby, let’s just say that it is now my favorite language! With all of that in mind, I would like to take you through my journey of putting Nerd Dinner in Rails.
Getting Up and Running with Rails
Chances are you don’t have Rails installed. In order to install Rails, you must first install the Ruby language. So far, I have simply referred to Rails as Rails. Technically, what I’ll show you is Ruby on Rails. I suppose the .NET equivalent would be <<insert language here>> on ASP.NET MVC. Ruby is the language and Rails is the Web framework that provides the MVC infrastructure. Whereas in ASP, MVC was bolted on via Microsoft.Web.Mvc, Rails was built from the ground up with MVC in mind.
The best place to get up and running with Rails is to visit. Once you go to the download page, you will have three tasks to complete:
- Download Ruby: The current version is 1.9.1. However, 1.9.1 has only been out for a short time. NOTE: Ruby 1.9.1. DOES NOT work with Rails version 2.3.4, which I used for this article. I wrote Rails Dinner with Ruby version 1.8.6, which has a one-click Windows installer that makes it a snap to install. You can use either version 1.8.6 or 1.8.7 of Ruby to work with this article. The Windows Installer takes care of making sure you’ve added Ruby to your path.
- Download RubyGems: RubyGems is the standard package manager for Ruby. When extending Ruby, you do so via a gem. Once you’ve downloaded RubyGems, you install it by issuing the following command at the command prompt: ruby setup.rb.
- Install Rails: This is not a misprint and there is nothing for you to download manually. Just this process alone may be enough to get you enthused about Rails. Rails is a gem you install in order to extend Ruby’s functionality. In order to install the Rails gem, or any other gem for that matter, you issue this command from the prompt: gem install rails -v=2.3.4. If you don’t specify the version, Rails 3.0, just released to beta will be installed. Rails 3.0 requires Ruby 1.8.7 or later.
If all worked correctly, you now have Ruby and Rails installed. In order to verify the versions, you can issue the commands ruby -v and rails -v from the command prompt. Figure 1 illustrates what you should see.
For Nerd Dinner on Rails, you need to install two additional gems: the GeoKit gem and the Ruby SQLite 3 gem.
Looking at Nerd Dinner’s geography capabilities, most of that is handled via Microsoft MapPoint. If you look in the Map.ascx partial view, you will find the following script source:. This facilitates the map display in Nerd Dinner. The Nerd Dinner on Rails app uses the same mapping resource. However, when it comes to calculating the distance to Dinners from search location, the original Nerd Dinner used a SQL Server stored proc that took pairs of latitude/longitude coordinates in order to provide the distance in miles. Fortunately, there is a gem called GeoKit that can handle this functionality. The following code will install these gems to your system - making them available to your Rails-based applications:
gem install geokit
I’ll get into the specifics of implementing the GeoKit Gem later on.
By default, Rails supports the SQLite 3 database. Rails also supports SQL Server, MySQL, Oracle, and others. To keep this example as simple as possible, I’ll stick with SQLite 3. Before you can install the SQLite Gem, you need to install SQLite 3. You can find everything you need to install SQLite 3 here:.
Once you have installed SQLite 3, you can then install the gem:
gem install SQLite3-ruby
You’ll also need to use a plug-in. In the ASP.NET MVC version of Nerd Dinner, authentication is handled via ASP Forms Authentication. In order to duplicate the functionality you need to employ some method of authentication. Fortunately, there is a plug-in for that! Once you have the basic Nerd Dinner app up and running, the Restful Authentication plug-in will be installed.
Creating the Base Nerd Dinner App on Rails
With Ruby, Rails, and GeoKit installed, I can now show you how to create the Nerd Dinner application. It’s a pretty simple process to create the base application. First, create a directory. For this example, I called mine RailsApps. In that directory, type: rails nerddinner. You will see the cursor blink for a few moments, and then just like that, you have the guts of your new Nerd Dinner Rails application. Figure 2 illustrates the output you should see. Figure 3 illustrates the directory structure Rails created for the new application.
OK, so now what? At this stage, your application isn’t capable of much. But, there is some functionality. When you installed Rails, you also installed a local Web server called WEBrick. From your railsapps\nerddinner directory, issue the following command:
ruby script\server
This command starts-up the local WEBrick Web server. By default, WEBrick listens for requests on port 3000. Figure 4 illustrates what you should see after you start the Web server and open a Web browser, navigating to.
So then, where does this default page come from? Rails provides that as well. Another directory which you will become familiar with is the public directory. Figure 5 illustrates where the index.html page is located. The public directory is the home directory of the application.
This is really no different than a newly created ASP.NET MVC app. Figure 6 illustrates what you get for free with a new ASP.NET MVC App.
What if you try to navigate to a Dinner? Figure 7 illustrates the exception that is thrown when you attempt to navigate to.
Considering that you have not created a Nerd Dinner database yet, much less a Dinners table or entity, you shouldn’t expect to be able to navigate to a Dinner. The exception, however, is very instructive. Just like ASP.NET MVC, Rails relies on a routing hash in order to direct traffic. When you make a request in ASP.NET MVC that does not match a route, you may see an error similar to Figure 8. In Rails and ASP.NET MVC you can easily deal with these scenarios.
With the framework basics in place, let’s take a look at Nerd Dinner on Rails, with Nerd Dinner on ASP.NET MVC as the guide.
Adding Dinners and RSVPs to Nerd Dinner on Rails
Like the ASP.NET MVC version, the Nerd Dinner application doesn’t need a complicated database. It has only two entities:
- Dinners
- RSVPs
The relationships are fairly straightforward as well:
- A Dinner has 0:N RSVPs
- An RSVP has 1 Dinner:
ruby script/generate scaffold Dinner id:int Title:string Eventdate:datetime Description:string Hostedby:string Contactphone:string Address:string Country:string Latitude:string Longitude:string
The following code scaffolds the RSVP objects:
ruby script/generate scaffold Rsvp id:int Attendeename:string Dinner:references:
rake db:migrate:
class Rsvp < ActiveRecord::Base belongs_to :Dinner end
As you can see, an RSVP belongs to a Dinner. All you need to do is modify the Dinner Model so that it knows that it has many RSVPs:
class Dinner < ActiveRecord::Base has_many :Rsvp, :dependent => :destroy!
Reviewing what Rails Provided
The database for this demo is SQLite 3. The database is located in the db and is named development.SQLite3. There is a FireFox add-in that you can download that allows you to open and view a SQLite database. You can find the manager here:. Once installed, you can access the manager from the FireFox Tools Menu.
Figure 15 illustrates how the FireFox SQLite db manager works. Looking at the RSVP table, you can see that Rails did a lot of work for you. Notice the Dinner_id field. This is the foreign key to the Dinners table. Because you told Rails that RSVP references Dinner, Rails took care of adding the required field to facilitate that relationship. Notice too that Rails created two audit columns to capture the create and update datetime values for each RSVP record.
Looking at Figure 14 again, notice that for date time fields, Rails went ahead and provided a series of dropdowns to assist with data entry. In the next section, I’ll show you how to substantially overhaul what Rails provided in order to get the same look, feel and behavior of the original ASP.NET MVC Nerd Dinner application.
Before continuing, I encourage you to review the controllers and views. With respect to views, Rails and ASP delimits script the same way: <% %>. With respect to controllers, the first thing you will notice is that there is not a lot of code. There are many Ruby on Rails books and resources available that will get you up and running very quickly. A great place to start is to check out the Ruby on Rails site:. From there, you can find any number of resources.
Nerd Dinner on Rails - Getting to the Finish Line
Let’s cut to the chase. Looking at Figure 16 and Figure 17, the Rails version of Nerd Dinner is, feature for feature, nearly identical to the original ASP.NET MVC version. Of course, I couldn’t resist adding a few features that are not in the original Nerd Dinner application. One feature I did add was to set limits on the search radius when looking for a Dinner. In Figure 17, you can see where the search distance default is 100 miles. To accomplish this feature, I used the GeoKit Gem. I’ll discuss the details of that code later in this article.
At the start of this project I identified the major features Nerd Dinner on Rails had to support:
- User authentication
- Create/Edit/Delete Dinners
- RSVP to a Dinner
- Search for Dinners based on a specified location and distance threshold
- Ability to display search results with respective distance from search location
- Full map support like the original Nerd Dinner ASP.NET MVC application
- Retain the overall look and feel of the original ASP.NET MVC Nerd Dinner application
- Full Ajax, JSON and jQuery support
At the outset of this article, I said that Nerd Dinner is not defined so much by the business problem it solves. Rather, it is defined by the simple way it illustrates the flexibility and power of the ASP.NET MVC framework. In addition to the core ASP.NET MVC framework, Nerd Dinner also demonstrates how to use Ajax, JSON and jQuery. Ajax, JSON and jQuery are first-class citizens in Rails. As in ASP.NET MVC, you can use Ajax in Rails to make calls to the server without requiring an entire page refresh. JSON, which stands for JavaScript Object Notation, allows you to serialize data from a controller method to the browser. jQuery, another powerful JavaScript library, fully supports Ajax and JSON and facilitates the passing of data to/from the server and the display of data in the browser.
In the MVC context, Ajax is typically used to either render a string or a view back to a target <div> region. JSON is about data serialization to/from the server to the client. In the Nerd Dinner application, JSON is used to display Dinner search results from the server to the client. Ajax is used as part of the RSVP process. Looking at Ajax and JSON alone, Nerd Dinner is a great teaching tool.
Nerd Dinner on Rails - Under the Covers
Like the original Nerd Dinner on ASP.NET MVC, Nerd Dinner on Rails is based on the Model View Controller (MVC) pattern. At this point, you have already seen the basic Rails framework and the database. The base Rails application as compared to the original Nerd Dinner ASP.NET MVC application is a lump of clay. At a raw level, it has rudimentary functionality. What it lacks is the look and feel and full functionality of the original Nerd Dinner application. In the following sections, that raw lump of clay will be transformed into a fully functional and complete Nerd Dinner on Rails.
User Authentication
There is still one piece of unfinished business with respect to user authentication. In the original version, in order to host and RSVP to a Dinner, you must be logged into the system. The ASP.NET MVC version uses ASP Forms Authentication. In the Rails version, I used the Restful Authentication plug-in.
The first step is to install the plug-in:
ruby script/plugin install- weenie.net/projects/plugins/restful_authentication
Figure 18 illustrates the console output once the plug-in is installed. The next step is to generate the user model, view and controller and db scripts:
ruby script/generate authenticated user sessions
Like the plug-in installation, the script generation will result in console output that enumerates what has been generated.
The last step is to run the Rake migration script:
Rake db:migrate
There are also a few additions required to the routes.rb file. The routes.rb performs the same function as the MVCApplication Class RegsiterRoutes method in the Global.asax file. Regardless of which MVC framework you use, the route concept applies. The routes.rb file is located in the config folder. The config folder also hosts a number of files that handle configuration-related tasks for the database and the overall environment.
Dinner: Model, View and Controller
Ultimately, the best way to learn a new language and a development environment is to simply work through code to learn syntax and to create small programs to learn the framework. Gradually, you build up the complexity of your applications as you learn more. When possible, you should try and take something you know in one environment and replicate it in another environment. That is precisely what I did with Nerd Dinner. Like the ASP.NET MVC version, the Rails version has models, views and controllers. As you will see, while the implementation differs, conceptually, the ASP.NET MVC and Rails versions are identical.
Dinner Model
In Rails, models are very simple. Models are based on ActiveRecord, the Rails ORM mechanism. As you can see in Listing 1, there are no defined properties. Instead, attributes are dynamically read out of the database.
Even if you have never looked at Ruby code before, you will probably have a good sense of what the code in Listing 1 does:
- It’s a model class named Dinner.
- The model has a related model called RSVP (upon destruction of the Dinner, the RSVPs should also be destroyed.
- Eventdate, Title, Description, Contactphone and Address are required data.
- There is a custom method called Formatted_Eventdate that returns a formatted date string. Dates in this system are stored in UTC format.
- There are methods to determine whether a specific user hosts the Dinner or whether that user has already RSVP’d the Dinner.
In the IsUserRegistered method, you can see that models, which are based on ActiveRecord, have methods that are reminiscent of LINQ. In this method, RSVPs are searched using the current Dinner and passed attendee name as criteria. In the Dinner show view, you will see how these methods are called.
Dinner View (Edit, New, Show & Index)
If you understand how views work in ASP.NET MVC, you already understand how views work in Rails. In both environments, you have different views for different actions. Dinners supports the following actions:
- Index Default home page for Dinners
- Show Displays detail about a selected Dinner
- New Called when the user wishes to create a Dinner - Get
- Create Called when the user wishes to save a new Dinner - Post
- Edit Called when the user edits the selected Dinner - Get
- Update Called when the user saves edits - Post
- rsvp Action invoked via Ajax when a user wishes to RSVP to the selected Dinner
- Destroy. Called when the user confirms the selected Dinner should be deleted
Before you continue, you need to address the look and feel of Nerd Dinner. In the original version, the Site.css style sheet file determined the look and feel. You can find that file under the Content Folder. In Rails the process is no different. Under the public folder, there is a stylesheets folder. At the same level as stylesheets, there are also folders called javascripts and images. You just need to copy the respective resources to the correct folders:
- site.css => public\stylesheets
- map.js => public\stylesheets
- nerd.jpg => public\stylesheets
Copying the files is not enough. You need to add code to the views in order to take advantage of these resources. In ASP.NET MVC you can base views off of site.master. You can find site.master in your views\shared folder. The same concept exists in Rails. Under the views folder you’ll find a folder called layouts. If you want all of your views to be based off of a common template, you do so by creating a file called application.html.erb. Listing 2 shows a common layout (functional equivalent of site.master) for Nerd Dinner on Rails.
This code is very similar if not nearly identical to an asp page. It contains a mixture of script and HTML. Like ASP.NET MVC, Rails has a number of helper methods for tasks such as creating links. The application layout page specifies a common layout. Notice the helper methods that Rails provides to include css and script files. The prototype.js file, included with Rails, provides Ajax support. You’ll see how this is implemented in the RSVP action.
With the default layout defined, take a look at the show view (Listing 3).
Reading the code in Listing 3, it is nearly the same as the ASP code. It has a div to display basic information about the Dinner and a special div for the map display. In addition, there is code to determine if the current user is also the host or whether the current user has already RSVP’d. Depending on the results of those evaluations, the appropriate text is displayed. Pay special attention the rsvpmsg div, and this code in particular:
<%= link_to_remote( "RSVP to this dinner", :update => "rsvpmsg", :url =>{ :action => :rsvp, :id => @dinner.id, :user => current_user.login}, :success => "AnimateRSVPMessage()") %>
The link_to_remote helper is how Ajax calls are made in Rails. If you recall, the dinners controller has an action called rsvp. I’ll show you that code in a moment. That action does not return a view. Instead, the rsvp action returns a string. The :update directive specifies which div is to receive the results of Ajax call. In this case, the rsvpmsg div is updated. Upon a successful call, the AnimateRSVPMessage JavaScript function is called.
In the ASP.NET MVC version, this same code exists in the rsvpstatus.ascx partial view:
<%= Ajax.ActionLink("RSVP for this dinner", "Register", "RSVP", new { id = Model.DinnerID }, new AjaxOptions { UpdateTargetId = "rsvpmsg", OnSuccess = "AnimateRSVPMessage" })%>
Throughout the view you can see how ActiveRecord exposes the Dinner Model. In ASP.NET MVC, you can determine whether a view is strongly typed. From a controller action, you can easily pass an object to the view. From within the view you can access that same object via the Model Object. Rails handles all of this for you behind the scenes. The context, in this case, is the Dinner model. Therefore, from the view, you can simply refer to the Dinner instance variable: @dinner.
ActiveRecord is a true ORM. Notice how you can loop through the RSVPs of a Dinner:
<%@dinner.Rsvp.each do |rsvp| %> <li> <%if rsvp.Attendeename == current_user.login%> <span style="color: red">You</span> <%else%> <%=h rsvp.Attendeename%> <%end%> </li> <%end%>
Take a moment and examine the other views. Like this view, they inherit from the application layout and have full access to the data via the @dinner instance variable.
Dinners Controller
The last major code block to review is the Dinners Controller.
The Dinners Controller Rails works in the same way as the ASP.NET MVC version. In the MVC pattern, the controller processes requests from the view. Remember I discussed the various dinner actions in the previous section. The scaffolding process generated much of this code. To illustrate how things operate, let’s take a look at the index method:
def index @dinners = Dinner.find(:all, :conditions => ['Eventdate >= ?',DateTime.now]) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @dinners } end end
For the index view, you only want future Dinners. Again, relying on ActiveRecord’s native features, the find method with conditions is used to locate Dinners. Notice in the response there are two options. One is html. In that case, the index.html.erb view will be rendered. You can see the output for that in Figure 19.
What if the url was altered to: instead? Figure 20 shows what is rendered in that case.
Notice the first line of code after the class declaration:
before_filter :login_required
This is how authentication is handled. ASP.NET MVC works much the same way. In ASP.NET MVC, the [Authorize] attribute is used to determine whether certain functionality requires a user to be logged into the system.
The rest of the Dinner controller actions operate in the same way. The one exception is the rsvp action, which as previously mentioned supports the rsvp Ajax call.
JSON Support
Before wrapping things up, let me briefly talk about how Rails supports JSON. JSON stands for JavaScript Object Notation. JSON provides a means to transfer data to/from a controller action from a JavaScript function. In Nerd Dinner, JSON is used to support the Dinner search function. On the main page you can search for nearby Dinners based on a zip code or an address. In the Rails version of Nerd Dinner, I added the ability to specify the search radius. Figure 21 illustrates the search capabilities in action.
The resulting list that appears to the right of the map is data served up by the Search Controller’s SearchByLocation method. Listing 5 show the search code.
The search functionality is quite simple. For the geographical calculations I used the Geokit gem, which I discussed earlier. Once all of the future Dinners have been retrieved, the code loops through the data and uses GeoKit to determine if the Dinner is within the search boundary. If it is, it is added to the @jsondinners array. @jsondinners is simply an array of JsonDinner objects. Listing 6 shows the class definition for JsonDinner:
This code is nearly identical to the ASP.NET MVC version. I modified the class slightly to include the distance. Figure 21 illustrates how the distance, calculated by Geokit, is referenced in the list of found Dinners.
So how does the search mechanism work? If there is a complicated aspect to Nerd Dinner, this is it. But once you go through the code a few times, it all makes sense. In map.js (in public\javascripts), there is a JavaScript function called FindDinnersGivenLocation:
function FindDinnersGivenLocation(where) { map.Find("", where, null, null, null, null, null, false, null, null, callbackUpdateMapDinners); }
All this function does is take the data entered into the search textbox and centers the map on that location. In the map’s Find method you can specify a callback function called callbackUpdateMapDinners (Listing 7) that is to be called upon completion of the Find method.
While there is a lot of code here, what is happening is actually quite simple. Once the map has completed its Find method call (which was initiated by the search button), a post is made to the SearchContoller/SearchByLocation method. In that post, four parameters are passed:
- Latitude Map center
- Longitude Map center
- Location The text the user entered
- Distance The distance threshold the user specified
Those four pieces of data are then used by the SearchByLocaton method which I have already covered. If you recall, the SearchByLocation method renders an array of JsonDinner objects. The next bit of JavaScript code acts on that datastream that was returned by the SearchByLocation method:
function(dinners) { $j.each(dinners, function(i, dinner)
For each item that was returned by the SearchByLocation method, a map point is created and the map point is loaded with data that is displayed when the user hovers the mouse over the point. In addition, a list of found Dinners is created to the right of the map.
That’s it!
This is why Nerd Dinner is a deceptively simple application. The business problem is not complicated. What Nerd Dinner does well is that within the context of a small business application, it demonstrates the power of the ASP.NET MVC framework. Further, the Nerd Dinner shows you how to incorporate jQuery. JavaScript, Ajax and JSON into your applications.
Rails Testing
At the beginning of this article I discussed how testing is a first-class citizen of the Rails framework. In Rails development it is such a core principle that in the case of gems, if your submission does not have a complete battery of tests, you need not bother submitting the gem! So then, how do you write a unit test in Rails? It is actually quite simple.
The Nerd Dinner Rails project has a folder named test. The test folder hosts the test fixtures and the code for, among other things, functional, integration and unit tests. Fixtures, like some configuration files, have a yml extension. Pronounced YAMAL, yml files () is another way to serialize data.
A test fixture hosts test data that is inserted into the test database prior to the running of a unit test. Like testing frameworks such as NUnit and MBUnit, the Rails environment takes care of database setup and teardown. Rails, through the data in the fixture files, puts the test database in a known good state prior to the running of each test (Listing 8).
Under the test\unit directory you will find a dinner_test.rb file. This file hosts the dinner related unit tests. Listing 9 illustrates the contents of this file.
Like NUnit and MBUnit, unit testing in Rails is based on assertions. Based on a pre-defined data condition, there should only be one dinner and that dinner will have a specific title. Listing 10 illustrates how to invoke the test.
Resources
The Ruby and Rails communities are rich and vibrant and you’ll find plenty of resources available to get you started. Here are a few of my favorite Ruby and Rails resources:
- RailsCasts.com Free Ruby and Rails screen casts.
- yehudakatz.com Yehuda is a member of the core Rails team and is also a contributor to the jQuery Project.
- RubyInside.com
- Programming Ruby 1.9 (PickAxe)
- Edgecase Ruby Koans
- Agile Web Development with Rails (Pragmatic Bookshelf)
- Rails Envy podcast,
Most of these many resources are free. If you live in large metro area, chances are good there is a Ruby/Rails user group near you.
Speaking of cost, everything shown in this article is free!
Summary
Now that I have a handle on what Rails can do, within the context of this exercise, the next step for me is to learn how to create a Rails application from the ground up using a TDD/BDD approach. Rails 3 is right around the corner and represents a big departure from the current version. I am very intrigued by what R:Spec/Cucumber has to offer. This was my first go around with Ruby on Rails and I am thoroughly impressed. The Ruby Language is very powerful and very intuitive. I look forward to what Rails 3.0 has to offer! | http://www.codemag.com/article/1006071 | CC-MAIN-2015-35 | refinedweb | 5,490 | 66.54 |
Details
Description
There's a bit of code in hbase-daemon.sh that makes HBase master being SIGKILLed when stopping it rather than trying SIGTERM (like it does for other daemons). When HBase is executed in a standalone mode (and the only daemon you need to run is master) that causes newly created tables to go missing as unflushed data is thrown out. If there was not a good reason to kill master with SIGKILL perhaps we can take that special case out and rely on SIGTERM.
Activity
- All
- Work Log
- History
- Activity
- Transitions
stack, before I submit the patch, I would really appreciate if you could let me know the relationship between bin/stop-hbase.sh and bin/hbase-daemon.sh. I was under the impression that whatever stop-hbase.sh triggers in the master code would also be triggered by JVM shutdown hook upon receiving SIGTERM, but it doesn't seem to be that way. Do we have to call bin/stop-hbase.sh manually from within the hbase-daemon.sh before stopping daemons?
stop-hbase.sh does shutdown hook plus shutting down the cluster. Its different. The hbase-daemon.sh sends signal to kill the daemon (triggering shutdown hook). Thats how I remember it. If I'm off, say so and I'll dig in and give you a more detailed response.
stack, thanks for the clarifications – much appreciated! Now, as I said, I only see addShutdownHook call in regionserver code:
$ git grep addShutdownHook src/main/java/org/apache/hadoop/hbase/regionserver/ShutdownHook.java: Runtime.getRuntime().addShutdownHook(t);
and then
/** * @param hrs * @param name * @return Thread the RegionServer is running in correctly named. * @throws IOException */ public static Thread startRegionServer(final HRegionServer hrs, final String name) throws IOException { Thread t = new Thread(hrs); t.setName(name); t.start(); // Install shutdown hook that will catch signals and run an orderly shutdown // of the hrs. ShutdownHook.install(hrs.getConfiguration(), FileSystem.get(hrs .getConfiguration()), hrs, t); return t; }
Now, the behavior that I observe is that when HBase is running in a distributed fashion, flushing of the newly created tables happen when regionserve receives a SIGTERM. When it is running in a standalone configuration tables don't get flushed UNLESS I explicitly call stop-hbase.sh before sending a SIGTERM.
Once would assume that the same code would be called in both cases since it is registering that hook unconditionally. What am I missing here?
Is it because no shutdown hook in master and when in standalone mode all runs in the one jvm, the master's effectively?
In start-hbase.sh, if distmode is false, we ONLY start master:
if [ "$distMode" == 'false' ] then "$bin"/hbase-daemon.sh start master else "$bin"/hbase-daemons.sh --config "${HBASE_CONF_DIR}" start zookeeper "$bin"/hbase-daemon.sh --config "${HBASE_CONF_DIR}" start master "$bin"/hbase-daemons.sh --config "${HBASE_CONF_DIR}" \ --hosts "${HBASE_REGIONSERVERS}" start regionserver "$bin"/hbase-daemons.sh --config "${HBASE_CONF_DIR}" \ --hosts "${HBASE_BACKUP_MASTERS}" start master-backup fi
Inside in master it will take care of starting up all the other beasties if distmode == false.
Perhaps this will be a naive suggestion, but wouldn't it make sense to install Shutdown hooks regardless of whether the Regioserver was started in a standalone mode. Will a trivial change like this one make sense:
--- src/main/java/org/apache/hadoop/hbase/util/JVMClusterUtil.java +++ src/main/java/org/apache/hadoop/hbase/util/JVMClusterUtil.java @@ -179,7 +179,11 @@ public class JVMClusterUtil { } if (regionservers != null) { for (JVMClusterUtil.RegionServerThread t: regionservers) { - t.start(); + try { + HRegionServer.startRegionServer(t.getRegionServer()); + } catch (IOException e) { + // Nothing to do, really + } } } if (masters == null || masters.isEmpty()) {
Have you tried it Roman? Do all the tests pass? Seems like an innocuous enough change.
stack, I have tried it with a standalone HBase writing to a local filesystem (I think there's no way making a standalone instance of HBase use HDFS). And that works quite nicely. Tables get flushed when I SIGTERM the process, etc. Once it came to testing I had to run it with miniDFS and that's where things got interesting. suppressHdfsShutdownHook can't disable the HDFS shutdown hook of the miniDFS, simply because there's nothing to disable.
So here's the question, should I work around this one special case by simply testing for the
LocalHBaseCluster.isLocal(hrs.getConfiguration())
or would you propose something else?
I'd appreciate your advice, since I'm just learning my way around HBase.
suppressHdfsShutdownHook can't disable the HDFS shutdown hook of the miniDFS, simply because there's nothing to disable.
There is no hdfs shutdown hook when running minihdfs?
And I don't follow how testing for localfs helps. I'm not clear on why testing for local fs makes a differenc when the shutdown hook is not in minidfs
. I'm missing something.
I'd appreciate your advice, since I'm just learning my way around HBase.
You seem to be doing just fine to me. Obviously from above exchange you know more about this area of the code than I do (and I think I wrote it?). That suppressHdfsShutdownHook is really pretty (smile). Thats some ugly gymnastics going on in there.
stack, I'm sorry for putting this on a backburner, but at least I now have a better understanding of what's going on.
Basically I got confused in a situation where suppressHdfsShutdownHook would be called multiple times on the same filesystem object. The first call would succeed, but all the other ones would fail. This is, obviously, just a problem with my patch, not the minihdfs cluster. I'll cook up an alternative and once I run the tests will attach an updated version.
P.S. Thanks for the encouragement!
I'm attaching a sample patch that seems to be working well enough. The idea behind it is to reference count the fsShutdownHooks that we have to run from shutdown sequences of multiple RegionServers and only really run each when the last registered regionserver shuts down. Please let me know what do you think.
I was asked yesterday how this can be tested. I'm not quite sure I can come up with a traditional unit test for this change, but here's how to verify it manually:
$ bin/hbase master start & PID=$! ; sleep 15 ; kill $PID
And look for LOG messages of the following nature:
INFO regionserver.ShutdownHook: Shutdown hook starting; hbase.shutdown.hook=true; fsShutdownHook=Thread[Thread-18,5,main] .............. INFO regionserver.ShutdownHook: Starting fs shutdown hook thread. INFO regionserver.ShutdownHook: Shutdown hook finished.
Without the patch – the HBase master simply dies (as in – no messages get produced)
This is not good:
+ } catch (Throwable ex) {}
At least log the exception.
And similar here:
+ try { + HRegionServer.startRegionServer(t.getRegionServer()); + } catch (Throwable ex) {} + // t.start();
What is the exception we are suppressing? Should we at least log it here too?
Otherwise, I'm fine with this referencecounting stuff. Its contained to the shutdown handler class.
Good stuff.
@stack
> At least log the exception.
> What is the exception we are suppressing? Should we at least log it here too?
Basically, the only root cause of possible exceptions here is the code in
suppressHdfsShutdownHook() (which is quite fragile and overly aggressive in
throwing exceptions if things don't look quite right). Now, if you look at
how this code is executed in a non-standalone case – HBase does bail on exceptions
thrown from there. We can adopt the same approach in a standalone and unit testing
case, but I wasn't sure it was the right thing to do. After all, NOT bailing out
(and lets say simply logging these things) will be no worse than what we currently
have (not calling shutdown hooks at all). On the other hand – if we do bail out
aggressively we get a better chance of catching incompatibilities between
suppressHdfsShutdownHook() logic and future hadoop releases during unit tests.
So perhaps – bailing out would make the most sense of all.
Latest version of patch attached. Unfortunately, it has grown since last time I've submitted it to incorporated feedback from this JIRA.
All tests pass on my local workstation.
+ * to be executed after the last regioserver referring to a given filesystem
typo (regioserver)
Otherwise looks pretty good. Thanks for fixing this messy bug.
Patch with the Todd fix and I swapped an unorthodox public AFTER a static qualifier. I tried this patch and it works for me. Committing this.
Committed to branch 0.92 and trunk. Thank you for the patch Roman.
Integrated in HBase-0.92 #35 (See)
HBASE-4209 The HBase hbase-daemon.sh SIGKILLs master when stopping it
stack :
Files :
- /hbase/branches/0.92/CHANGES.txt
- /hbase/branches/0.92/src/main/java/org/apache/hadoop/hbase/LocalHBaseCluster.java
- /hbase/branches/0.92/src/main/java/org/apache/hadoop/hbase/regionserver/ShutdownHook.java
- /hbase/branches/0.92/src/main/java/org/apache/hadoop/hbase/util/JVMClusterUtil.java
Integrated in HBase-TRUNK #2274 (See)
HBASE-4209 The HBase hbase-daemon.sh SIGKILLs master when stopping it
stack :
Files :
- /hbase/trunk/CHANGES.txt
- /hbase/trunk/src/main/java/org/apache/hadoop/hbase/LocalHBaseCluster.java
- /hbase/trunk/src/main/java/org/apache/hadoop/hbase/regionserver/ShutdownHook.java
- /hbase/trunk/src/main/java/org/apache/hadoop/hbase/util/JVMClusterUtil.java
This issue was closed as part of a bulk closing operation on 2015-11-20. All issues that have been resolved and where all fixVersions have been released have been closed (following discussions on the mailing list).
I do not not remember why it SIGKILLs (I was going to blame hadoop saying we copied all from there but I just checked and don't see it there so it must be an addition of ours). If plain kill works for you, make a patch and we'll add it. Thanks Roman. | https://issues.apache.org/jira/browse/HBASE-4209?focusedCommentId=13106978&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel | CC-MAIN-2016-07 | refinedweb | 1,628 | 58.58 |
Docker security Part 1
Are Docker containers really secure?
opensource.com
This article is based on a talk I gave at DockerCon this year. It will discuss Docker container security, where we are currently, and where we are headed.
This is part of a series on Docker security, read part two.
Containers do not contain
I hear and read about a lot of people assuming that Docker containers actually sandbox applications—meaning they can run random applications on their system as root with Docker. They believe Docker containers will actually protect their host system.
- I have heard people say Docker containers are as secure as running processes in separate VMs/KVM.
- I know people are downloading random Docker images and then launching them on their host.
- I have even seen PaaS servers (not OpenShift, yet) allowing users to upload their own images to run on a multi-tenant system.
- I have a co-worker who said: "Docker is about running random code downloaded from the Internet and running it as root."
"Will you walk into my parlour?," said the Spider to the Fly.
Stop assuming that Docker and the Linux kernel protect you from malware.
Do you care?
If you are not running Docker on a multi-tenant system, and you are using good security practices for the services running within a container, you probably do not need to worry. Just assume that privileged processes running within the container are the same as privileged processes running outside of the container.
Some people make the mistake of thinking of containers as a better and faster way of of running virtual machines. From a security point of view, containers are much weaker, which I will cover later in this article.
If you believe as I do, Docker containers should be treated as "container services"—meaning treated as containers running Apache the same way you would treat the Apache service running on your system., this means you would do the following:
- Drop privileges as quickly as possible
- Run your services as non-root whenever possible
- Treat root within a container as if it is root outside of the container
Currently we are telling people in Common Criteria to treat privileged processes within a container with the same criteria as privileged processes running outside the container.
Don't run random Docker images on your system. In a lot of ways I see the Docker container revolution as similar to the Linux revolution around 1999. At that time, when an administrator heard about a new cool Linux service, they would:
- Search the Internet for a package at places like rpmfind.net or just random websites
- Download the program onto their system
- Install if via RPM or make install
- Run it with privilege
What could go wrong?
Two weeks later the administrator hears about a zlib vulnerability and has to figure out if, while hoping and praying that it's not, their software is vulnerable!
This is where Red Hat distributions and a few other trusted parties have stepped in to save the day. Red Hat Enterprise Linux give administrators:
- A trusted repository they can download software from
- Security Updates to fix vulnerabilities
- A security response team to find and manage vulnerabilities
- A team of engineers to manage/maintain packages and work on security enhancements
- Common Criteria Certification to check the security of the operating system
Only run containers from trusted parties. I believe you should continue to get your code/packages from the same people who you have gotten it from in the past. If the code does not come from internal or a trusted third party, do not rely on container technology to protect your host..
5 Comments
So essentially, if you're running a non-priveleged service in there with no root access, your service should be contained. I don't know why anyone would allow a process in a container to run as root, kind of defies the point, right?
Well not really. You would run a root/priv process within a container for exactly the same reason that you would run one on the host system. To allow it access to system services that are not available to non-privileged processes. The basic idea of this article is to treat these processes the same. In the next article, I will cover what we are doing to make docker mor secure.
Dan,
Can you recommend some materials - books/websites/etc - on Linux security?
Thx,
Jeff
You write:
""""
Devices are not namespaced:
/dev/mem
/dev/sd* file system devices
"""
However, Docker containers do not have access to these devices. Docker has a very short white list for devices.
The non-root thing is a bit of a red herring, isn't it? It is based on the idea that one would not be able to obtain root inside the container which goes straight back to container hygiene and the complexities of sanitizing imported software.
If containers are only secure if obtaining root is impossible, why even use a container? Just use a non-root user. | http://opensource.com/business/14/7/docker-security-selinux | CC-MAIN-2015-27 | refinedweb | 842 | 52.19 |
You can program in Python in (at least) three different ways: interactively with
jupyter notebook or with an
ipython command line, or using an edit-run cycle approach with a program editor (e.g.
atom,
idle,
spyder,…).
In all cases, you need to be able to open a command line window (a.k.a. a terminal): * Ubuntu-Linux: Ctrl-Alt-T (see) * MacOSX: Open Finder/Applications/Utilities/Terminal (see) * Windows: Win+X+Command-Prompt (see)
The first step is to type
jupyter notebook in a terminal
mkdir -p AIP2016-files # only if AIP2016-file does not yet exist cd AIP2016-myfiles jupyter notebook
A browser will open a page like the following:
By cliking on
New and selecting
Python [root], a new tab will show a page like below, where you can enter python code in ‘cells’. To execute the code in a cell, just move the cursor there and press
Ctrl+Enter
A nice feature of the “n jupyter notebooks” is that they are saved automatically, in .ipynb files that can be shared with other people. This is very handy, for example, to send a data analysis report by email.
Jupyter’s documentation si available at
You can launch
ipython in a terminal, and start give this file to interpret to a python interpreter. Here is how:
New Filein the Editor and enter the following text:
import turtle: | http://www.pallier.org/lectures/AIP2016/Info-2/Starting-Python/Starting-Python-slides.html | CC-MAIN-2017-51 | refinedweb | 229 | 56.18 |
GLPK/Windows executables
Contents
GLPK for Windows[edit]
The third-party GLPK for Windows (winglpk) project regularly releases pre-compiled Windows executables, based on the official GLPK source files. Executables for both 32-bit and 64-bit operating systems are available. Administrator rights are not needed. The GLPK for Windows distribution also includes GLPK for Java, which provides a binding to the Java programming language.
This project is active and updated executables usually follow an official GLPK release by only a few days. This is the best option for Windows users who do not wish to build and install GLPK by hand.
After downloading the archive from Sourceforge, please, calculate the MD5 and the SHA1 check sums and compare them to the values provided by Sourceforge. You can use Microsoft's File Checksum Integrity Verifier utility[1] for this purpose, e.g.
fciv.exe -both winglpk-4.47.zip
The downloaded archive has to be extracted. This can be done with 7-zip available at. You may move the extracted directory (glpk-4.47) to your favorite place e.g to "C:\program files\GLPK".
Directory w32 contains the 32bit binaries and w64 contains the 64bit binaries.
You will typically want to have the GLPK dynamic link library (glpk_4_47.dll) in the search path for binaries. Either change the environment PATH variable accordingly or copy glpk_4_47.dll to "C:\windows\system32\". Open the control center and type "environment" into the search field to find the control to set your environment variables.
This mid-2012 help list posting contains PNG format screenshots for the settings described above in relation to the Microsoft Visual Studio 2010 C++ IDE — users who prefer screenshots will find these images particularly helpful.
Building a C program using the GLPK library[edit]
The following description describes how to build a first program using the GLPK library. A 32bit system is assumed.
- open Visual Studio Express 2010 C++
- create a new "Win32 Console Application"
- do not choose compiled headers
- open the Project Properties dialog:
- under Linker > Input > Additional Dependencies : add "C:\Program Files\GLPK\glpk-4.47\w32\glpk_4_47.lib"
- under Configuration Properties > VC++ Directories > Include directories : add "C:\Program Files\GLPK\glpk-4.47\src
Enter the following code and then hit F5 to compile and run the test:
#include <stdio.h> #include <conio.h> #include "glpk.h" int main(int argc, char* argv[]) { printf ("GLPK version %s\n", glp_version()); printf ("Press any key\n"); while (!kbhit()){} getch(); return 0; }
The program will output the GLPK version, and wait for any key to be hit, e.g.
GLPK version 4.47 Press any key
If you were using precompiled headers test.cpp would be
#include "stdafx.h" int main(int argc, char* argv[]) { printf ("GLPK version %s\n", glp_version()); printf ("Press any key\n"); while (!kbhit()){} getch(); return 0; }
And stdafx.h would be
#pragma once #include <stdio.h> #include <conio.h> #include "glpk.h"
Additional background[edit]
Andy Trapp's 2009 presentation on GLPK [2] provides a good introduction to the use of GLPK with Windows (although some details are no longer current).
References[edit]
- ↑ "Availability and description of the File Checksum Integrity Verifier utility". Microsoft. 2011.. Retrieved 2011-09-24.
- ↑ Trapp, Andy (2009). "IE 2082: Introduction to GLPK".. Retrieved 2011-09-24. | https://en.wikibooks.org/wiki/GLPK/Windows_executables | CC-MAIN-2017-09 | refinedweb | 547 | 59.8 |
Today as few elements as possible showing your data, complete with the ability to template and customize everything you see.
That is great and all, but what about the smart tag? This handy little tag pops up in your Visual Studio designer while working with RadGauge, allowing you to automatically generate over 15 different pre-defined gauge layouts, providing resources, styles, and full Xaml markup to let you quickly and easily get started with RadGauge. Plus you can easily customize anything you see, so if our color choices, marker templates, or gauge segments don’t match your requirement, you are already 75% there with the Xaml and only need to make minor modifications. This is also a valuable learning tool as you can quickly and easily read through any of the different generated gauges to see just how the different elements play together to form these controls.
Step 1 – Radial Gauge in 2 Clicks
Before setting up our RadialGauge, I want to also show off a linear gauge here in this post, so I’m going to create another page with a Pivot control containing two items:
<
controls:Pivot
<!--Pivot item one-->
controls:PivotItem
Header
"item1"
Grid
</
<!--Pivot item two-->
"item2"
>
Now that we’ve got a place to put our RadGauges, we’re going to take advantage of the smart tag to do the hard work for us. I went ahead and added the following namespace:
xmlns:telerikDataViz="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.DataVisualization"
And wrote in a quick RadGauge declaration that we can select to get the smart tag working:
telerikDataViz:RadGauge
/>
I think I’ll go ahead and select the first gauge in the second row:
Awesome, right? I am not going to bore you with stepping line-by-line through the generated Xaml, rather I’ll let you know that to make this functional and all MVVM-ish I’m going to create a business object with six inter-related points (I’ll dream up a story that makes it work) and a seventh lone-gun value that has nothing to do with the others. Remember that for Step 3. Once our object is created, we’ll come back, throw in a few binding statements, then add a button to create some animation by changing values.
Step 2 – Linear Gauge in 2 Clicks
If you remember our Radial Gauge example, then this will be pretty easy for you to handle. Moving to our second Pivot item, we go ahead and write that same first line of code so that we can implement a RadGauge for the designer, then we’ll choose the third linear gauge in the first row:
After a second of Visual Studio magic we have a working gauge, again complete with styles, colors, and indicators that work as-is or can be fully customized. Since the gauges offer so many options, customization will be another series down the road, but similar to the Radial gauge we are going to look through and see that we’ll need 3 distinct values and then a fourth that will be shared between two markers that are working together.
Step 3 – Writing Some Code
Can you believe we’ve gotten this far with only writing a handful of code? The smart tags make this easy, but now we need to dive into our ViewModel to create some objects and code to help link our gauge implementations to data.
We’re implementing a GaugeDataClass to hold our data. Again, all the code is going to be available in the download, but to serve our purposes for updating gauges we have the following setup:
And we implement INotifyPropertyChanged… so you might have a guess where this is going. ;)
Our ViewModel isn’t very complex either, as you have noticed from previous posts we are setting up a few relay commands, we have a RefreshData method to load new random values, and a public GaugeDataClass to bind to – simple, clean MVVM.
Step 4 – Putting it all Together
Running back through everything we just worked on, we’ve added some complex gauges after only typing two stub lines of code, put together a class and viewmodel to handle our data and interactions, so what is left? The awesome binding system that we know and love in our Xaml development can handle the rest for us. I’m adding quick binding statements to the values of all Gauge markers as well as putting in two buttons below my Pivot control to allow for users to control data refresh.
Last but certainly not least, we’re going back to our MainPageViewModel to add RadGauge to our list to pick from. The end result? Gauges, MVVM-style, with very little coding on our side as far as the Xaml is concerned thanks to our sponsor the smart tag.
Check out the updated source code for this project and look forward to some more posts in this series as we continue to work through the Telerik RadControls for Windows Phone, MVVM-style!. | https://www.telerik.com/blogs/windows-phone-7-mvvm-7---radgauge | CC-MAIN-2018-13 | refinedweb | 841 | 59.37 |
I'm trying to write a test for a model with a picture, using paperclip. I'm using the test framework default, no shoulda or rspec. In this context, how should I test it? Should I really upload a file? How should I add a file to the fixture?
Adding file to a model is dead simple. For example:
@post = Post.new @post.attachment = File.new("test/fixtures/sample_file.png") # Replace attachment= with the name of your paperclip attachment
In that case you should put the file into your
test/fixtures dir.
I usually make a little helper in my test_helper.rb
def sample_file(filename = "sample_file.png") File.new("test/fixtures/#{filename}") end
Then
If you use something like Factory Girl instead of fixtures this becomes even easier. | https://codedump.io/share/Wa5j3wpaJXOo/1/unit-test-in-rails---model-with-paperclip | CC-MAIN-2017-30 | refinedweb | 128 | 61.22 |
sleep(3) BSD Library Functions Manual sleep(3)
NAME
sleep -- suspend thread execution for an interval measured in seconds
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <unistd.h> unsigned int sleep(unsigned int seconds);
DESCRIPTION
The sleep() function suspends execution of the calling thread until either seconds seconds have elapsed or a signal is delivered to the thread and its action is to invoke a signal-catching function or to ter- minate.
RETURN VALUES
If the sleep() function returns because the requested time has elapsed, the value returned will be zero. If the sleep() function returns due to the delivery of a signal, the value returned will be the unslept amount (the requested time minus the time actually slept) in seconds.
SEE ALSO
nanosleep(2), usleep(3)
STANDARDS
The sleep() function conforms to ISO/IEC 9945-1:1990 (``POSIX.1'').
HISTORY
A sleep() function appeared in Version 7 AT&T UNIX. BSD February 13, 1998 BSD
Mac OS X 10.8 - Generated Fri Aug 31 05:27:50 CDT 2012 | http://www.manpagez.com/man/3/Sleep/ | CC-MAIN-2013-20 | refinedweb | 171 | 60.14 |
10 September 2012 08:31 [Source: ICIS news]
SINGAPORE (ICIS)--Rising commodity prices have largely driven up ?xml:namespace>
The pressure of inflation will continue to persist, Li Daxiao added.
“The inflection point has been come, and CPI will keep rising in the fourth quarter,” said Li Xunlei, chief economist at Haitong Securities.
The country’s producer price index (PPI), which is a gauge of wholesale prices, declined by 3.5% year on year, hitting a 34-month low since November 2009, the data showed.“The poor PPI data indicates that industrial products prices have dropped further and economic activities are still weakening,” said Ha Jiming, vice chairman of Goldman Sachs Investment Management Department in
The drop in PPI indicates that the real economy remains in the contraction, analysts | http://www.icis.com/Articles/2012/09/10/9593970/rising-commodity-prices-drive-up-chinas-cpi-analyst.html | CC-MAIN-2015-22 | refinedweb | 129 | 50.87 |
in
Business Administration
Study Manual
BUSINESS COMMUNICATION
The Association of Business Executives
William House • 14 Worple Road • Wimbledon • London • SW19 4DD • United Kingdom
Tel: +44(0)20 8879 1973 • Fax: +44(0)20 8946 7153
No part of this publication may be reproduced, stored in a retrieval system, or transmitted in
any form, or by any means, electronic, electrostatic, mechanical, photocopied or otherwise,
without the express permission in writing from The Association of Business Executives.
abc
ABE Diploma in Business Administration
Study Manual
BUSINESS COMMUNICATION
Contents
Study
Unit
Title Page
Syllabus i
1 Principles and Methods of Communication 1
Purpose of Business Communications 2
The Communication Process 6
Key Factors for Effective Communication 12
The Barriers to Effective Communication 15
2 The Basics of Communicating 21
The Importance of Language 22
Non-Verbal Communication and Self-Presentation 26
Effective Reading 32
Verbal Skills 34
Listening 36
Effective Note Taking 37
3 Written Communication 45
The Written Word 47
General Approach to Business Correspondence 49
Business Correspondence – Practical Applications 56
Reports and Reporting 60
Writing Articles 68
Preparing and Placing a Press Release 68
Writing an Effective Mailshot 73
4 Oral Communication 75
Organising a Presentation 76
Presentational Skills 84
Using the Telephone 97
5 Visual Communication 103
Nature and Purpose of Audio and Visual Aids 104
Designing Audio-Visual Aids 109
Presenting Statistical Information 115
Design and Corporate Identity 123
6 Interviews and Meetings 137
Interviews 138
Meetings – An Overview 142
Documentation for Meetings 144
Procedure in Meetings 149
7 Electronic Communication Systems 155
Introduction 156
Modes of Communication 156
The Internet 159
The Use of IT in Business 166
Input Devices 170
Output Devices 173
8 IT and Presenting Information 177
Introduction 178
Word Processing 178
Desktop Publishing 181
Electronic or Web Publishing 182
9 Information Processing 187
Introduction 188
Data and Information 188
Gathering and Organising Information 190
i
Diploma in Business Administration – Part 1
Business Communication
Syllabus
Aims
1. To enable students to maximise their personal business communication skills necessary both
within the organisation and for communication with external audiences.
2. To provide students with an opportunity to appreciate the internal mechanisms needed for
business communication and how to ensure that these are effective.
3. To be able to deal with different types of data, particularly for the purposes of presenting
information that is visually appealing and professionally produced.
4. To fully understand the role of Information Technology in the business communication
environment and the efficiencies that these opportunities bring to the world of work.
Programme Content and Learning Objectives
After completing the programme, the student should be able to:
1. Business Communication: Background and Theory
In this section students will achieve the ability to:
Understand the communication process, barriers to it, techniques for overcoming them
and for assessing the effectiveness of communication.
Acknowledge the different modes of communication, including face-to-face interactions,
letters, memos, telephone contact, electronic mail, the Internet and video conferencing
and assess the relative advantages and disadvantages of each one.
2. Written Communication: Modes of communication and Computer Software applications
In this section students will achieve the ability to:
Produce and use appropriately a range of written communications including electronic
mail messages, memos, letters, briefs, direct mail, reports, press releases and job
descriptions.
Understand the key elements of word processing including, page layout, typefaces and
fonts and printing and other software computer applications.
3. Oral Communication: Presentations and Visual aids
In this section students will achieve the ability to:
Understand the purposes of presentations and speeches and how to prepare for their
delivery.
Demonstrate the choice and use of visual aids.
Appreciate how to effectively use the telephone and the importance of listening
ii
4. Visual Communication 1: Logos, Graphics and Multimedia
In this section students will achieve the ability to:
Identify the use of visual communications in the presentation of information, including
the role and value of graphics and multimedia.
5. Visual Communication 2: Using Statistical Data and Information
In this section students will achieve the ability to:
Understand basic statistics and how to organise this data into statistical information as
part of a visual presentation.
6. Meetings and Interviews: Structure, Content and Listening
In this section students will achieve the ability to:
Identify different types of meetings and interviews.
Understand the formal structures, procedures and documentation necessary for successful
meetings and interviews.
7. Information Technology and Business Communication
In this section students will achieve the ability to:
Understand the use of information technology in business organisations, including
telecommuting, workgroup computing, bulletin board systems, commercial services and
use of the Internet, including global perspectives such as the world-wide web.
Appreciate the value of personal computing in Communication, including word
processing, desktop publishing, electronic publishing and presenting and organising and
gathering information via spreadsheets, databases and browsers.
8. Input through Computer Hardware
In this section students will achieve the ability to:
Appreciate the use of input devices such as the keyboard, pointing devices and scanners.
9. Output through Computer Hardware
In this section students will achieve the ability to:
Understand how output devices work, such as screen displays, large computer systems
and microcomputer systems.
Method of Assessment
By written examination. The pass mark is 40%. Time allowed 3 hours.
The question paper will contain:
Eight questions from which the candidate will be required to answer any four. All questions carry 25
marks.
iii
Reading List
Essential Reading
R. H. Sheldon. Business Communications, Peter Andrew – ISBN 094676505
Additional Reading
Ludlow, R. and Patteson, F. The Essence of Effective Communication; Prentice-Hall
Capron, H. L. Computers: Tools for an Information Age; Addison-Wesley
Bergin, F. Practical Communications; Pitman
Stevens, M. Improving Your Presentation Skills; Kogan Page
iv
1
© Licensed to ABE
Study Unit 1
Principles and Methods of Communication
Contents Page
Introduction 2
A. Purpose of Business Communications 2
Role of Organisational Structure and Culture 2
Communication Systems Within and Between Organisations 3
B. The Communication Process 6
The Need to Communicate 6
Encoding and Transmission 7
Channels of Communication 7
Decoding 7
Interpreting and Feedback 10
C. Key Factors for Effective Communication 12
Intentional and Unintentional Communication 12
Personality Perception 12
J udgment and Concealment 13
Congeniality 13
Rumour 13
Status 13
Effective Feedback or Evaluation Mechanisms 15
Conclusion 15
D. The Barriers to Effective Communication 15
Sample Case Studies 17
2 Principles and Methods of Communication
© Licensed to ABE
INTRODUCTION
In order to achieve effective business communications you must understand the context in which
communications take place and identify all the elements which contribute to successful
communication. We start, then, by considering the nature of communications in business
organisations and move on to examine the basic principles of the communication process.
Finally, here, we go on to consider the key factors which influence the effectiveness or otherwise of
communications. There are many things that can get in the way of successful communications and we
shall look in detail at these, including a case study where you can use the understanding you have
gained to identify barriers to successful communication in a real-life situation.
A. PURPOSE OF BUSINESS COMMUNICATIONS
No organisation exists solely in isolation with one member who has no contact with anyone or
anything. The exchange of ideas, information or instructions is a fundamental feature of all
organisations. This exchange may take place internally between different sectors or departments, or
externally with other organisations. The purpose of business communications is to understand more
fully how this process functions most effectively. At an individual level, using the correct formats for
letters, memos, reports, or the correct language or approach in oral presentations, telephone calls,
meetings or interviews, will be an accurate representation of how an organisation organises and
communicates.
Information can enter an organisation in a variety of ways:
personal experience of staff;
newspapers and print media;
television;
from customers and competitors.
How information is transmitted externally and utilised effectively internally will be crucial to the
organisation’s success.
The main focus of business communications is to:
(a) give out information;
(b) make your ideas understood;
(c) initiate some action;
(d) share ideas, attitudes, beliefs;
(e) establish links with other people.
Role of Organisational Structure and Culture
Organisations can be made up of one person or thousands of people. How these people do their jobs
and how they communicate depends on the structure and culture of the organisation.
Organisational structure is the formal arrangement of people in their roles and areas of responsibility
and authority. Staff can be organised on a functional, production, regional, divisional or even on a
matrix basis.
Principles and Methods of Communication 3
© Licensed to ABE
An organisation’s culture can be defined as “the corporate personality” or “the way things are done
around here”. It is characterised by the degree of formality and adherence to rules which can be
demonstrated in the way people communicate and even in the way people dress.
(a) Power Culture
This is often developed from a “one man band” or entrepreneur. One person will control all
communications within the organisation and may deliberately encourage or block certain
information.
(b) Role Culture
Information passes from the top down to clearly defined departments, to people with clearly
defined responsibilities. This can aid initial communication but may result in a delay in activity
if several groups have to be involved. This type of culture is often found in bureaucratic
organisations such as local government, the Civil Service, banks, etc.
(c) Task Culture
Here teams of people will work together on particular projects in problem-solving groups
according to personal expertise rather than status. This can be confusing as staff may have to
work with different people each time they are involved in a new project. The pattern of
communication may resemble a wheel, with a strong project leader at the centre but with
effective communication channels between team members at the rim. Such a culture is often
found in market-led firms, e.g. project teams on an oil rig, on an aerospace programme or on a
building contract.
(d) Person Culture
The most important factor here is the personal needs of the staff – their individual growth and
development.
As decisions are reached by consensus, this organisation usually functions best where there is
an exchange of creative ideas, e.g. in a small design partnership. Sometimes a particular
department of an organisation will appear to function in this way, although it will still have to
report to other levels of management.
The structure and culture of an organisation can therefore have a profound effect on the process of
business communications. Knowing how an organisation is structured and its type of culture will help
you to understand the pattern of communication and even identify the right person with whom to
communicate and/or the most appropriate channel of communication.
Communication Systems Within and Between Organisations
The formal communication system in an organisation sets out the command structure and the inter-
relationships between the departments within it. A company organisation chart in either a company
brochure or company report will usually outline the chain of command and responsibility and hence
indicate the likely information flow within that organisation.
Flows of communication within an organisation may progress downwards, upwards, horizontally or
diagonally. The organisational chart which illustrates the formal communication system will also
indicate lines of accountability and the direction in which communication flows within the
organisation (see Figure 1.1). When working in a matrix or people-centred organisation, it may be
necessary to draft an organisation chart for yourself so that you can clearly see how information flows
are managed.
4 Principles and Methods of Communication
© Licensed to ABE
Chief Executive/Managing Director
Director
(Finance)
Director
(Sales & Marketing)
Director
(Production)
Director
(Personnel)
Controller Controller Controller Controller Controller Controller Controller
Operational teams and subordinates
Figure 1.1: A Simple Company Organisation Chart
The formal communication system is usually in written form but need not necessarily be so –
meetings, conferences and presentations may all use oral and visual skills within a formal context.
The following diagrams illustrate how communications flow within organisations from the
perspective of a middle manager.
(a) Downward vertical flows
These are usually in the form of verbal or written messages. Verbal messages are usually
planned, intending to communicate a clearly defined set of instructions or information. The
written messages will usually be contained in memos, or notices of staff meetings.
Senior Management
Middle Management
Figure 1.2: Downward Vertical Flows
(b) Upward vertical flows
These are used to convey information from lower staff levels to management (see Figure 1.3).
They can take the form of progress reports or reports of grievance procedures. In a
bureaucratic organisation they will almost always be in written form. There may also be a
“house style” determining exactly how such written reports are presented to management.
Senior Management
Middle Management
Figure 1.3: Upward Vertical Flows
Principles and Methods of Communication 5
© Licensed to ABE
(c) Horizontal flows
These take the form of the proceedings of cross-functional, problem-solving teams as found in
the task or people-culture organisations. They may occur at formal or informal meetings within
the functions or they may be responses to or requests for information.
Senior Management
Middle Manager X Y Z
Figure 1.4: Horizontal Flows
(d) Diagonal communications
These may take the form of formal meetings or informal conversations. They often relate to
“fire-fighting” activities and cross-functional problem-solving. They may represent a move to
co-ordinate the roles of two or more sectors or departments in particular issues. Diagonal
communications can also be viewed as an attempt to improve internal communications so that
the passing of information and ideas is not restricted to and from management or along the
same levels of responsibility.
Senior management
A B C D
Middle management
1 2 3 4 5 6 7 8 9 10 11 12
(i) (ii) (iii) (iv) (v) (vi) (vii) (viii) (ix) (x) (xi) (xii) (xiii) (xiv)
Subordinates
Usual reporting system
Diagonal flow for specific projects
Figure 1.5: Diagonal Flows
The example of diagonal communication in Figure 1.5 shows middle managers 5 and 6, who
usually report to Senior Manager B and employ subordinates (v) and (vi), now working with
Senior Manager A and subordinates (iii) in Department A and (ix) in Department C.
Informal communication systems tend to co-exist alongside the formal structures that are established
by management. In this way like-minded individuals form networks and information is
communicated as people chat during tea breaks, over the photocopier and as they pass in corridors.
6 Principles and Methods of Communication
© Licensed to ABE
Such informal networks arise due to social needs and to fill the information gaps left by the formal
system.
When the informal network has grown to such an extent that information is more regularly
communicated through the informal rather than the formal routes, so much so that staff are not
formally informed of events affecting them, or the organisation is characterised by rumour and gossip
(known as the “grapevine”), then it is clear that the formal structure is either inadequate or has broken
down.
It is the role of managers to ensure that poor internal communication does not exist as it can lead to
mistakes in customer service, poor industrial relations, stress-related illness and reduced levels of staff
performance.
B. THE COMMUNICATION PROCESS
The Need to Communicate
How is information exchanged?
A simplistic model would be as follows:
Encoding Decoding
Sender
Channel/Medium
Audience
Feedback to sender if possible or appropriate
Figure 1.6: The basic communication process
In order to send our message, it is clear that we need an understanding of the role/function of the
communicator and audience, and then we can select the appropriate channel of communication. There
will also be feedback from us, as communicators, to the audience. Communication should at least be
a two-way process and it is important to remember that you communicate with, and not to, an
audience. However consumers often cannot respond to the advertising campaigns seen in the mass
media.
Effective communication needs to be planned; organisations, and individuals within them, must
identify not only what they want to communicate, but with whom and why. Information will always
be communicated within or between organisations, which are themselves networks of
communications.
This model does not illustrate how the communicator and audience will in turn respond to the
communication within their own organisation.
The stages of the communication process are as follows:
The need to communicate a message Why
Encoding “Writing” the message
Transmission Sending the message
Selecting the communication channel How to send
Principles and Methods of Communication 7
© Licensed to ABE
Decoding Understanding
Interpreting and feedback
Encoding and Transmission
What is the message?
Given that all participants in the communications process have their own unique perspective, it is up
to the communicator to make sure that the message accurately reflects what is intended and is then
presented in the most suitable format.
Any ambiguity in the message will automatically hinder communications, as the following examples
show:
“Long haired boy suspended by head.”
“We’ve recently reduced our staff.”
“The peasants were revolting.”
Complicated phrases or jargon are usually inappropriate, e.g.
“We would be best to facilitate the removal of superfluous stock at our earliest convenience.”
Why not:
“We need to get rid of our excess stock as soon as possible”?
Clarity of purpose, message and delivery are essential elements of effective communication. Lack of
planning or preparation, particularly when telephoning or talking to someone, reflects not just on
yourself but on your organisation.
If you are clear as to the purpose of the communication then it is more likely that the person you are
talking to will be:
(a) The right person;
(b) Able to discuss this matter with you at this time;
(c) Prepared themselves so that information can be exchanged, not merely noted;
(d) In a position to respond positively to your communication.
Channels of Communication
It is important to ensure that you use an appropriate channel or medium to communicate with a target
audience. There are various methods of communicating with a target audience:
Face to face – meetings, interviews, presentations or informal discussions, etc.
Oral – using the telephone, voice mail and answer machines, etc.
Written – using letters, memos, reports, forms, fax messages, or E mail, etc.
Visual – using charts, tables, diagrams, slides, maps or notices, etc.
(a) Internal Channels of Communication
The processing of immediate information to individuals within an organisation will include
telephone messages, internal memoranda or messages which will probably be written on
headed paper to be kept as records of the correspondence later. These will be immediate
8 Principles and Methods of Communication
© Licensed to ABE
responses to other information received and be required by specified individuals in a very short
time-scale.
Reports, briefs and summaries will be determined as to their format by the organisation and will
be prepared for a specific audience to specific objectives and guidelines. (It is also expensive
to send all information to everybody!)
House journals or newsletters might be appropriate if the intention is to contact all staff within
an organisation and the information can be scheduled.
Meetings of interest groups or teams, or staff development activities or internal presentations
will take place amongst small groups of identified staff, who share a common interest or need
for particular knowledge or information.
Personal or personnel issues may well be dealt with orally. Formal procedures for written
warnings, interviews and disciplinary hearings will be necessary.
(b) External Channels of Communication
External channels of communication need not restrict information exchange to an external
organisation. Corporate brochures, sales literature or any paid-for advertising is also accessible
to those within the organisation. What is crucial to remember is that you may not want your
internal market to gain information “second-hand” in this way. In terms of your organisation’s
success, briefing internally via house journals, magazines, staff meetings or newsletters should
form part of the initial communication process prior to or coincidental with your external
communication.
However, if external communications take the form of letters, telephone calls or reports, then it
won’t be necessary for everyone within your organisation to have copies! Key personnel in
projects, departments or teams will, of course, need to be briefed as to ongoing communication
externally.
In addition to the nature of the information to be sent, the cost of external channels of
communication – particularly if they include advertising – is an important consideration.
Sending business correspondence second-class as opposed to first-class might, however, result
in information being received too late and the business being lost.
(c) Selecting the Channel of Communication
The choice of the channel of communication depends on a number of factors:
The urgency of the message – the time-scale required to send information and to allow
for a response
Whether the information is to be transmitted internally or externally
The size and location of your audience
The nature of the information itself – particularly the complexity of the message
The need for a written record
Whether the message is sensitive or confidential
The cost of communicating
The need for interaction and feedback
Internal communication channels will be within an organisation’s control. The communicator
can make use of memos, house journals, bulletins, notice boards, meetings (formal and
Principles and Methods of Communication 9
© Licensed to ABE
informal), telephone calls or closed-circuit television. The recipients will be familiar with the
context, background and language used in the communication.
Externally an organisation has many publics with which it communicates – shareholders,
employees, customers, creditors, governments, local communities and agencies and a variety of
opinion-formers. There will be a preferred channel applicable to each. Apparently informal
verbal channels or “word of mouth” can be as important to an organisation’s reputation as
formal channels like company reports or brochures.
Individual contact with an organisation can be more effective than broadcast media, where the
message is diluted and standardised to suit many rather than individuals. Newspapers are out-
of-date almost as soon as they are printed, ready for the next news item. Clearly the time-scale
of the communication will also determine the channel.
On a day-to-day basis, letters, faxes, telephone calls, reports and personal meetings will form
the majority of business communications. However, sales and promotional literature, press
releases, broadcast media, magazine and journal articles, presentations and trade conferences
will all be used to transmit information.
The choice of channels should be kept under review to ensure that the most appropriate and
effective is being used. For example:
Are they still effective for that particular audience?
Are they still cost-effective?
Is there an appropriate evaluation mechanism to deal with feedback?
Is the organisation using the right communicator(s)?
Have company aims and objectives changed?
Have the company’s publics changed?
Who are the current/new opinion-formers?
Decoding
Who is your audience?
Communication will also be determined by the status of your audience. In different contexts each of
us has a different status and may represent different market segments: doctor, patient, mother, wife,
husband, single parent, consultant, tennis coach, etc. The same message may be addressed to different
audiences using differing language and channels of communication, and you will require the feedback
to be different for your own internal communications. (See Figure 1.7.)
10 Principles and Methods of Communication
© Licensed to ABE
MESSAGE TO BE SENT: There has been an outbreak of scabies in the local area.
You represent the local health authority.
Audience Message Most appropriate channel
School teacher and
head teacher
Could you please keep a lookout
for signs of scabies in Class 4 and
make parents aware of symptoms.
Literature. Possibly telephone call
if cases continued to affect one
school/class.
School secretary Please circulate the following
information to all teaching/non-
teaching staff.
Local education authority
department bulletin, enclosing
relevant literature.
Doctor There have been three cases of
scabies in North Ward. Could you
let me know of any in your
practice?
Health Service bulletin.
Worried parent (who
telephones your
office)
There have been few cases, but if
you’re worried I’d recommend
Derbac M available at the chemist
and I’ll send you an information
leaflet.
Telephone call.
Local chemist There has been an outbreak of
scabies; you may need to stock
Derbac M.
Memo to all pharmacists.
Local population Detailed information on symptoms
and treatment.
Information leaflet.
Figure 1.7
This also introduces the notion of supplementary information which may be necessary to take
account of specialist interests.
Interpreting and Feedback
People are important. In dealing with organisations we sometimes lose sight of the fact that not only
do we need to understand the organisational culture, but we do also actually communicate with
people. Personal communication style can be as important in delivering a message as the selection of
the appropriate channel.
Initial impressions are important but like all communications are not a one-way process. The person
receiving the message will be responding to the communicator’s style and vice versa.
The following chart (Figure 1.8) gives an indication as to the effect non-verbal communication can
have on an audience. It will help you to think about the importance of body language in interpersonal
communication and how it can be used effectively when communicating with others.
Principles and Methods of Communication 11
© Licensed to ABE
Body language What people intend to
communicate
What is communicated
Firm handshake Strength, interest, commitment Professional, businesslike
approach
Limp handshake Friendly approach Lack of commitment
Hesitancy
Good personal hygiene Cleanliness Acceptable standards
Poor personal hygiene “Take me as I am” Inattention to self.
Probably not interested in
business either.
Standing very close to the
person you’re speaking to
Trying to establish a rapport,
being friendly
At least an invasion of
personal space, at worst sexual
harassment
Figure 1.8
Clearly the success of the information exchange can depend on the personal impression made by
either the communicator or audience.
The general appearance of communicator and audience and the type of language used will also affect
the communications process. Maintaining a friendly yet businesslike approach is what both parties
should be aiming for. Final selection of words often depends on clues picked up during the course of
conversation. This is why conversations between friends are very different from those between
business partners or in business meetings.
(a) Oral Communication
Speech is such a natural activity that we tend to speak first and think later. This casual
approach could be a problem in business.
Speech should be viewed as a tool for accomplishing objectives. How to plan what to say, how
to say it and manage the impression to be created will be ensured by tailoring remarks and
delivery style to suit the occasion or situation.
(b) Listening
An oral communication is unsuccessful if it does not include listening. Listening may result in
better relationships and better understanding of those with whom we communicate; provide
information; stimulate new ideas; and motivate others to improve their listening skills.
Later in this course we will consider telephone technique and oral presentations in more detail.
(c) Feedback
The impact of a communication is like dropping a pebble in a still pond. The pebble will have
an immediate effect but the ripples will continue for some time afterwards.
Feedback can take place immediately or over a long period of time; it may be the desired
outcome of a series of communications which will take place over several months. Both
12 Principles and Methods of Communication
© Licensed to ABE
communicator and audience can respond to the feedback. It should be an effective valuation
mechanism for the communication and the communication process alike.
C. KEY FACTORS FOR EFFECTIVE COMMUNICATION
Exactly what are we striving for when we communicate? It’s not just about information exchange
within and between organisations. The style of communication we use may depend on the importance
we feel that the information, the contact, or the response may have. It may reflect the status and
standing of all participants in the communication. It may be a supportive or subversive activity. It
may be a chore rather than a pleasure. The sender will certainly vary his or her approach to the
communication independently of the medium or message selection according to what he or she sees as
his or her role in the process and that of the audience. Sometimes the communication may be directed
at one audience but intended for someone with more power in the process. It could be an exploitation
of formal or informal networks dependent on hierarchical status or actual power.
You can never entirely divorce a message from its sender, and will certainly pick up other clues and
information from the sender’s attitude.
Communication styles, then, vary according to the status, perception and attitude of the sender as well
as the medium chosen.
Intentional and Unintentional Communication
(a) Intentional Communication
When you write a letter, speak to a group or make a telephone call, you are deliberately
attempting to transmit information, ideas or attitudes. This is an intentional communication.
(b) Unintentional Communication
All the time you communicate intentionally, you are also communicating unintentionally. As
individuals, we can never entirely assess what additional messages we are communicating, as
these are influenced by the role, perception or status of those with whom we are
communicating.
Even when we send a letter (intentional communication), the recipient will judge it on the type
of language used, the typeface, the handwriting, the letterhead, the paper type or the spelling
used within.
By not addressing the power of the unintentional communication and ensuring that the letter is
accurate and reflects the organisation which sent it, the intentional communication is
undermined.
Personal appearance may convey attitudes at odds with conversation. This may be refreshing at
a dinner party but not at an interview or business meeting.
Similarly, body language and (dare I say it) etiquette are unintentional communication tools.
Personality Perception
People respond to each other as to their perceptions of each other’s personality. As individuals we
function as:
The person we are.
The person we believe ourselves to be.
Principles and Methods of Communication 13
© Licensed to ABE
The person as perceived by others.
These three personalities are often significantly different.
Judgement and Concealment
Often we make a judgement about facts and information we come across. When we pass this
information on to others we subconsciously make an “internal” judgement about what we feel is
important. This may mean that some aspect is emphasised or played down (concealed) depending on
whether we feel it is relevant or irrelevant.
Congeniality
The recipient of a message tends to be more attuned to the message if it is congenial to or confirms
the person’s own frame of reference, i.e. all the attitudes and presumptions that determine how a
person perceives issues and events. It is almost like a filtering mechanism which blocks out
“unacceptable” facts and opinions whilst reinforcing and embellishing information that is more
“acceptable”.
Rumour
Despite our analysis of intentional or unintentional communication, a rumour is the most effective
form of communication within any organisation.
Sometimes rumours are intentional or unintentional leaks of information which become part of the
organisational culture prior to any official statements being made. At other times they are unfounded
but spread rapidly because there is fear and uncertainty and rumour supports existing speculations.
Certainly the rumour chain is like “Chinese Whispers” and the rumour will change form and tone as it
is passed on through an organisation.
Rumours need to be substantiated or denied by persons in authority who have, and are acknowledged
as having, access to the relevant (correct) information.
Status
The confidence that readers and listeners have in a communication is affected by the extent to which
they believe the information and the credibility of the communicator. Much of this credibility is
derived from perceived status.
Teachers are listened to because there is a perception that they are honest, objective and competent.
Estate agents may arouse suspicion because they are trying to make a large commission from the
seller.
Within an organisation, key members have status conferred upon them according to:
Position in the hierarchy
Extent of technical knowledge (expertise)
Ability to convey enthusiasm, sincerity and competence
Prejudice concerning role, job title, gender, race, age
Corporate image
It is important to identify who has status and how they have achieved it in order to ensure that
communications can be effectively disseminated. (See Figure 1.8.)
14 Principles and Methods of Communication
© Licensed to ABE
F
i
g
u
r
e
1
.
8
Principles and Methods of Communication 15
© Licensed to ABE
Effective Feedback or Evaluation Mechanisms
Communication between and within organisations is constantly evaluated and represented. Unless
there is a mechanism/process to deal with incoming or outgoing information, the communications
become worthless.
It is important to record even informal exchanges formally. Many a politician has been caught out by
not keeping notes of expenditure or of what has actually been said.
Most communications require some action, maybe not immediately, but it may well form the basis for
later communications. This is particularly true if you are trying to research attitudes to your
organisation, a particular product or a new concept. A gut feeling that “people think -------” is not
nearly as relevant as “80% of our clients” or “60% of our workforce believe -----”.
Making notes on telephone calls, at appointments, in meetings, after informal meetings, filing letters
and storing data on disc (correctly labelled for retrieval) are simple and effective ways of allowing
feedback and evaluation to take place rather than a series of guesses.
Conclusion
Effective communication within and between organisations is dependent on human relationships and
organisational contexts which influence manner, tone and style.
Information must be appropriate to the context and medium, accessible, clearly presented and attract
attention because individuals receive so many messages and communications.
The credibility of an organisation is dependent on the communication style of the individuals who are
its representatives.
Successful communications do not usually take place in a hostile environment.
We can summarise the key factors in successful and effective communications as:
Relevance
Accessibility
Precision
Attract attention
Congeniality
Credibility
D. THE BARRIERS TO EFFECTIVE COMMUNICATION
For a communication to be effective it is dependent on the nature and quality of the information
which is being sent to the recipient. It also relies on the interpretation placed on the communication
by both sender and receiver.
Because individuals differ so very much from each other it is helpful if, when we communicate, we
understand the nature of those differences and modify our interpersonal behaviour to cope with them.
However, this is not always possible if we have to communicate with a large and diverse audience
which may differ in a number of ways, such as age, interests or culture, and we are unable to
communicate with each of them on an individual basis.
16 Principles and Methods of Communication
© Licensed to ABE
In fact there are many barriers to successful communication and in Figure 1.9 you can see that
“noise”, or barriers to communication, can interfere with the encoding and decoding stages.
Figure 1.9
There are a number of potential barriers which may result in an ineffective communication, which in
turn may cause problems in the workplace. These include:
Irritation
Misunderstanding
Mistakes
Conflict
Barriers to successful communication include:
(a) Technical noise
For example, if a message is not received because of interference on a mobile telephone or
because a fax machine is not working properly.
(b) Physical noise
For example, if an office is too noisy because it lacks sound-proofing or a group is too large so
they cannot hear what is being said in a presentation.
(c) Lack of interest or hostile attitude
For example, if, during a sales presentation, an individual believes a product is not appropriate
for his needs or feels strongly that his valuable time is being wasted, then the person’s message
will not get through what is essentially a very strong barrier.
(d) Poor listening skills
For example, if a group of staff on a training course are not used to sitting down and
concentrating on what is being said then their lack of listening skills might mean that the
message is not successfully communicated.
Principles and Methods of Communication 17
© Licensed to ABE
(e) Information overload
For example, during a meeting a manager might try to give his audience a long list of facts and
figures in a short period of time; this would mean that most of his message would not be
communicated successfully.
(f) Lack of understanding
For example, if someone had a poor grasp of language and used incorrect words such as
“economically variable” instead of “viable”, or the person used technical jargon or
abbreviations which were not understood by the audience.
(g) Psychological noise
For example, if a person at an interview said that he was very interested in the job being
described but started to yawn and gaze disinterestedly out of the window as the interviewer was
speaking.
(h) Perceptual bias
For example, if a person uses selective hearing and tunes out in order to avoid an unpleasant
message or one that does not fit into his pre-existing attitudes and values. An employee
listening to his line manager talk about the importance of team work and its benefits who was
uncomfortable in the team he was currently working in would be likely to “block” the message.
(i) Poor timing
For example, telephoning at lunch times and on Friday afternoons may make it difficult to get
through because the person you need to contact is unavailable; or if you are talking to someone
in an appraisal interview telling them how long-term planning in the firm might affect their
role, they are unlikely to be listening if they know that the next topic concerns their annual pay
rise!
Sample Case Studies
Consider the communication barriers in the following situations. Think about the first example and
review the suggested barriers set out at the end. Then move on to the second example and try and list
the barriers yourself before reviewing the suggestions made.
Example 1
Sally Strict, the Office Manager in Telephone Ordering section, is nearing retirement and has very
conservative ideas about the appearance of office staff and how they should behave.
Ben Brown, the new Sales and Marketing Manager, has a reputation as a “whiz kid” and has overall
responsibility for the Telephone Ordering section. As a result of some last-minute direct response
advertising which he placed last week, he realised that the section would be facing a very busy period
over the next few weeks. Consequently, he made arrangements for a number of temporary staff to
start the following Monday.
Early Monday morning, whilst on his way to a meeting, he telephones Mrs Strict from his mobile
telephone.
“Sall – girl, guess what, I’ve organised some temps because .... (silence as he is in an area with poor
reception) ... anyway can’t chat long because the telephone battery needs recharging ... back in the
office on Wednesday.”
Mrs Strict is very annoyed. Before the telephone call she had already been called to reception to look
after three young women from the local temporary staff agency. The young women were all students
18 Principles and Methods of Communication
© Licensed to ABE
looking forward to earning some money in their vacation. Two of them sat in their chairs yawning;
the other one had very short cropped hair and a ring in her nose. She started to introduce herself but
much to her surprise Mrs Strict said, “I am very sorry but you must be mistaken. The Telephone
Ordering section does not require temporary staff. If we did, I certainly would not want to work with
you three.”
The communication barriers evident in this are as follows:
Technical noise which means that Ben’s message is interrupted and therefore incomplete.
Mrs Strict’s hostile attitude would mean that even if there had been no technical noise, it
would have been difficult for Ben to communicate his message effectively.
Mrs Strict’s perceptual bias against the appearance of the three young temp staff would mean
that, whatever they were to say or do, initially they would find it very difficult to communicate
successfully as she is likely to be selective in the way she listens to what they say.
Furthermore, they created psychological noise so that whatever positive message they wanted
to communicate was contradicted by their appearance and body language.
Example 2
The following extract about Tyrone Crystal and Belleek Pottery comes fromthe Belfast Telegraph, 17
May 1994. Identify where you think there have been barriers to successful communication or a
communication breakdown between Tyrone Crystal and Belleek Pottery.
Principles and Methods of Communication 19
© Licensed to ABE
20 Principles and Methods of Communication
© Licensed to ABE
The extract illustrates a failure in effective communications between the two organisations and also
indicates that there may be internal communications problems which have manifested themselves as
external barriers.
Prejudice, personality and misunderstanding seem to be the hallmarks of this communication.
It would appear that Belleek’s Irish American owner had not identified Paddy Duffy, chairman of the
co-operative which owns Tyrone Crystal, as an important person in the communications process. This
indicates a lack of appropriate research and poor briefing.
Belleek are also interested in purchasing another “Irish tabletop business”. This may have been
interpreted as a lack of interest in or commitment to Tyrone Crystal.
Tyrone Crystal may have had some internal communications problems as indicated by their
reorganisation of the sales network and appointment of a new distributor.
Note also the communication medium used – the press. A further barrier to successful communication
was to reveal information to the press without apparently discussing the issue between the two
organisations.
21
© Licensed to ABE
Study Unit 2
The Basics of Communicating
Contents Page
Introduction 22
A. The Importance of Language 22
Effective Use of Language 23
Influencing Factors in the Use of Language 24
Persuasive Language 24
B. Non-Verbal Communication and Self-Presentation 26
Stereotypes 26
Our Self-image 27
Other Non-verbal Communication Factors 29
Body Language 29
Appearance 31
Application 31
C. Effective Reading 32
Identifying the Right Material 32
Efficient and Effective Reading 33
D. Verbal Skills 34
E. Listening 36
Active Listening 36
Effective Listening 37
F. Effective Note Taking 37
The Purpose of Note Taking 37
Note Taking and Sources of Information 38
Note Taking Techniques 39
Common Problems with Note Taking 43
22 The Basics of Communicating
© Licensed to ABE
INTRODUCTION
In this unit we consider the basic principles underpinning all forms of communication, starting with
how to use language effectively and, in particular, how to persuade – the purpose of most business
communications.
We move on to examine the many non-verbal factors which influence communication, arising from,
usually, unconscious aspects of our own perceptions, attitudes and behaviour. You need to be aware
of these in order to communicate effectively.
The next sections consider key aspects of the fundamental skills of reading, speaking and listening.
Finally, we examine the skill of note taking – the situations in which the skill may be required (which
are more numerous than you may imagine in a business context) and the different approaches which
may be adopted.
A. THE IMPORTANCE OF LANGUAGE
Whatever channel of communication you use – written or oral, face-to-face or via some intermediary
– the effectiveness of the message will be largely dependent on the individual words selected to reflect
your meaning. Even if you utilise signs or images, the recipient’s response will be coded in language.. Oracy (or oral communications) is as word-dependent as literacy (written communication).. We may fail to notice catchphrases or tags which we use
again and again either in oral or written communications, for example:
“Uh-huh”
“Yeh”
“You know”
“It’s amazing”
“Swings and roundabouts”
Language has a purpose to communicate. This does not mean that it is always straightforward.
Careful phrasing and information can change the entire perceived meaning of a phrase or sentence,
e.g.:
“Do you think we need to use Susan in the production briefings?”
“Well, she’s very competent ---”
You can feel the “but” in that response and yet nothing detrimental about Susan has been uttered.
The Basics of Communicating 23
© Licensed to ABE
The inappropriate use of foreign languages is deliberate and aims to establish either superiority or a
sense of unity, for example:
“Pretentious? Moi!”
To complicate matters further, the recipient of your communication may well have a different set of
meanings attached to the words and phrases you use and thus view your message in an altogether
different way from the one which you intended.
“The relationship between academic theory and marketing practice is a reflection of their
relative positions in terms of the key dimensions of differentiation and cost-effectiveness.”
What does this mean? What it does illustrate is a total lack of understanding of its own statement. It
is also a combination of different ideas meshed together to form incomprehensible jargon.
Effective Use of Language
“Sticks and stones may break my bones
But words will never hurt me”
Would that this were true! It is not just the words of others which can hurt us, but our own words
which can injure our reputation or professional status.
How, then, can we use language that accurately reflects our objectives and is clearly understood by
those with whom we communicate? There are a number of ground rules or basic techniques which
underpin any effective communication – oral, visual or written.
Keep the aims of the communication firmly in mind.
Plan the communication – channel, location, time, person(s).
Aim for brevity.
Ensure ideas are clearly expressed.
Keep to relevant points.
Avoid unnecessary jargon or technical words.
Prefer the simple to the complex.
Check that the communication is logically structured.
Know what you are communicating about: be adequately briefed.
Use appropriate tone and style.
Use appropriate language (i.e. French, English, etc.) that is understood by all parties.
Be positive.
Review and assess for errors.
Don’t allow your language to become boring, cliché-ridden, insincere or hypocritical.
Don’t patronise.
Don’t waffle.
Respect the views and opinions of the recipient.
Be able to respond to feedback.
Plan and evaluate the communication
24 The Basics of Communicating
© Licensed to ABE
Influencing Factors in the Use of Language
The following factors influence not only your use of language but that of the receiver of your
communication:
Age
Culture
Gender
Race
Religion
Status
Context
Education
Technical knowledge/expertise
Organisational culture
Previous meetings/experience
Note that the “global village” means that more and more organisations are working with other
organisations from all over the world. The development of the EU will mean an increasingly
European environment for British organisations. The appropriate use of language becomes more and
more apparent.
Errors in product names or slogans as a result of not taking the culture or language into account have
abounded. For example:
“Hoover sucks”, which is banned in the US.
“Sellotape”, which is a brand of condom in Australia.
“Bums” – crisps sold in Spain, which are not available in the UK under this name.
In France it is advisable to avoid “Franglais” – a sensitive political issue! (Le parking, le stopping --)
Persuasive Language
Persuasive communication techniques are essential for an effective manager in the whole range of
business activities:
Presentations
Internal marketing communications
External marketing communications
Meetings, briefings
Personnel issues
Negotiations
It is always important always to consider issues or ideas from the other person’s point of view (be
customer-oriented) and determine what’s in it for them before making any representation. In this way
communications can be positive not negative, and the communication has the scope to be proactive
not reactive.
The Basics of Communicating 25
© Licensed to ABE
If you want to persuade, be positive and customer-oriented. Hence:
“Sales are up by nearly 50%.”
NOT: “We’ve only managed to sell 20 so far!”
“This is going to be a really wonderful family event with lots of attractions.”
NOT: “There’s going to be lots of screaming children and overpriced fairground rides.”
The purpose of persuasive communication is to harness and utilise skills which seek to convince,
motivate, exhort and influence for a particular purpose and in a specific context. It may be used to
lead decision-making, support management objectives, advertise, sell, lobby or promote.
Often the persuader will use more emotive vocabulary, short sentences and accentuate the positive.
He or she may feel it necessary to be less formal and more familiar in the use of particular words or
phrases.
The persuasion may take the form of offering alternatives which have obvious disadvantages for the
recipient which the original proposal does not share.
The skilled persuader will also be aware of how best to present the outcome of the communication to
his or her own organisation.
Advertisers are the most obvious example of professional persuaders. Yet the product, service, idea or
proposal must have genuine merit as perceived by the recipient of the message, or he or she won’t be
persuaded otherwise.
In the majority of business communications persuasion is used as an effective negotiation skill.
Careful phrasing of correspondence, whether it is formal or informal, will reflect your meaning
accurately and be appropriate to the context.
Persuasive language has a place even in briefs or reports, as it is a way of phrasing which accentuates
the positive without resorting to slang or inappropriate language.
The following examples show how persuasive language elicits favourable or positive responses:
(a) “As a result we are highly effective in building new business opportunities.”
(b) Compare the following:
(i) “The CBI Quarterly Industrial Trends Survey for smaller business reveals a strong
increase in orders and output in the four months at rates faster than expected.”
(ii) “There was a significant increase in orders and output in the four months.”
(c) “It’s packed with leading edge Pentium technology, at very down to earth prices.”
(d) “Help you plan and install completely integrated presentation systems in your training room
or board room.”
(e) “Will become the leader in its market in terms of its unmatched product offering and its
unrivalled service to customers.”
(f) “Give your brand the crucial edge which will make it stand out from the crowd.”
(g) “The purpose of this report is to illustrate how X can shape the future for training provision.”
26 The Basics of Communicating
© Licensed to ABE
B. NON-VERBAL COMMUNICATION AND SELF-
PRESENTATION
The way we perceive others and they us is often a result of a series of assumptions which we make as
to their status, attitude and potential response to us and our communication.
Remember we are all three people:
(a) The person we are.
(b) The person we think we are/would like to be.
(c) The person that other people perceive.
How we present ourselves may not be a reflection of how we perceive ourselves or would like to be
perceived. Certain aspects may predetermine others’ perception of us:
J ob title
Status
Gender
Age
Background
Use of language
Appearance
Accent
Stance/attitude
Gesticulation
How others choose to respond to the non-verbal signals that we send will be a combination of:
Their prejudices, perceptions and attitudes.
How we choose to present ourselves.
Our understanding of the communication process.
Stereotypes
Stereotypes may be damning and unrepresentative but are useful hooks on which to hang our
impressions (correct or otherwise). These stereotypes may be influenced by media presentation of
types of individuals or groups, or based on our own experiences and relationships. Categorising
people by job title or status is one of the easiest ways of imposing a stereotypical view.
Hence doctors or teachers will be perceived as reflections of our own prejudices and relationships
with doctors or teachers we know and have known. If introduced to someone by job title, your instant
response is to sort this information internally and decide what the implications are of that information.
As you converse with or observe that same individual, you will either reaffirm or adjust your
perceptions accordingly.
J ust to illustrate how persuasive these types are, complete the following Table (Table 2.1) by filling in
the gaps.
The Basics of Communicating 27
© Licensed to ABE
Table 2.1: Considering stereotypes
Job Title Gender Age Type of Car Type of Housing
Primary school teacher 28
Lawyer Male
E-type J aguar Town house
Nurse 42
Dentist
There is no correct answer, but the answers you give will be a reflection of your own thoughts,
attitudes and perceptions of these job categories or titles.
Remember that a lot of prejudices need to be challenged and that our collection of assumptions will
not represent any individual. Effective communication cannot be if it is pervaded with entrenched
outmoded or unnecessary assumptions about people. We need to ask ourselves continually:
Exactly who are we communicating with?
Anecdotal evidence abounds of salespeople only attempting to sell household goods to women, and
building services to men. Why? This may be correct in some instances, but if they listened to and
really attempted to communicate with their customers, they could find out who is making the
purchase decision and sell to, rather than offend, them.
Our Self-image
Our self-image is influenced greatly by the way we think others see us, and sometimes we may
deliberately attempt to create an image which we think others will find more acceptable.
Maybe we overestimate or underestimate ourselves or simply misread people’s reactions towards us
because of a lack or surfeit of confidence or our own prejudices.
What self-presentation does is convey our personal qualities, not our expertise or knowledge.
Try completing the exercise in Figure 2.1. First fill in the boxes in the “How I see Myself” section, as
honestly as you can, to show what most accurately reflects your self-image. Then, complete the
second section indicating what you think others think of you. If you are really brave, you could ask
someone who knows you well to complete this section to get a more objective view!
What this exercise should do is point out any differences between your self-image – what you feel you
project – and how others see you. It may be that “you” are different with different people and in
different contexts – at work, at home, with friends.
28 The Basics of Communicating
© Licensed to ABE
How do I see myself?
Friendly Unfriendly
Happy Miserable
Outgoing Shy
Even-tempered Quick-tempered
Honest Arrogant
Intelligent Unintelligent
Professional Good sense of humour
Tolerant Nervous
How do others see me??
Friendly Unfriendly
Happy Miserable
Outgoing Shy
Even-tempered Quick-tempered
Honest Arrogant
Intelligent Unintelligent
Professional Good sense of humour
Tolerant Nervous
Figure 2.1: Self image
The Basics of Communicating 29
© Licensed to ABE
Other Non-verbal Communication Factors
In addition to status assumptions, other influencing factors in the communications process which are
non-verbal will be:
(a) Body language:
Facial expression
Eye contact
Posture and stance
Physical contact
Gestures and gesticulation
(b) Appearance:
Style
Appropriateness of clothing to situation
Attention to appearance
(c) Reading skills:
Ability to understand text/information
Being able to read the gaps
Body Language
(a) Facial Expressions
Whilst generally accepting that a smile is a gesture of warmth and friendliness, psychologists at
Dartmouth College have discovered that many of us mistake phoney smiles for the real thing.
We probably don’t notice the difference because we don’t want to and accept phoney smiles as
genuine. We feel better about ourselves if we think people like us.
The subtlety of facial expressions is determined by the type of eye contact we encounter. It is
important to look people straight in the eye when talking to them. Looking upwards,
downwards or to the side indicates that they are not worthy of our full attention and therefore
lack significance. Establishing eye contact creates a bond between participants. If you feel
unable to do this, by focusing between the eyebrows of the person you are addressing it will
appear that you are looking directly at them without your feeling committed to an undesirable
Staring at people or being stared at is very discomforting. Indeed, if you stare at a part of a
person’s face, he or she will become acutely aware of this and scratch or touch the place
concerned.
Trying to “read” people’s facial expressions is an important aspect of communicating with
them, as it will give clues as to their responses to your oral or written proposals. (See Figure
2.2.)
30 The Basics of Communicating
© Licensed to ABE
Figure 2.2
Winking or twitching, scratching, sniffing or snorting are all characteristics which are
unattractive and draw attention to the individual concerned, not the purpose of the
communication.
(b) Posture and Stance
In business situations you will probably stand or sit, enter or leave a room. How you do so will
form an immediate impression.
Standing attentively is actually easier to achieve than sitting attentively yet comfortably.
Slouching, leaning forward, and arms crossed all give impressions of our attitude, not our
physical comfort.
Consider the attitudes that the following postures indicate:
Leaning forward on desk
This can indicate attentiveness or be representative of overfamiliarity/dominance of the
other person’s personal space.
Perching on edge of seat
This is usually perceived as nervousness, being ill at ease with the situation or individual.
Fiddling with pens/paper, etc.
This indicates either boredom or nervousness; either way it shows a lack of commitment
to the meeting, a feeling that your “mind is elsewhere”.
Arms folded tightly across chest
This is a classic defensive position. Arms crossed lightly can be a useful position for
those who don’t know what to do with their hands.
Reclining in seat
Possibly a little too relaxed!
The Basics of Communicating 31
© Licensed to ABE
Biting nails, scratching
Not only does this indicate nervousness or boredom but the habit becomes the focus of
the meeting rather than the information. The other person will find this extremely
irritating and may not view any proposals made with favour.
(c) Physical Contact
Physical contact is much more than a firm handshake, or even a firm handshake accompanied
by looking directly into the eyes of the person with whom you are communicating. It is about
personal space and how sensitive you are to the spatial requirements of others. Touching is
rarely appropriate in the business context and compulsive touchers may be viewed as
overfamiliar or rude and overbearing.
(d) Gestures and Gesticulation
Shaking or nodding your head indicates disagreement or collaboration; a thumbs-up sign in a
meeting may not be appropriate!
Scratching the nose may be viewed as being thoughtful, as will resting the hand under the chin.
The problem with gestures and gesticulation is one of recognising those gestures we use all the
time which may not be viewed favourably by others. Excessive gesticulation (hand
movements) is very disconcerting and becomes the focus of the communication.
Appearance
It is sad but true that we judge and are judged by appearance. The first impression is as critical to the
success of business communication as the contents of the meeting, brief or presentation.
Clothes do not make the man (or woman) but they do help others to make an initial assessment of him
(or her).
We can summarise the impact of appearance as follows:
(a) Personal style – how we choose clothes that reflect our personality and suit our
physical shape/type
(b) Appropriateness – wearing appropriate clothes dependent on the context or situation.
On management weekends it’s often hard for delegates to strike the
right balance between formal and informal clothing.
(c) Attention to appearance – this includes whether clothes are clean, ironed, fit, or have buttons
missing; whether shoes are scuffed, colours match and don’t clash;
also use of colour.
Application
By developing an understanding of how non-verbal characteristics may influence the effectiveness of
the communications process, you can place much more emphasis on what you actually intend to
communicate. You will be enabled to:
Plan your meetings.
Be ready with alternative approaches to the situation.
Use the location to your advantage (possibly by choosing one with which you are familiar or by
arriving early to check entrances, seating plans, etc.).
32 The Basics of Communicating
© Licensed to ABE
Discourage interruptions which will influence the non-verbal impression you give, e.g.
telephone calls, visits.
Sit or stand comfortably and in your own personal space.
Appear relaxed, interested and committed to the exchange.
Avoid overfamiliarity in words, language or gestures.
Check your appearance.
Retain eye contact at all times.
Talk clearly, avoiding jargon or gabbling.
Listen.
C. EFFECTIVE READING
The ability to grasp the salient points of a text is an increasingly important non-verbal communication
skill. Not only do you need to recognise and interpret bias, but you must also select information
which is of use to you and your organisation. Scanning or skimming texts is a technique best acquired
with practice, but by recognising key words and phrases the importance of the text in a newspaper,
magazine or journal can be restricted to one relevant article instead of laboriously poring over each
page. Look out for the gaps in the text. What information is missing? Why is this the case? What
organisations choose not to let you know is as fascinating as what they reveal.
Remember that most sources of printed literature represent carefully phrased and structured accounts
of ideas, events or issues. Use written texts to your advantage.
There are certain techniques which you can use to develop the effectiveness of your reading, and we
consider these here in respect of selecting the right reading materials and reading efficiently and
effectively
Identifying the Right Material
You clearly need to determine if won’t read it!)?
is the publication arranged in a way which makes it easy to find what you need?
is the style of writing such that you would want to read it?
You may fell there are Basics of Communicating 33
© Licensed to ABE writer's style is
important – whilst your reaction is a very personal thing, you need to feel comfortable with
reading your source material, if at all possible..
Efficient
34 The Basics of Communicating
© Licensed to ABE.
D. VERBAL SKILLS
Face-to-face communication is not wholly dependent on non-verbal skills. How we express ourselves
verbally and respond to the language of others is fundamental.
Verbal communication is not just about which words we choose, but also encompasses the following
factors:
Pronunciation
Accent
Clarity of speech and expression of ideas
Choice of language (specific words)
Use of foreign words
J argon or technical words and phrases
Stress
Tone
Volume (are you audible to your listener(s)?)
Rhythm and pace
Articulation
These factors are important whether we are communicating with one person or a group of people –
and, indeed, some may be equally applicable in written communication.
We speak to make ourselves understood: to convey our thoughts, ideas and proposals. Verbal
communication is an activity where we can form an actual and immediate relationship with those with
whom we communicate in a way that written communication cannot.
However good our overheads or preparation and our understanding of non-verbal communication, if
we lack confidence or are unable to articulate our thoughts the communication will fail. This
immediate and personal relationship with our audience is the arena where much business takes place.
Networking is, after all, based on verbal communication. There is, however, little point in identifying
the right people to network with if you are unable to communicate with them.
(a) Pronunciation
Regional dialects are only relevant if you are going to use pronunciations or specific
words which only those from a particular region will understand; otherwise you may risk
alienating your audience.
Strangulated vowels or pronunciation is irritating.
The Basics of Communicating 35
© Licensed to ABE
The word “bath” is perfectly acceptable as either “barth” or “baath” or “bath”, but “barf”
or barrth” sound contrived. Try saying these aloud and you’ll see what I mean.
An affected accent is insincere.
Take care to speak slowly if your audience do not have the same accent as yourself.
(b) Clarity
If you plan what you have to say and understand both the points you intend to make and the
potential objections to them, then you ought to be able to express your ideas and proposals
clearly and simply.
Your ideas should follow a logical sequence and allow the listener the opportunity to consider
each point in turn. A circular or apparently random argument can quickly deteriorate into
arguing over minor issues, because no one is quite sure what the major issues are.
(c) Choice of Language
Sometimes slang words are permissible in oral communication in a way that they will not be in
written text.
“OK” or tags like “Fine”, “Very good” can be used in response to questions. Swearing is
usually inappropriate.
Avoid over-complex phrases or jargon. Technical words are best used in relevant contexts or
learned journals, not to parade your knowledge and others’ lack of knowledge. The purpose of
the exchange is to communicate, not self-aggrandisement.
(d) Stress
You may choose to stress important words or syllables, much as you may highlight or underline
written text.
Stress may change the meaning of an entire sentence. For example:
We may need to improve sales by 10%.
We may need to improve sales by 10%.
We may need to improve sales by 10%.
In speech you may choose to phrase a sentence differently than you would in text to achieve
different emphasis.
For example:
“I think we might have to improve sales by 10%.”
“Unless we can achieve a 10% improvement in sales -----”
“Based on last year’s figures an increase of 10% looks likely.”
“A 10% improvement in sales is what we’re aiming for, for the period -----.”
(e) Tone
The tone of your voice indicates your emotional response and enthusiasm for what you are
saying. Consider the following sentence and say it to yourself as if you are amazed, curious,
angry, disapproving or sympathetic. The words don’t change but your tone and the stress you
place on particular words will.
“When did you get back?”
36 The Basics of Communicating
© Licensed to ABE
(f) Volume
Make sure that people can hear you, but don’t shout or heckle them. The volume of a person’s.
(h) Articulation
Failure to speak clearly results in ambiguity and misunderstanding. Avoid:
Mumbling
Hesitancy
Reading every word like a “robot”
Missing off the beginning or ends of words
E. LISTENING
Managers spend approximately 60% to 70% of their time communicating with individuals or groups,
and of that time, approximately 55% to 65% is spent listening. Improving listening may result in
better relationships and better understanding of those with whom we communicate; provide
information; stimulate new ideas; and motivate others to improve their listening skills.
Conversely, not listening can result in many misunderstandings, particularly if a message has then to
be conveyed to others. Individuals may miss appointments, fail to grasp the salient facts of a
communication, or fail to hear the name of the person they are speaking to. In an emergency, not
listening could prove fatal in a business communication. Particularly in a customer-oriented
environment, not listening to internal or external individuals, groups or markets could prove fatal to
the development or existence of that business.
Active Listening
Listening is an active, not a passive, activity. It requires understanding of the communication and the
ability to make effective judgements on what is heard. Many breakdowns in communication take
place because people don’t listen attentively to what is actually said, but to what they would:
(a) Like to hear; or
(b) Expect to hear.
Active listening is characterised by positive body language and an attentive pose. It may be necessary
to summarise what has been said at key moments to ensure that both parties have understood the
communication.
There are three levels of listening:
Attentive listening, for important or highly relevant information.
Empathetic listening, to attune oneself with the speaker and to seek common ground in
appreciation of his or her attitudes, feelings and emotions.
The Basics of Communicating 37
© Licensed to ABE
Casual listening for pleasure, where we may respond in a more light-hearted way and use puns
and double meanings as a means to enjoy the actual language used.
Effective Listening
Most of us do not listen effectively for a variety of reasons.
We comprehend faster than we speak.
External distractions compete for our attention.
We don’t take the time to listen.
We don’t know how to listen.
We allow our own emotions and prejudices to filter what we hear.
Effective listening can be achieved if we:
(a) Listen for facts and remember key words.
(b) Listen for feelings, interpret the speaker’s point of view, observe his or her non-verbal
communication, and listen to what isn’t said.
(c) Do not tune out to unpleasant messages that we are not keen to hear.
(d) Clarify what is being said by asking questions where relevant.
(e) Give a reflective summary (if it is appropriate), which briefly paraphrases what the other person
has been saying; you then know that you are both on common ground.
Informal as well as formal channels of communication will utilise oral or spoken communications to
convey all sorts of information. Oral communication may not merely be on the level of a
conversation between individuals but could be in the form of a video, a filmed presentation or video
conferencing. Oral communication is often the most widely used form of communication, but lacks
the stature of written or technological forms because it appears to be less formal and less tightly
organised.
To be effective within your organisation, you need to make use of and understand all forms of
communication. Effective listening is a vital ingredient in sharing and acquiring important business
information.
F. EFFECTIVE NOTE TAKING
Note taking is a way of formalising all the ideas and research which you carry out at all times in order
to be well informed and to function efficiently at work. Note taking encompasses apparently casual
conversations, business meetings, television or radio programmes, trade journals, newspapers,
magazines, advertising, ideas or responses to window displays, fine art, design, architecture or views.
Over time, note taking is an analytical skill which provides you with back-up data and ongoing
relevant market research. It also helps you to keep an open mind to new influences and to connect
ideas and events with projects or proposals with which you are involved.
The Purpose of Note Taking
The main reason for note taking is often assumed to be to provide a written record of a spoken
presentation or event which can be referred to at a later date to aid recall. Whilst this is undoubtedly
38 The Basics of Communicating
© Licensed to ABE
true, it rather misses a key point about note taking – that the way in which you interpret and record
information in taking notes can, in itself, be an invaluable aid to learning.
When you make notes, from whatever source, you are necessarily sifting, summarising and shortening
the full information. This is a key aspect of any research. You are selective about what you record, so
you pick out the key points, and then write them down in your own words. “Your own words” might
be the same as the way the information was expressed by the source, but are very often different to
reflect your own individual way of understanding it.
Thus, note taking serves two purposes:
to aid learning; and
to facilitate recall and/or retrieval of the information..
Acknowledging sources of information is often important and it is useful to keep a record of the
sources you consult at the time, possibly on cards which have publication details and perhaps
very brief notes about the content, so that you can build up a file of references.'ve
The Basics of Communicating 39
© Licensed to ABE
notes. At times, particular visual displays may be used by a presenter to make or record points
– handouts, overhead projector slides, flip charts, etc. These can also be used to help in your
recording of the event.
J ust as it is important to keep a record of your written sources, so it is with oral sources. You
should always note the date and overall subject, as well as perhaps the time and other
participants where these may be significant for future recall..
Records of an event are often formally produced in the form of reports and minutes. This
doesn't necessarily mean that you don't have to take your own notes. You may want to check
the official record against yours, or at least perhaps keep your notes together with it.
Lecturers and trainers also often produce records of an event in the form of copies of their own
structure notes and visual displays. These can help to develop or complement your own notes,
or even be used and annotated with your own thoughts and interpretations.
Note Taking Techniques
Everyone has their own individual styles of note taking. Some people take a lot, others very few.
Some prefer to make notes after the event, although most elect to make notes during it (often for the
simple reason that they know they'll never get around to it if it's left until later!).
There is no right or wrong way. Whatever suits you, and achieves its purpose in terms of assisting
learning and facilitating retrieval, should be fine.
There are a number of general principles behind note taking, and some specific techniques which you
can use.
(a) General principles
We can identify four general points about note taking which apply irrespective of the source of
information, the nature of the research, or the technique you use.
The fundamental principle is to be selective. Don't try to write everything down, but pick
out the key points, words and phrases.
Translate into your own words as much as possible. This involves reflection and
conceptualisation and, thus, helps understanding and learning.
Use abbreviations – common ones or your own system. As long as you can understand
them later, it doesn't really matter how obscure they might be to someone else.
40 The Basics of Communicating
© Licensed to ABE
Structure your note taking around the key points in a way which brings out the
connections between all the different points. A number of different methods of doing this
are considered below, but they all involve identifying and highlighting the most
significant issues and linking subsidiary points to them.
In this connection, use of different colours or highlighter pens can be useful, although
chopping and changing between pens can sometimes be distracting and time-consuming.
(b).3.
Innovation
Are innovation and change the same thing?
Change: Can be slight
adaptation minimal
transformation at other end
** moving from one state to another
Innovation: novelties / changes
originality / creativity
Related concepts and associations:
1. Progress: moving forward,
more positive
future
(evolution, achievement)
2. Creativity: imagination, inventiveness
discovery
strong link inspiration, intuition
3. Development: increase, augment
advance / extend, etc.
Figure 2.3: An example of linear notes
The Basics of Communicating 41
© Licensed to ABE
(c) Spider diagrams
This approach shows connections in a different way – graphically. The best way of explaining
it is to illustrate it, as in Figure 2.4..
42 The Basics of Communicating
© Licensed to ABE
Figure 2.4: An example of a spider diagram
The Basics of Communicating 43
© Licensed to ABE identify certain things about the form of presentation which either facilitate or hinder the
making of notes. These factors can be divided a good presentation when you
experience one, but also to assist you when you need to present information – in either written or oral
form.
44 The Basics of Communicating
© Licensed to ABE
45
© Licensed to ABE
Study Unit 3
Written Communication
Contents Page
Introduction 47
A. The Written Word 47
Written Compared with Oral Communication 47
Purpose of Written Communications 48
Forms of Written Communication 48
B. General Approach to Business Correspondence 49
Letters – First Impressions 49
Purpose of Letters 50
Format of Letters 51
Hand-written Letters 53
Sending a Fax 53
Keep It Straightforward and Simple (KISS) 54
Style 55
Use Business Correspondence to IMPRESS 55
C. Business Correspondence – Practical Applications 56
Standard Letter Format 56
Letters of Recommendation 56
Dealing with Complaints 57
Letters of Application – Standard Format 58
Internal Communications – Memoranda 58
Briefs 60
D. Reports and Reporting 60
The Reporting System 60
Classification of Reports 61
Business Report Formats 62
(Continued over)
46 Written Communication
© Licensed to ABE
Writing a Report 63
Reading a Report 64
Sample Reports 64
E. Writing Articles 68
F. Preparing and Placing a Press Release 68
Writing a Press Release 68
Placing a Press Release 69
Typical Press Release Layout 70
An Article from a Press Release 70
Example 71
G. Writing an Effective Mailshot 73
Example 73
Written Communication 47
© Licensed to ABE
INTRODUCTION
In this study unit we are going to look at the importance of written communication, its purpose and
the forms it can take.
We start by discussing how to approach business correspondence in general – concentrating on letters,
memos and briefs, as these are the basic forms of communication in the business context – and the
particular requirements of matters such as letters of recommendation and complaints.
We then go on to look at report writing, beginning by considering the reporting system in general and
the various types of business report, including appropriate formats. This is followed by a
consideration of several types of reports, before considering the different skills required to write
articles.
Finally, we consider how to place and construct communications for public relations and direct
marketing purposes using press releases and mailshots.
A. THE WRITTEN WORD
Written Compared with Oral Communication
Written correspondence within or between organisations so
48 Written Communication
© Licensed to ABE
bereft of those interpersonal skills and allows us to judge and interpret the actual words in order to
make a considered response.
Purpose of Written Communications.
Forms of Written Communication
There is a whole range of formats where information is written down:
Memoranda
Letters
Notes
Magazine and newspaper articles
Instructions
Labelling
Databases
Books
Directories (including telephone directories)
Pamphlets
Wills and legal documents
Company literature
Postcards
Signs
Briefs
Written Communication 49
© Licensed to ABE
Reports
Business plans
There is a notion of “inter-textuality” where behind every text is another text, and that there is no such
thing as an original word or article or idea as everything has already been phrased in some way
before.
Certainly every time you write a report, letter, make notes or send a memo, you will have made
reference to previous written correspondence.
For the purpose of written communications within the business context, the forms that you need to
make best use of are:
(a) Letters;
(b) Memoranda (plus notes);
(c) Briefs; and
(d) Reports.
As letters, memos and briefs are the most frequent form of written correspondence/communication
within or between organisations, we shall start by examining these formats.
B. GENERAL APPROACH TO BUSINESS
CORRESPONDENCE
In the next two sections we will concentrate on the design, implementation and evaluation of business
correspondence. Or,. It is a physical document and will be judged by the
recipient as such.
It is worth first considering the actuality or physicality of a letter. What is it? Usually, sheets of paper
presented within a paper or card envelope. Note the following, however:
(a) Paper Quality
The weight, colour and texture of the paper used will make a statement about the person or
organisation who sent the letter and how they view the recipient. For example, poor quality,
dirty or even coloured paper will reflect a lack of interest in, or commitment to, the
correspondence. Is it folded to fit the envelope or does it appear to be shoved in?
50 Written Communication
© Licensed to ABE
(b) Envelope
Does the envelope match the letter?
Does it have a window?
Was it franked or stamped?
Is the sender’s address printed on the back of the envelope?
Bills and invoices are more likely to arrive in envelopes with the sender’s address on the
reverse.
A brown window envelope always used to signify a tax demand; white window envelopes
indicate a seriousness of purpose, although this effect will be lost if the address is not displayed
accurately because the letter has been incorrectly folded.
(c) Logos and Corporate Image
Is the company logo represented on the letter and envelope?
(d),
dinner/function invitations, relevant media articles, questionnaires
Responding to complaints
Summarising key or salient points made at a previous meeting
Arranging future meetings, perhaps including possible agendas
Updating or mini progress reports
J ob applications
Written Communication 51
© Licensed to ABE
Format of Letters
Many organisations are introducing a standard template which determines the spacing and layout of
all letters. With the increase in more complicated and varied stationery and logos, it is important that
text can actually be reproduced on the page.
The registered office address, number and location of registration
An example is shown in Figure 3.1
There are no rules about letter layout except to state that layout should be consistent, legible and
within the frame of the letter spacing. Even historical ideas about positioning the address have
changed – there are many variations nowadays.
Envelope layout is more straightforward. If you are using FREEPOST or prepaid envelopes, the Post
Office have strict guidelines as to presentation, and need to approve your envelope design.
It is worth noting here that FREEPOST operates on a licence basis, where you open a FREEPOST
account having received authorisation/licence on payment of a small fee and envelope design
approval. Thereafter you pay for FREEPOST envelopes made use of, not for every FREEPOST
envelope you have printed. The Post Office will deduct the correct sums from your account (either
first or second class) and instruct you to keep a reserve sum to cover the costs of these transactions.
The Post Office Guide indicates Post Office Preferred envelope sizes and address layout. Clearly they
will advice you to use the relevant postcode to aid speedy delivery of your correspondence.
52 Written Communication
© Licensed to ABE
ABC BUSINESS
TRAINING
62 George Street, London SW21 4DX
Tel: 0208 666 5565 Fax: 0208 555 6656
Chairman: Gary Davies BA FCA • Managing Director: J ulie Gill
ABC-DEF PUBLICATIONS LTD
Registered office: 62 George Street, London SW21 4DX, England (No. 123454321)
Figure 3.1: ABC Letterhead (Mythical company) – Reduced
Written Communication 53
© Licensed to ABE
Hand-written Letters
Whilst it is commonly perceived to be more acceptable to send typed or word-processed letters in
business correspondence, it is important to consider how hand-written text could be advantageous.
Firstly, the signature needs to be hand-written each time it appears; a photocopied signature is sloppy
and lacks care for the recipient.
If the letter is typed, then the envelope should be too. Where time is an issue, for example a mail shot
to potential or actual customers, use window envelopes.
If you feel that you need to convey additional warmth in response, perhaps, to a letter of complaint or
to congratulate a colleague on the success of a joint venture, a hand-written letter may be appropriate.
Do not, however, be lulled into thinking that a hand-written!
It is perfectly permissible, incidentally, for a letter of application to be hand-written.
Sending a Fax
Modern technology allows us to communicate world-wide in a matter of minutes either by telephone
or fax. The quality of fax paper can be the determining factor as to its reception and may lead to faxes
being used selectively.
For example, even if your fax machine can reproduce colour logos and uses letter quality paper, the
recipients of your faxes may not have such machines. What they receive may be a blurred logo and
complicated document or important letter on shiny, flimsy fax paper.
If faxes are to be as effective as letters/posted or hand-delivered written communications, then the
following points are worth considering:
(a) Is your logo/letterhead fax-friendly, i.e. will it reproduce well in black and white?
(b) Do you ensure that you send your faxes on headed paper and continuation sheets?
(c) Do you number all pages of the correspondence?
(d) Is your fax number clearly printed on your letterhead?
(e) Have you “blocked” the correspondence so that all text will be faxed and you won’t lose the
top/bottom or words on the right or left?
Try to leave at least a 1.5 cm margin around the entire text on each page.
(f) How urgent is the correspondence? Would it be better to send a good copy by post or even to
hand-deliver it?
(g) Keep your copy:
(i) As a record of the correspondence as you would all other correspondence; and
(ii) For amendments over the telephone which can occur in design briefs, advertising layout,
job descriptions and presentation details.
(h) Remember that it’s impossible to make notes or corrections on the flimsy fax paper – you have
to go to the trouble of photocopying it first onto better quality paper or rewriting/typing.
(j) Is it cost-effective to send a 40-page brief by fax?
54 Written Communication
© Licensed to ABE
(k) A fax is excellent in the following circumstances:
(i) For confirmation of details/booking/orders.
(ii) As an external memo system.
(iii) To send initial drafts or proposals.
(iv) As an immediate written response to an external request for data.
Keep It Straightforward and Simple (KISS)
Dealing with written correspondence is often an underrated function in organisations; yet in a
marketing-oriented organisation it is recognised as crucial for effective and ongoing relationships with
actual and potential customers.
Marketing correspondence is not just about carefully phrased mail shots or sales literature, but what
responses are made to customers.
Letters of praise are wonderful to receive and may require an acknowledgement to the sender and
careful internal communications to those praised and those not praised. Letters of enquiry or
complaint need to be dealt with even more sensitively and should reflect internal communication
procedures for dealing with all information received by the organisation.
Hence all information received and transmitted must be planned, evaluated and stored appropriately.
A carefully worded letter of complaint cannot be answered by a hasty fax or telephone call. It
requires the same care in its response.
Sometimes you may be in the position to make the letter of complaint and you must be very clear why
you are complaining, whether the complaint is justified and if there are any legal ramifications for
either or both parties involved.
Written Communication 55
© Licensed to ABE
An improved system for dealing with external communications
The key to the written response to the complaint is to KISS your customer! KEEP IT
STRAIGHTFORWARD AND SIMPLE.
Style
You should use the most effective words in the most appropriate order, reflecting the content and
context of the correspondence.
Consider the following examples:
Dear Sir,
Sorry I can’t see you on Tuesday, I’m
going to visit my mother.
Dear Dr Smith,
I regret that I am unable to attend our
meeting scheduled for Tuesday 12 J uly
19... Would it be possible to rearrange it
for 19 J uly 19..?
We are unable to deliver the goods you
ordered before mid-April.
The goods you ordered will be delivered
by 22 April 19...
As a result of our recent successful
interface I feel that we can embrace the
concept of partnership and mutual
development.
I felt that our meeting was most
successful and would like to pursue the
possibility of joint ventures.
In view of our recent reorganisation and
increase in labour costs, a surcharge is to
be levied on all goods from 1 April 19...
A 10% increase in prices – a 100%
increase in quality.
A 10% surcharge is, regrettably, payable
on orders under £6 to cover postage and
packing.
Use Business Correspondence to IMPRESS
Idea – what is the purpose of the correspondence?
Method – plan and structure your main points.
Paragraphs – open and close your letter.
Recipient – to whom are you sending this letter?
Emphasis – what tone do you want to adopt? Use appropriate language to achieve this.
Style – KISS the recipient.
Safety – check for errors, omissions or even legal ramifications/requirements.
56 Written Communication
© Licensed to ABE
C. BUSINESS CORRESPONDENCE – PRACTICAL
APPLICATIONS
Standard Letter Format
The following apply to all types of letter:
(a) Appropriate greeting – “Dear Sir”, etc.
(b) Opening paragraph – puts the message into a context.
(c) Middle paragraph(s) – develop(s) the detailed message.
(d) Closing paragraph – states action needed.
(e) Appropriate ending – “Yours” etc.
Remember that:
“Dear Sir”
“Dear Madam”
“Dear Madam/Sir”
“Dear Sir/Madam”
“Dear Mr Smith”
“Dear Mr Jones”
also:
“Dear Caroline”
“Dear Alasdair”
The opening paragraph may refer to previous correspondence, acknowledgement of a telephone call
or request, or explain the purpose of the letter. Please avoid “I am writing to you” whenever possible.
They know you are writing to them; what they want to know is why.
Middle paragraphs will describe in sequence events or ideas relating to the opening paragraph. Keep
these paragraphs short and simple. Don’t worry about one-sentence paragraphs; often they have a
greater impact and illustrate the sequence better.
The closing paragraph is crucial. If you have avoided waffle prior to this stage, don’t introduce it
now! This is a summary of what has gone before – don’t introduce new ideas or proposals. An
effective way of eliciting future correspondence or a meeting is to use a closed question or sentence.
For example:
“I should like to meet you on Tuesday 2 January 19.. at 10.00 a.m. at your premises to
discuss these matters further.”
The recipient has to respond to fix an alternative meeting, to agree the meeting or to discuss why he or
she cannot attend or does not feel the meeting to be appropriate.
Letters of Recommendation
The purpose of a letter of recommendation is to persuade the reader or readers that the person
recommended has the background, skills and experience necessary for the position.
Such letters are usually confidential and sent out at the request of an organisation, but may be kept on
a personnel file for future reference if the person recommended is employed.
ends “Yours sincerely”.
may end, “With best wishes”.
ends “Yours faithfully”.
Written Communication 57
© Licensed to ABE
A letter of recommendation should include:
The full name of the candidate (and occasionally other names by which the candidate may be
known, e.g. maiden name, Anglicised name).
The job or benefit the candidate is seeking.
Whether the writer is answering a request or taking the initiative.
How long and in what context the writer has known the candidate; also the position of the
writer.
Facts or information relevant to the position or benefit sought.
The writer’s overall evaluation of the candidate’s suitability for the job or benefit sought.
As with all correspondence, the writer should avoid over-lengthy descriptions and stick to the key
facts. One full side (typed) of A4 or equivalent is usually sufficient for most correspondence of this
nature, unless there are particular circumstances which warrant more detail. If that is the case, a
telephone call may first be necessary to the organisation making the request.
Dealing with Complaints
(Note that we are considering the text, not layout, in these instances. Obviously these would be
produced on appropriate letterheads.)
(a) Letter
27 J une 20..
Dear Mr Green,
Re: telephone conversation Wednesday 24 June 19.. –
58 Written Communication
© Licensed to ABE
(b) Response
28 J une 20..
Dear Mrs Brown,
Thank you for your letter dated 27 J une 20..
Your wardrobe will, I’m happy to say, be delivered on Tuesday 7 J uly 20.. at
10.00 a.m.
Unfortunately there was a design fault and the manufacturers recalled all
existing wardrobes until this fault could be rectified.
I enclose a gift voucher for £30 for use in any of our stores.
Please don’t hesitate to contact me should you require more information.
Yours sincerely,
Mr W. Green
Letters of Application – Standard Format
A letter of application should:
(a) Be correctly addressed, dated, etc.
(b) Acknowledge the source of the advertisement.
(c) Make a formal application statement and refer to relevant enclosures (e.g. curriculum vitae,
application form).
(d) Link the advertised position with your own current position and aspirations.
If the letter is in place of an application form, and you have been sent a detailed job description,
answer the points in the job description in turn, showing how you are the appropriate candidate for
this position.
If it is a covering letter, outline your experience, qualifications and personal qualities which you feel
appropriate for the position.
Finally, indicate your availability for interview.
Internal Communications – Memoranda
(a) Formats
Memoranda do not require an inside address, salutation, such as “Dear Bill”, or a
complimentary close, such as “Yours sincerely”. The format using To, From, and Date is
standard but the order in which these items appear can vary. A reference (Ref) or subject
heading may not always be used. Although organisations often have pre-printed memoranda
stationery, you should remember to use the MEMORANDUM heading for any memo that you
draft for examination purposes.
Written Communication 59
© Licensed to ABE
Memoranda should not be long and should be written in a concise style. Ideally they should
relate to one topic only.
Here is an example of a memorandum sent to staff in one company located on two different
sites.
MILESTONE MARKETING
MEMORANDUM
To: All Staff
From: Chris Weber
Managing Director
Date: 19 May 199.
Subject: Fire Drill Procedure
Last week’s fire drill was not carried out successfully. In fact many staff
ignored it and carried on with their work.
The correct procedure must be adhered to and any member of staff who does
not comply with this instruction will be disciplined.
Not only is it a legal requirement that all organisations carry out regular fire
drills, but it is also an essential safety procedure organised to ensure the
safety of staff in the event of fire.
The next fire drill will take place on Monday 20 J une and on hearing the
continuous bell staff must:
(a) Stop work immediately.
(b) Close all windows and the last person leaving a work area should
close doors as they vacate the area.
(c) Leave the building quickly and calmly through the nearest fire exit.
(d) Not use the lifts.
(e) Congregate at the designated meeting points outside the building.
It is imperative that all employees follow these instructions and familiarise
themselves with the fire procedure notices in their section which identify fire
exits and meeting points.
Figure 3.2
60 Written Communication
© Licensed to ABE
(b) Purpose
Memos are ideal for interdepartmental correspondence where a formal response needs to be
noted and acted upon.
Usually they are requests for information required in a short time period, or may issue orders or
changes in procedures.
As a formal channel, it is perfectly acceptable to refer to memos, dated such and such,
regarding such and such a matter, in other forms of correspondence.
They must always include the date sent, name(s) of the recipient(s), the sender’s name, the
purpose of the memo and action required.
Briefs
A brief can be an internal or external communication, often depending on the size/function of the
organisation. Here are some examples:
Internal: External:
Brief to graphics department. Brief to external designer.
Task-based to employee. Brief to architect, builder, IT
consultant, management consultant.
External briefs may often spend some time describing corporate strategy and ideology, whereas
internal briefs will be more task-specific and less conceptual.
For example, an external designer will need to know something about the organisation and the
purpose and function of his or her designs. An internal graphic designer may well be asked to
produce a document/illustration for an internal department in a brief where corporate issues are not
discussed.
A brief should be a document which is carefully structured and purposeful, designed to meet clearly
specified objectives in a designated time-scale and at an agreed cost. Sometimes the cost is agreed on
a tendering basis, where several external agencies receive the brief and submit their responses and
costings. Advertising agencies are a good example of this.
One thing is certain – few briefs are brief! In 1994 British Airways commissioned a 40-page brief to
designers for the design for their new uniforms and corporate identity.
Unlike a report, a brief is designed to elicit, not give, information. It is still reliant on clear, careful,
concise language and will reflect a formal, not informal, style.
A sloppy brief will result in sloppy information or results.
D. REPORTS AND REPORTING
The Reporting System
Much internal business communication will be characterised by its reporting procedures as
determined by the channels within the organisation and the type of organisational structure used.
Every employee will have to report to someone whether it is:
A section head
A department head
Written Communication 61
© Licensed to ABE
A senior manager
A colleague
An auditor
There are also occasions requiring reporting such as:
Team briefings
Presentations
Meetings with shareholders, directors or the chief executive
The business report is the document used for the formal dissemination of specialist, researched
information. The commission and production of reports is crucial to the achievement of the objectives
which organisations set themselves.
Reports are likely to reflect issues which affect personnel, finance, production, marketing, managing
the business or external political or economic factors which could determine changes for running the
business effectively.
Not all reports arrive on your desk the size of the Yellow Pages and just as interesting. The success of
a report is reliant on the report writer being given a clear remit and brief for the context and content.
There has to be an agreed process for the dissemination and evaluation of the report once it has been
written. There must be an evaluatory mechanism for dealing with any recommendations which are
made.
Reports are not always written – sometimes brief oral reports or summaries of meetings are all that is
required as the reporting mechanism.
Classification of Reports
Reports can be classified in the following ways:
(a) Regular and Routine
These include:
Health and safety
Maintenance
Progress
Staff appraisal
Sales
Production targets
Financial
They are characterised by a standard format to allow comparison between the current and
previous reports, and standard procedures for implementation and evaluation.
Some of these reports will go to monthly meetings where recommendations or problem areas
(e.g. sales targets not being met) will be discussed.
62 Written Communication
© Licensed to ABE
.
(c) Specially Commissioned Reports
These could include:
Market research
Personnel
Investigatory
Policy changing
Market forecasting
Production
Investment in new equipment
IT strategy
Special interest
These especially commissioned reports will form the basis for company policy and will include
recommendations as to how best to implement company strategic development objectives.
We shall concentrate here on specially commissioned reports.
Business Report Formats
The usual format of a business report is as set out Figure 3.3 following.
For very lengthy reports, an executive summary may be circulated with the report, prior to the report
or as an alternative to the final report. It is often the basis for an oral presentation of the report and
allows for discussion as to its main features and recommendations rather than wading through every
page. The executive summary would contain an outline only of the following elements:
title, author and aims of the report;
methodology and findings;
main recommendations.
A short formal report is usually three-part and probably no longer than 20 pages. It will include:
Introduction – aims, objectives, background.
Findings – sources.
Conclusions and recommendations.
Written Communication 63
© Licensed to ABE
(Introduction)
1. Title.
2. Author (name, title, status as necessary).
3. Identity of the person who commissioned the report.
4. Date report presented.
(The date it is commissioned or the date it was actually completed will not be the
same as the published or presented date. A report “comes into being” on its
presentation as a live document. Prior to that date it is a draft or work in
progress.)
5. Acknowledgements.
6. Table of contents, pagination.
7. Status, e.g. confidential.
(Main Body of Report)
1. Background/history/introduction/terms of reference/aims and objectives.
2. Methodology/procedure.
3. Findings, statistical data, etc.
4. Conclusions.
5. Key summary.
6. Recommendations.
7. Footnotes (if appropriate).
8. Appendices (including copies of questionnaires, standard letters, etc.).
9. Index.
10. Bibliography.
11. Circulation list (this may also appear at the end of the Introduction section
depending on the status of the report).
Figure 3.3
Writing a Report
Report writing lends itself to a more formal, factual and objective style. It is an analysis of a situation
characterised by clear, purposeful research, a summary of the main findings and realistic
recommendations. Prejudice or emotional responses to the findings or research are inappropriate.
Many reports require some primary as well as secondary research. This must be carried out without
bias or prejudice, otherwise the findings of the research are irrelevant and inappropriate. One of the
ways in which objectivity is seen to be employed is by referring to the process, findings or
recommendations in the third person – hence, “I found out that” becomes “It became evident that”.
64 Written Communication
© Licensed to ABE
If the writer has received a proper brief as to the purpose, use and dissemination of the report, then it
is easier to use appropriate tone and style from its inception., if any, will be available from others within the organisation?
Will there be a requirement for progress reports or a draft report before presentation or
publication?
Will the author be required to present the report? When? To whom?
Reading a Report
Not only will you have to write business reports, but you will also be expected to read, understand and
respond to key issues in the reports that others write.
You will use reports as the basis for your market research on any issues which may concern your
organisation, such as government reports which indicate a shift in government funding or spending, or
support particular initiatives.
Sometimes you may be asked to present the key issues of a particular report and the impact that this
report will have on your organisation. At other times you may decide to read a report in its entirety as
a result of a summary of its findings in a newspaper or national news bulletin, or on receiving an
executive summary.
Sample Reports
Over the next three pages we set out some samples of short reports to illustrate the above points about
style and structure.
Written Communication 65
© Licensed to ABE
(a) Informal Report
REPORT ON NEGOTIATION SKILLS TRAINING COURSE
For the attention of: Ben Firth, Marketing Director
From: Hugh Heaton, Marketing Assistant
1. Introduction
This report provides information on the value and effectiveness of the recent
Negotiation Skills course which Hugh Heaton attended on 4 December 199..
2. Findings
2.1.
66 Written Communication
© Licensed to ABE
) Most staff have taken advantage of the flexi-time system during the
last three months.
(b) None of the staff using the system exceeded their limit of days owing.
Implications of the System
(a) The rules relating to the core time have meant that neither customers
nor the general flow of work has been disrupted in any way.
(b) Staff morale has improved due to the flexibility of the system. There
has been a significant decrease in absences amongst staff during the
period of the pilot scheme.
(c) The administration of the system has involved more work for Mrs
Graves in the administration section than was originally planned.
Written Communication 67
© Licensed to ABE
(c) Formal Report
REPORT ON INSURANCE SECTION’S TELEPHONE TECHNIQUE
For the attention of: Nicola Bingley
From: Sam Daniels
1.0 Terms of Reference
The quality circle team was requested to investigate the problems with the telephone
service in the insurance claims section.
2.0 Procedure
2.1 Telephone technique in the insurance claims section was observed.
2.2. Complaints from customers and members of staff were looked into.
2.3 Staff in the insurance claims section were interviewed.
3.0 Findings
3.1.
3.2 Staff often promised customers and staff in other sections that colleagues would
return their calls but they did not. Messages were not often taken and it was
noted that the section did not have a stock of telephone message pads.
3.3 J unior members of staff were reluctant to deal with incoming calls because they
did not feel capable of dealing with many of the complicated queries received.
4.0 Conclusions
It is evident that staff in the insurance claims section are not providing an adequate
telephone service. They are extremely busy and there is an obvious staff shortage.
Messages are often not relayed because message pads are unavailable. J unior staff
lack training to deal with the more complex queries. All staff need training in
telephone technique.
5.0 Recommendations
5.1 Additional staff should be employed in the insurance section.
5.2 All staff should be provided with a stock of telephone message pads.
5.3 J unior staff should undergo specialised training, provided by senior staff, on
some of the more complex incoming enquiries which the section receives.
5.4 All staff should attend a training course on telephone technique.
Signed on behalf of the quality circle team:
Dated:
68 Written Communication
© Licensed to ABE) what
(ii) who
(iii) where
(iv) when
(v) why
(vi) how
It should have a catchy title (puns are very popular in local papers).
It should be no longer than one side of A4.
It should be typed, double spacing where possible.
Written Communication 69
© Licensed to ABE
It must contain a contact name, address and telephone number. This should be at the bottom of
the sheet after the word “end”.
It is worthwhile including a relevant black and white photograph.
Give the press release a date.
Do not underline anything – key points should be obvious. The editorial team may choose to
italicise or subdivide the details.
Give an embargo date if necessary.
Include a relevant (positive) quote where possible.
Make sure you keep a record of all press releases you send out (they’re useful for other promotional
activities) and to whom you send them.
Placing a Press Release
Research which publications would be appropriate. Find out the names of the editors and features
staff. Introduce yourself to them even before you have any releases to place. If you are already
advertising in that publication, it may be possible to negotiate a small release at key times. For
example, a car sales company may advertise on the same page as a release about a new marque which
they are now stocking.
Familiarise yourself with the style and issues which concern the publication. Find out if they plan any
special editions or features which would benefit your organisation, were it to be represented in these
“specials”.
Always thank the publication for their assistance and seek their advice if appropriate.
Think of fresh ways of presenting your company. A press release is not a free advertisement; it is
usually part of a public relations exercise. It will reflect good news. Restaurants offer journalists the
opportunity to try their cuisine and then to write about it in their “Dining Out” section. Driving
instructors may choose to offer driving lessons to a journalist.
Remember that if you are using a local paper, then your press release has to be of local interest.
If you are placing a press release in a national publication, it is more likely to be product/service
specific and you will probably have targeted specialist publications or specialist sections of national
newspapers. This will include new advances in technology.
What you must keep in mind is that an advertisement will be in the style and in a publication
appropriate to your identified target market; a press release is targeting the publication (i.e. its
editorial staff) as well as your identified target market.
Sometimes, of course, a publication may choose not to publish your release.
70 Written Communication
© Licensed to ABE
Typical Press Release Layout
Company letterhead
Date
Headline
Who, why, what, when, where, how
Background details
Customer benefits
Contact details
Any enclosures, e.g. photo
Figure 3.4
Remember:
Never underline anything.
Avoid exclamation marks.
Do not start a sentence with a number.
Check spelling and grammar.
An Article from a Press Release
The following article (Figure 3.5) illustrates how a press release may become an article in a
newspaper. The information that has been left out is how to get nomination forms. Remember that
your press release is unlikely to be reproduced in its entirety, so make sure that you include all the
relevant facts.
Written Communication 71
© Licensed to ABE
Figure 3.5
(Source: Belfast Telegraph, 20 September 1994)
Example
The following example illustrates the points above. It shows a (fictitious) press release to be sent to
several local magazines and newspapers by the marketing assistant at the local leisure centre which is
keen to find ways of extending the membership and increasing the number of users. It follows several
improvements to the facilities – new showers, extra steam rooms, and the refurbishment of the bar by
the Boddway Brewery.
72 Written Communication
© Licensed to ABE
WESTOVER LEISURE CENTRE
Press Release
Date: 12 J une 200X
Westover Leisure Centre’s New Look
Following a massive refurbishment programme our local leisure centre has
made drastic improvements to its facilities.
The showers have been replaced with a more powerful version so that a
strong spray of water is guaranteed. Temperature control is much better and
new cubicle doors give more privacy.
Two additional steam rooms have been built to cater for the massive demand
for this facility. The cold weather, in particular, seems to encourage more
people to want to have a hot, relaxing steam bath.
The Centre’s manager, Steven Lee said: “Many of our customers are using
the centre more as a social outlet and although they are keen to use the sports
facilities, many like to socialise in the bar. That’s why, in addition to
improving some of the facilities, we have negotiated with the Boddway
Brewery for a total refurbishment.”
The new look bar includes new seating and non-smoking areas. The walls
no longer have a white clinical look and the lighting consists of a series of
wall and concealed ceiling lights.
“The whole atmosphere is more congenial and welcoming. We expect to
have lots of bar promotions as well,” said Mr Lee. “Most people try us out
once as guests and then become members because they get hooked on the
whole experience.”
Guests wishing to use the facilities can do so by paying a £3.00 entrance fee.
Those intending to join as members should take advantage of the old rates
before increases in September.
END
For further details please contact Ravi Manju, Marketing Assistant, at
Westover Leisure Centre, Westover Road, Assington 01234 594666.
Written Communication 73
© Licensed to ABE
G. WRITING AN EFFECTIVE MAILSHOT
Marketing letters or circulars are generally sent to a large audience and may or may not be
personalised.
They are often used to send out information about products or services with the aim of persuading the
reader to send off for more information or to order products/services. Sometimes they are sent in
response to a request or they are unsolicited mail.
Generally this type of letter has to be written in a persuasive style and must convey an air of
congeniality to overcome the impersonality of mass communication. This is achieved by the use of
friendly, cheerful language. Rhetorical questions are used and the audience is often offered an
incentive to reply by a certain date.
Very importantly, the letter or some component of the mailshot should contain a response mechanism,
i.e. an easy to complete coupon, freepost address or reply paid envelope.
Information technology means that circular letters can be personalised, based on the information held
on databases.
Example
The following is a (fictitious) circular to customers of a branch of the Midshire Bank plc informing
them that a market research survey is to take place over the next few weeks. The bank has appointed
TMI Limited to conduct telephone interviews with a random sample of customers. The letter seeks to
persuade customers to cooperate by giving their views, but also explains that not all customers will be
chosen to be part of the sample and reassures them that their responses will be completely
confidential.
74 Written Communication
© Licensed to ABE
MIDSHIRE BANK PLC
High Street
Assington
Berkshire
AS1 6EL
Mr A Customer
17 Goldthorpe Way
Didsbury
Berkshire
DKS1 3FF
12 J une 200X
Dear Mr Customer
At Midshire Bank we try to provide banking facilities of the highest quality
in order to meet our customers’ needs. To do this we need to listen to what
our customers say.
To help us do this, we have asked TMI Limited, an independent research
company, to interview a number of our customers. TMI will be conducting
their interviews by telephone over the next few weeks.
I would be very grateful, if you are contacted by TMI, if you could assist
them in their research. We would certainly like to hear your views and
opinions on our services.
May I take this opportunity to assure you that TMI is a reputable company
and your individual responses will be completely confidential, according to
the Market Research Society’s Code of Conduct.
Yours sincerely
Milly Brown
Manager
75
© Licensed to ABE
Study Unit 4
Oral Communication
Contents Page
Introduction 76
A. Organising a Presentation 76
Organisation and Planning 76
Types and Styles of Presentations 79
The Context of the Presentation 80
Internal Communications Processes 80
The Planning Process 81
Target Audience 83
Presenter’s Briefs 84
B. Presentational Skills 84
Key Presentational Elements 85
Types of Presentation 85
The 6 Ps of Presentations 88
Knowing Your Audience 90
Subject Knowledge 91
Structuring Your Material 92
Making and Using Notes 93
Practice 93
Structuring the Presentation 94
Tone and Style 94
Non-verbal Communication 95
Participation 95
C. Using the Telephone 97
Purpose of Telephone Calls 97
Successful Calls 99
Telephone Technique 100
Using Answerphones to Your Advantage 100
Message Taking 101
76 Oral Communication
© Licensed to ABE
INTRODUCTION
In this unit on oral communication we shall be concentrating on the art of ensuring an effective
presentation. We shall be drawing on some of the basic principles discussed in Unit 2, and you should
note the links to the unit on visual communication which follows – particularly the use of audio-visual
aids and on the presentation of statistical information.
Presentations may be five minutes or two hours long, but the basic precepts will be the same – the
conveying of a specific message to an identified audience at a designated time and place. Similarly,
the purpose and content of each and every presentation which you may make will vary tremendously,
but the skills needed to ensure that they are all effective will be the same.
We start by examining the organisation of presentations and considering the fundamental importance
of proper preparation. We then go on to the presentation itself, looking at the elements which
contribute to its effectiveness and the particular skills that are needed.
The unit concludes with a review of another important area of oral communication, that of using the
telephone. Telephone conversations are a unique form of such communication in that they lack many
of the non-verbal cues which are so important to the communication process, and we shall consider
the particular demands of such interactions and how to make them effective.
A. ORGANISING A PRESENTATION
We shall, in this first section of the unit, assume your role is as the organiser, co-ordinator, facilitator
or convenor of a presentation. Thus, a deliberate distinction is drawn between the roles of organiser
and presenter, because you need to be aware of the different communication skills applied in each
context. Although sometimes organisers of presentations may also be requested to be active
participants in the presentation itself, the majority of presentations are more effective if this does not
occur. A presenter does not or should not need to worry about the arrangements surrounding a
presentation, and an organiser does not or should not need to worry about making an effective
presentation.
The organiser is the only person who can have an effective overview of the success of the proceedings
and implement minor adjustments as necessary. Similarly, the organiser is the best person to evaluate
the presentation untrammelled by concerns as to his or her performance.
Organisation and Planning
Whatever the context or proposed content of your presentation, it will require careful planning. All of
the following elements will form part of the planning process – some will run sequentially, others
concurrently, so you may well be arranging speakers at the same time as booking the venue.
(a) Preliminary considerations
What is your status as an organiser (e.g. total control, reporting to superiors, reporting to
presentation team)? What sort of organisation are you working for?
What type of presentation are you organising? Is it fee-paying, paid for, part of an
existing public relations calendar, a meeting, a conference, a seminar?
By whom and how will the objectives be set? What are they? Who determines the
budget? Who reports to whom?
Oral Communication 77
© Licensed to ABE
(b) Work before the event
Attend all necessary team briefings and meetings.
Make up a file summarising all the activities you will need to organise, who your
contacts are, time-scale, deadlines and budgeting.
Check that you understand the requirements of your audience. Who are they? Where are
they?
Location:
(i) Book the venue according to the requirements and budget.
(ii) Confirm the arrangements.
(iii) Check whether there are any potential sponsorship/advertising opportunities.
(iv) Check the travel arrangements.
Arrange speakers.
Invite the audience.
Special arrangements for the day itself:
(i) Floral displays.
(ii) Audio-visual aids.
(iii) Music.
(iv) Lighting.
(v) Sponsorship.
(vi) Food and refreshments.
(vii) Media coverage.
(viii) Press release.
(ix) Advertise event in relevant medium/media.
(x) Access and cloakroom facilities.
(xi) Arrange supporting material/presentation packs.
(xii) Arrange signs, name badges.
(xiii) Caretaking.
Discuss potential follow-up activities at team briefings and make arrangements.
(b) At the presentation
Meet/greet the speakers and audience.
Double-check all previous arrangements.
Keep a time check on the speakers.
Liaise with catering staff.
Remain a point of contact for all speakers and audience members to deal with any
eventuality.
Distribute supporting material/presentation packs.
78 Oral Communication
© Licensed to ABE
Arrange photocopying facilities for speakers’ material in case copies are required.
(c) Work after the event
Ensure all parties have been paid, invoices received, etc.
Circulate any necessary follow-up documentation to participants (this may include
evaluation questionnaires). Thank speakers and participants for attending, etc.
Present the final budget sheet.
Attend post-presentation briefing and report back to teams as necessary.
Throughout the planning process and then, subsequently, keep the internal market aware
of the purpose of the event, its success and the future implications (if any) for the
organisation.
It is important to be aware of a number of general principles about presentations as these affect the
approach to their organisation. For example, you can safely assume that you have interesting/relevant
information which needs to be communicated to others, and that the communication will be part of a
formal process (internally or externally).
However, there are a number of important points about presentations which you cannot assume and
which must, therefore, be specifically addressed in the organisation and planning leading up to the
event.
All presentations are of a standard length.
All presentations are directed at an audience of five people.
All presentations take place externally.
All presentations require sophisticated audio and visual aids.
All presentations are successful.
All presenters are equally prepared/skilled at presenting.
Your materials speaks for itself.
Your personality, choice of language and style have no bearing on the effectiveness of your
presentation.
The audience is eagerly awaiting your every word.
You have an unlimited budget.
All presentations take place in exclusive hotel conference suites.
You are, or you superior is, the best person to make the presentation.
You have the support of your internal market.
Advertisers and sponsors will be falling over themselves to participate.
Finally, we can note a number of points about which you can be certain and which, again, you will
need to address in the organisation and planning.
Presentations make use of a wide variety of communication skills.
No two presentations will be the same.
Individual style has a tremendous influence on the reception of a presentation.
Organising presentations is extremely hard work!
Oral Communication 79
© Licensed to ABE
Types and Styles of Presentations
(a) Internal Presentations
Within an organisation presentations are used to:
Brief relevant teams, groups, committees.
Inform such teams, groups or committees.
Raise issues for discussion.
Illustrate strategic developments (for example, presenting your section’s five-year plan or
sales figures).
These presentations may involve as few as two staff or the entire workforce. “Making a
presentation” is a formal communication process with objectives usually set by senior
management.
Any promotional activity surrounding a presentation – perhaps a meeting to discuss company
employment policy – will make use of existing internal communications channels.
Many organisations insist that middle or senior managers hold a progress report meeting on
Monday mornings. This is another form of presentation. The managers are relaying key
information to directors or executives.
What is certainly true of all presentations, be they internal or external, is that the presenter can
be selective above the information which he or she presents.
The key skills are to know how to summarise relevant data effectively, to understand the
requirements of the audience and be prepared for any “sticky” questions.
(b) External Presentations
Because these involve people from outside your organisation, they are sometimes viewed more
seriously. Shareholders’ meetings, press conferences, after-dinner speeches, formal
introductions, trade exhibitions and advertising pitches are all types of external presentation.
Such presentations are more likely to:
Take place in a neutral location (e.g. a hotel, conference suite, etc.).
Involve some advertising or promotional activity using external media.
Involve more than one presenter.
Form part of a public relations budget.
Be acknowledged as formal marketing activities, i.e. be worthwhile and high status.
Need careful co-ordination and attention to detail.
Require sophisticated interpersonal skills on the part of organiser(s) and presenter(s)
alike.
The style of an external presentation will be determined by the corporate image of the
presenting company, and the perceived requirements of the audience, whereas the style of an
internal presentation will be characterised by the role and status of individuals making the
presentation and their own personal style.
Furthermore, participants making up the audience for an external presentation such as a seminar
or conference may have paid for the privilege of so doing. It would be extremely unlikely for
the audience at an internal presentation to have been charged admittance!
80 Oral Communication
© Licensed to ABE
The Context of the Presentation
Presentations are a facet of organisational activity. Thus, whether they are internal or external,
corporate strategy or objectives will have determined the context, background or rationale for the
presentation. Furthermore, the organisational culture will have a strong impact on who is selected to
make presentations and to whom – for example, a matrix organisation is more likely to encourage
presentations across departments or by junior staff than a hierarchical/bureaucratic organisation.
If you are the organiser of the presentation, you need to be familiar with this organisational context
and to consider the following questions:
What is the purpose of the presentation?
Will I have total control as to the style, format and context?
Who will I have to report to? When? With what information (e.g. progress, financial,
promotional activity, etc.)?
Who will I be working with? Internally? Externally?
Do I need to set up a presentation team?
Is there a budget? How has it been set?
Are there any restrictions on hiring specialist presenters?
How does this activity fit in with other organisational activities (for example,, extra people, teams, authority)?
What is the time-scale for the event?
How will the presentation be assessed?
Internal Communications Processes
When organising any presentation, you need to know who are the key internal members of staff with
whom you will be working – for example:
the senior management team
the chief executive
caretaking and cleaning staff
administrative staff
maintenance staff
department heads
presentation team drawn from throughout the organisation
Oral Communication 81
© Licensed to ABE
Having identified these people, you will have to make effective use of the existing internal
communications system. It is not always practical to arrange meetings with all concerned. For
example, caretaking staff could be involved in the setting up and cleaning up for ten presentations in
one organisation. If they attended meetings with all presentation teams, they would probably never do
anything else!
Interpersonal communications will be critical to the success of your venture. However, if you rely on
everyone’s word after a brief chat as to your requirements, you may well discover that:
they’ve misunderstood your requirements;
you haven’t stipulated the date, time, location or purpose;
you were discussing a hypothetical presentation and not a real one.
It is essential, therefore, that your requirements are clarified or determined in writing. Presentations
are a formal communications process and use formal communications channels. You must be
prepared to use briefs or short reports as to how you are to set up the presentation, internal memos for
co-ordination and properly drawn up planning and costing sheets to monitor and control the
organisation and budget.
The Planning Process
Your plans for the presentation will be determined by the budget and time-scale. Within those
constraints you need to identify and plan all those activities which you will need to organise,
including key personnel and administrative procedures.
It would be sensible to set up a file with the following sections as headings and to include all internal
and external correspondence/relevant data:
Title, date and timing of presentation
Location
Speakers
Catering arrangements
Invoices
Advertising and promotional activities
Special arrangements
You will also need a chart showing planned activities on particular dates – for example, date of
presentation, team briefings, meeting with hotel managers, guest speakers, etc. (See Figure 4.1).
82 Oral Communication
© Licensed to ABE
F
i
g
u
r
e
4
.
1
:
I
n
i
t
i
a
l
p
e
r
s
o
n
a
l
p
l
a
n
n
e
r
Oral Communication 83
© Licensed to ABE
The time-scale will be dependent on the range of activities and research necessary, and this may be a
function of the complexity of the planned event. For example, you may need to:
Choose a location.
Select catering facilities.
Interview speakers and brief them.
Write press releases/programmes, etc.
Liaise with the local press/media.
Target a particular audience and make up your own database of potential participants.
Check corporate requirements on promotional activities/colour schemes, etc.
Arrange printing.
This will involve a lot of meetings, telephone calls and faxes – all of which must be recorded and
filed. Whilst much of this can be held on computer, a physical file has the advantage of containing all
the documentary evidence – expense claims, invoices, internal memos, invitation letters, etc.
Target Audience
Very early in the planning process you need to know who are the intended audience for the
presentation. You then need to anticipate the needs of the audience and structure the presentation
accordingly.
Perhaps more importantly, you need to inform your audience of the presentation and request their
attendance. In may cases, you will know who the audience is and there may well be an expectation on
their part of attending. Thus, internally, it may be that the audience has requested the presentation or
that everyone recognises the need to attend. Similarly, externally, the audience may request a
presentation – you may be a manufacturer supplying a retail outlet which wants to know more about
your range for the next season. The presentation could be an Annual General Meeting where
shareholders (the audience) have particular concerns about your organisation and require very specific
information about corporate issues.
However, the audience may well be an externally invited audience, specific to the particular subject
matter of the presentation – a product launch, a recruitment drive, a public relations press conference
after an industrial accident (essentially a damage limitation exercise), etc. If this is the case, then you
need to:
(a) Identify your target audience.
(b) Locate your target audience.
(c) Choose the most appropriate channel of communication to inform/invite them.
You need to be aware of any special requirements your potential audience may have, such as:
Dietary requirements.
Access to meeting/presentation rooms/location.
Market-sensitive costing structure.
Necessary length of the presentation.
Timing of the presentation (cereal and grain farmers are, for example, much more likely to
attend conferences between November and February after harvest and before replanting).
Crêche facilities.
84 Oral Communication
© Licensed to ABE
Medical facilities.
Adherence to health and safety legislation.
Translators.
Presenter’s Briefs
As an organiser, it is your role to ensure that the presenters themselves are properly briefed and can,
therefore, communicate effectively and achieve the objectives of the event. Getting the most out of
your presenters is obviously best achieved by having clear objectives as to the purpose of the
presentation and an understanding of the audience requirements. However, some can choose their
presenters, others have presenters thrust upon them,, venue and timing
Communication skills required
Technical or specialist knowledge required
Any special requirements – particularly as to company policy on certain issues (for example, in
respect of gender and racial inclusivity), notification of audio-visual aids needed, etc.
B. PRESENTATIONAL SKILLS
Presenting information, proposals or ideas to someone else should be easy. After all, you just need to
talk to them, reach agreement and take appropriate action. If only it were that simple! As you have
seen from previous study units, there are many barriers to effective communication and the most
important one is ourselves. Too often we assume that because we understand the
importance/relevance of our plans or proposals, then so does everyone else. We forget to introduce
the stages or processes of our thinking, which would illustrate how we reached the conclusions we are
presenting. We get bogged down in a mass of detail which disguises the simplicity of an idea.
Sometimes we are overawed by our audience, or lack commitment in our ideas or judgement.
In order to present ourselves and our information effectively, we need to show evidence of what might
be termed the 6 Ps of presentation:
Planning
Purpose
Political sensitivity
Personal commitment
Personal communication skills (ability to persuade)
Polish
Oral Communication 85
© Licensed to ABE
We shall examine these in detail later, but first we shall look at some of the key elements of making a
presentation and the different demands of different types of presentation.
Key Presentational Elements
The main elements which make up an effective presentation may be summarised as in the list below.
You should consider this as a checklist to be directly and carefully addressed when planning the
delivery of any presentation.
Understanding the difference between written and spoken communications
Oral communication skills (style, delivery, rapport)
Using non-verbal techniques
Understanding your audience’s requirements
The ability to interact with an audience
Preparation and planning
Knowing your subject
Presenting enough, but not too much, information/data
Careful selection of information/data
Summarising salient points
Using appropriate visual aids
Timing
Reflecting corporate objectives accurately
Working in a team with other presenters, presentation organisers and/or senior management
We shall be concerned, in the following parts of this section, with illustrating these skills and how you
can make your presentations more effective by paying particular attention to them.
Types of Presentation
Not only does the size of the audience, the subject matter, time-scale or location vary from
presentation to presentation, but also the purpose – which determines those factors – will vary
enormously.. Thus we could identify the following types:
to prospective employers at a job interview
to senior managers
86 Oral Communication
© Licensed to ABE
to colleagues
to potential clients – planned “pitches”, etc.
to actual and/or potential clients – product launches, etc.
at exhibition stands/trade fairs
at in-house training/staff development activities
at company conferences/as an invited speaker
This form of classification provides a useful means of starting to analysis the impact of the context on
the form of presentation. In each of these instances, the context will determine how you approach the
planning, design and execution of your presentation. Thus, it will not always be appropriate to use
audio-visual aids, and sometimes you will be alone, whereas at other times you will be part of a team
of presenters. Note, too, that your status will vary in the different situations and this will affect how
each audience perceives you, your organisation and the validity of your arguments/presentation. The
degree of predictability of how the presentation will go may also vary with the context – for example,
if you are presenting specific information, as at an interview or trade fair, you will have to be prepared
for non-scripted or apparently unrelated questions/requirements from your audience.
Figure 4.2 illustrates some of the considerations involved in this range of presentation types.
Oral Communication 87
© Licensed to ABE
F
i
g
u
r
e
4
.
2
:
R
e
q
u
i
r
e
m
e
n
t
s
o
f
d
i
f
f
e
r
e
n
t
t
y
p
e
s
o
f
p
r
e
s
e
n
t
a
t
i
o
n
88 Oral Communication
© Licensed to ABE
The 6 Ps of Presentations
(a) Planning
Being well prepared for a presentation affects how the audience perceives you and your
organisation, and how confident you feel about your presentation. It will result in your using
any technical equipment more effectively and in your being able to react quickly and accurately
to any questions posed by the audience. Presenters who apparently “think on their feet” and
engage in an almost social interaction with their audience, usually do so as a result of very
careful and detailed planning.
So, what are the elements of a presentation which you are giving that require planning?
Background
You will need to know the location, the timing, the running order, and the position from
which you will be presenting (e.g. on a stage, in a meeting room, etc.). What technical
equipment will be available to you? Who will be co-ordinating the presentation should
you require additional assistance? Who are the other presenters? What are their
subjects? Who are their audience? Why and how have they been selected? What is your
role, status and what is expected of you in this context?
Personal Preparation
Is it necessary to adopt a particular dress code?
Are you physically prepared with relevant data as well as spare pens, etc.?, allow questions.)
Do you understand what you are presenting?
Have you considered all the potential implications or perceptions that there may be to
your material? This will ensure that you can respond to any criticism or query
adequately as opposed to defensively.
Are any visual aids produced easily visible, relevant and properly produced?
Check who will be available to offer technical support if necessary.
The planning should allow you to take control of your presentation. In fact, you can even set
the scene by preparing information about yourself and your presentation, with which the co-
ordinator can introduce you.
Oral Communication 89
© Licensed to ABE
(b) Purpose
The first element of the planning stage is concerned with identifying the purpose of the
presentation being given and your role in fulfilling that purpose.
Clearly the purpose varies from presentation to presentation, but some presentations are for the
benefit of internal audiences, and others for external audiences. In every case they are a
medium for corporate strategy, objectives or ideas to be revealed, discussed and communicated
(see Figure 4.3).
Type of Presentation Purpose
Product launch Communicate to external market; generate sales.
J ob interview Illustrate empathy and understanding of
corporate objectives.
Exhibition stand Raise awareness; communicate to external
market; generate sales.
To senior managers Generate support for an idea/proposal; test
market an idea; establish presenter as the expert.
To colleagues Share ideas/proposals; establish team hierarchy.
“Pitch” to potential
clients
Communicate corporate ethos and attitudes to
external market with the objective of making
future sales.
Figure 4.3
(c) Political Sensitivity
Why political sensitivity? Quite simply, presenters need to be aware of the potential impact and
ramifications of the content of their presentations. Some issues are of political sensitivity in
the largest sense (e.g. nuclear waste, closing hospitals or schools). In other instances there
could be internal politics which need to be considered (e.g. reallocating workloads from one
department to another). There include:
Political presentations which represent local or national politics (e.g. party conferences,
union meetings, local government meetings).
Presentations which are politically sensitive and need to take account of legislation or
political change in the external sense (e.g. new processes for food production, chemical
emissions, education).
Presentations which in their planning and execution need to reflect sensitivity to internal
political issues.
(d) Personal Commitment
If a presenter has no interest in the planning, writing or presenting of the material then the
presentation will be a disaster.
However, too great a commitment to the subject matter may result in an inability to see the
potential pitfalls or problems, and cause the presentation to be seen as overzealous and of the
preaching type.
90 Oral Communication
© Licensed to ABE
Too great a personal involvement in the presentation and your role can result in an excess of
nerves and overplanning which destroys the impact of the presentation.
Your commitment should be to extensive and relevant preparation, professional delivery and
your own sanity!
(e) Personal Communication Skills
It is extremely important to be able to establish a rapport with your audience and fellow
presenters. Obviously you can’t retain eye contact with a hundred people, but you can make
sure that your physical appearance, body language and style of presentation contribute to, rather
than detract from, what you are trying to communicate.
The following tips may come in useful:
Wear clothes which are smart (and clean) in which you feel comfortable. Avoid being
fussily dressed or too formal.
Try to control your nerves and the general nervous “tics” which we all have – fiddling
with pens, scratching, etc.
Use the space you have available to you; move around it so that the audience have to
follow you and stay attentive.
Look directly at your audience, not at your notes, the floor or the ceiling. This is actually
easier with a large audience. As before, if you are not comfortable looking people in the
eye, look at the space between their eyebrows. This gives the appearance that you are
looking directly at them.
(f) Polish
This is the most difficult element to achieve; it rarely comes naturally and is usually a result of
practice, rehearsal and experience. A truly polished presenter can attain professionalism with
friendliness. Don’t mistake being polished for being slick or over-rehearsed. (“It sounds like
he’s said this a million times before.”)
Even if you have to give the same information to a variety of audiences, vary your presentation.
Remember to present the identified benefits to each particular audience. Avoid clumsy
phrasing, jargon or rambling.
It’s worth looking at news bulletins to see how professional presenters use their material and
respond to the unexpected. Live morning shows are an even greater test of presenters and
reflect polish to varying degrees.
Knowing Your Audience
As indicated above, you also need to consider your audience carefully. As with all methods of
communication, you need to start from the point at which the audience is “at”. You will find it helpful
to ask yourself the following questions:
Who will make up the audience? Are you addressing a group of directors or senior managers,
or a group of work colleagues?
How big will the audience be?
What is the level of their existing knowledge and awareness of the subject?
At what level can you pitch the complexity of your presentation?
Oral Communication 91
© Licensed to ABE
What is the likely reaction to the presentation? Is it likely that there will be anxiety or
resistance to the subject matter, and can you get any ideas about the reasons for this?
What are their own objectives for the session likely to be?
Whilst the needs of the audience should not be allowed to dictate your overall aims, they will almost
certainly influence the specific objectives and the way in which the presentation will be delivered.
So how do you set about finding out this information?
Much of it can be obtained from careful consideration of the attendance list which is usually produced
for a formal event, such as a training programme. This will certainly give an indication of the size of
the audience and probably information about their background and experience. There may also be
information about the audience’s individual objectives in attending.
You should also consider past events of a similar nature. For example, finding out about a particular
committee or how the last such presentation went.
Finally, we can reiterate the maxim of putting yourself in the audience’s shoes. Once you have some
sort of profile of the possible audience, think about it from their point of view. What will they be
looking for and what will grab their attention?
Subject Knowledge
In oral communication generally, it is essential to “know your stuff ” – you can’t look it up as you go
along. It all has to be at your fingertips – or more precisely, perhaps, on the tip of your tongue.
This means that you have to thoroughly research the topic and gather as much information as possible
about it. Whilst you obviously need to focus on that which is directly relevant to your objectives, it is
good to get as wide a perspective about the subject as possible. This will help you to deal with
additional issues or alternative approaches which your audience might raise in questions. Make sure,
too, that your information is up-to-date.
To a large extent, this is the same as any information gathering exercise. However, there are certain
aspects which are of particular relevance to presentations, as opposed to other forms of
communication.
Exemplification
It is always helpful to illustrate the points you make by providing examples, but during
presentations, examples provide a welcome opportunity to add life and colour to what may be a
dull subject. Any exemplification needs to be carefully researched and developed to ensure it is
accurate, relevant and supportive of your main themes.
Depending on the type of presentation, the examples may need to be more or less detailed. In
some instances – such as an introduction to a new accounting system – you would need to
provide detailed, worked-through practical examples. If there are not appropriate real examples
to draw upon, it may be necessary to develop your own simulations. In other situations,
perhaps during a speech about company recycling policy and practice to a local school, you
would want to include some general facts and figures.
Anecdotes – short stories –about real incidents are also particularly helpful in illustrating
practical implications or applications. Putting a humorous slant on these can be very effective
in adding life and colour to the presentation.
Depending on the type of presentation, it may also be appropriate to involve the audience in
some way by getting them to contribute information or examples from their own experience.
92 Oral Communication
© Licensed to ABE
You need to be very clear about the type of information you want them to contribute and how
you will use it. (We shall return to the issue of getting audience input and participation below.)
Exercises
If the presentation you are involved in deals with skills development, it is likely that you will
want to include some practical work – in the way of exercises – for the participants in the
session. For example, this would be the case with the introduction to a new accounting system,
where it would be important to give the audience some practical experience in trying out the
procedures being introduced.
Any such exercises that are used need to be carefully worked out in advance. They should be
relatively simple so that participants can understand what is involved straightaway, and you, as
the presenter, can easily explain what is required. They must also be absolutely correct and
capable of being completed in the time available.
Structuring Your Material
If you have done your research thoroughly, you will undoubtedly have far too much material to
include in the presentation itself. You need, then, to organise that material:
determining what should be used, such that you are able to cover all the objectives in the time
available; and
structuring the session and the material so that the audience may be effectively led through it in
a way which enables them to meet the stated objectives.
One approach to organising a mass of material is to consider it under three categories:
This concentrates attention on those key elements which must be included – those that are central to
meeting the objectives and will, therefore, form the core of the presentation. Anything else is
supplementary to the main points. This may be divided into those elements which should or could be
included:
material that should be included is that which is supportive of your main points – important
material, but not essential and could be omitted without detracting from the exposition, if there
is not sufficient time;
material that could be included is that which extends your central material into further areas,
not central to the main theme of the presentation. If there were unlimited time, it would be
must include
should include
could include
Oral Communication 93
© Licensed to ABE
good to include and it would add to the sum of information relevant to the objectives.
However, the objectives can be met without it.
The point of this exercise is to focus on the core. It is this core – not the supplementary material –
which needs to be organised to give the structure to the presentation, and this is far easier when you
have stripped the content down to the essentials. It is important not to let detail get in the way of the
overall structure.
It is better to have a well-rounded argument based around the core points of a presentation than to try
to include too much of the supporting detail.
Structuring, then, is the process of determining the main headings and sub-headings within the core.
Do not have too many main headings or the overall focus of the presentation will become dissipated –
but at the same time, do not have so few that each area is too large to have a clear focus of its own.
In doing this, you need to think carefully about the order in which you wish to present your points.
The aim is to develop the presentation in a logical fashion, starting from the basics and developing
complexity as you work through it. This ensures a coherent progression to the whole, and helps to
make your arguments persuasive. Your starting point is always where your audience is now (or at
least where you assume them to be) and you can work from there, carrying them with you step-by-
step through the various elements you need to cover.
Structuring the presentation to work, step-by-step, through your subject, also helps to divide the
session into a number of “chunks” and provides natural break points. These allow both you and your
audience periodically to take stock of progress through the subject, and make it easier for you to keep
track of where you are.
Making and Using Notes
Very few speakers are able to remember everything they need to say at the time. You will need,
therefore, to have some notes to help you remember all your points and to guide you through them in
the correct order during the presentation. When we say “notes”, we mean notes – you do not need to
produce a full script for the presentation. There may be a temptation to write it all out verbatim, but
this will only encourage you to read the words out to your audience, rather than speak to them.
It is best to use cue cards, rather than sheaves of paper. These are small cards which simply state the
key points to be covered – main and sub-headings, with a number of subsidiary points underneath.
Cards have the advantage of being small and easily handled, they do not rustle if you are nervous and
can be easily bound together to keep them in order.
The words on the cue cards need to written clearly and boldly so that they can be easily read while
you are standing up and speaking. The cards should be numbered to keep them in order and to help
you know where you are during the presentation. They can also be usefully annotated to show where
you will use any visual aids. Colour coding can be used to clearly identify different elements or to
separate topics.
Practice
This is the final part of your preparation, but should never be omitted. There is no substitute for
rehearsal – it is essential if you are to be in control of your content and confident about the timing,
pace, fluency, etc. of its delivery.
Try to make this rehearsal as “real” as possible. Use your cue cards and incorporate the visual aids,
just as if you were doing the presentation for real. If at all possible, carry out your trial in front of a
“tame” audience, but even talking out loud to yourself will be of help. It is very likely that you will
94 Oral Communication
© Licensed to ABE
want to make some minor changes once you have tried things out, so adjust the order or amend your
cue cards as you go along. You can also check out exactly how fluently the use of your visual aids fits
into the presentation, and make changes if necessary.
Structuring the Presentation
We discussed above the need to organise and structure your material into a coherent and manageable
order. You also need to bear in mind the essential structure of the presentation itself.
J ust as with any form of communication, a presentation should have three clearly identifiable parts – a
beginning, a middle and an end. In terms of a formal presentation, these serve particular purposes.
Beginning
The purpose of any introduction is to tell your audience about what you are going to cover. It is
no different in a formal presentation. Outline what you are going to say and, importantly, how
you are going to present it. Tell them how you intend to handle questions (see below) and what
use will be made of visual aids – especially the availability of handouts and the introduction of
any videos. The more your audience know what to expect, the better they will be able to follow
your presentation and relate to the subject matter.
You also need to introduce yourself (and sometimes, where the audience is a small group, to get
them to introduce themselves).
However, there is an important additional purpose served by the introduction to a formal
presentation. This is to gain your audience’s attention and establish a rapport which will carry
you through the rest of what you have to say. You set the tone of the session by what you say in
the first few minutes, so the keynote has to be interest. This is generated by what you say and
how you say it – so, make it light, introduce some humour if possible (for example, by using
amusing anecdotes), and be positive.
Middle
This is the main body of the presentation, where you get down to the meat of what you want to
say and work through all your material. As we noted above, it should take your audience
through the topic(s) in a logical order, linking together similar aspects of subject matter and
providing appropriate exemplification. It is useful to include brief summaries from time to time
to allow you and your audience to take stock and ensure that you are carrying them with you as
you develop your themes.
End
The conclusion of the presentation must be equally as positive as the introduction. The final
impression you make on the audience is often the one which they will carry away with them, so
make sure it is not weak.
You need to summarise what you have covered in a succinct and interesting way. Again, this
can be helped if you can introduce a touch of humour. If you shared the session’s objectives
with the audience as part of the introduction, you can return to them as the basis for the
summary. You should also close with a distinct final statement, so that the audience is aware
that you have definitely finished. This helps to prevent any tailing off and ensures that the
ending is positive.
Tone and Style
Most forms of presentation are not about delivering a formal, impersonal speech to an audience. They
are, essentially, an interaction between you as the presenter and the audience. There may, or may not,
Oral Communication 95
© Licensed to ABE
be a degree of active participation (see below) by the audience, but try to think of it as a conversation,
albeit with a (possibly) large group of people and essentially one-way. Talk to them, rather than
lecture at them.
It is important to think about your audience in establishing the tone and style of speech that is
appropriate. The key elements are the size of the audience, the degree of formality required for the
occasion, and the size, layout and acoustics of the room. You need to speak clearly and avoid rushing
things. If you have planned it correctly, you should have time to make all your points without
steaming through it so fast that the audience has difficulty following either the arguments or the
speech itself. Often, nerves will tend to make you speak faster than normal, so be quite deliberate in
adjusting to an appropriate pace. The larger the audience, the more difficult it will be for those
furthest away from you to hear, so speak with these people in mind.
If you are using visual aids, allow your audience time to assimilate them. Don’t introduce key points
whilst they are studying one of your highly attractive OHP transparencies. Talk them through
anything that you show them, as well as using it as a reference point to develop further your argument.
Non-verbal Communication
Body language is very important in delivering presentations, as this conditions the rapport you
establish with the audience. You need to adopt an open stance and style which engages with the
audience, rather than distances you from them. You also need, as far as nerves may permit, to be as
natural as possible.
Depending on the particular situation (formality, size of audience, size of room, etc.), you may be able
to make a decision about whether you should stand or sit to make your presentation. Whichever way
you do it, do not hide yourself away behind a desk or lectern, or feel that you have to retain the same
stance and remain motionless throughout the session – a certain amount of movement will be more
natural. For example, if you are using a lectern, it is quite acceptable to move away from it, and
indeed, such movement may help to engage the audience.
If you are the sort of person who would naturally use your hands as you express yourself, feel free to
do so, but beware of over-expansive gestures, as this will detract from what you are saying.
It is important to maintain eye contact with the audience as a whole. This helps to show interest in,
and engagement with, your audience. Let your eyes move over the audience and avoid fixing your
gaze on one particular individual. This is where you will see the importance of using only cue cards
rather than a full script – you will be able to glance at your notes without losing the impact of eye
Eye contact is also important because you should all the time be watching for feedback from the
audience, and assessing people’s level of concentration. Try to vary the intensity of your delivery to
take into account the need for individuals to refocus.
In using any visual aids, it is important to remember that you need to maintain contact with your
audience as you write. Do not turn your back for too long, and never speak without turning to face
the front.
Participation
The final point in considering the delivery of a presentation lies in respect of the way in which you
interact with the audience. Oral communication is essentially a two-way process, and although in a
presentation you will have a lot of one-way presenting of information to do, do not lose track of the
need for some degree of participation.
96 Oral Communication
© Licensed to ABE
At the least, you need to consider how you deal with questions. There are, basically, two alternatives:
leave them until the end, when you can set some time aside for them – which provides you with
more control over the running of the session, but can be very uninvolving for the audience at
the time; or
take them as you go along – which has the advantage of resolving any issues at the time they
arise, but can be difficult to handle as it may throw out your timing or disrupt your planned
order of dealing with topics. This method allows for a higher degree of audience involvement
and works best with smaller, less formal groups. However, even in larger, formal presentations,
it is best to allow some degree of questioning on points as they arise, but do not be afraid to cut
short discussion and defer consideration of particular points to a later stage of the presentation
or the end.
Whichever method you use, you need to take control over it and explicitly state the way in which you
intend to handle questions in your introduction.
Allied to this is the question of allowing for audience response and feedback to what you have to say.
Depending on the type of presentation, it is quite possible that people will want to discuss issues you
raise. Again, you may want these to be aired as they arise and encourage participation and
involvement from your audience. However, in anything more than small, informal groups, this can be
very hard to control. Remember that you have a presentation to give, not a discussion group to run!
The best time for discussion is at the end, when you done your bit and can allow time for the audience
to make their contribution.
Do not, though, ignore your audience. Very often, they can make a valuable contribution to the
development of your presentation by providing examples from their own experience and contributing
their own ideas. Obtaining their input at certain points is a useful device for involving them, as well
as bringing in real issues of concern to them. Thus, in developing a list of, say, safety problems
encountered at the workplace, you could usefully solicit examples from your audience, rather than just
presenting your own.
In doing this, you need to ensure that you can keep control over what is said. It is easy to get
deflected from the central line of your presentation by the issues that may be raised. You need,
therefore, to know the types of responses you want to get, so that you can classify the actual responses
to fit in with the way you want to develop your argument. It is important, then, that you are prepared
for such an aspect to your presentation. J ust because you are going to get the audience to contribute
something, doesn’t mean that you don’t have to plan for it.
It is helpful to record the responses you get by writing them onto a flipchart or marker board. In
doing so, you can respond yourself to the input and perhaps put the specific instance raised into a
classification which suits you. (Remember, whenever you write anything up during the course of the
presentation, that you have to write legibly and in large letters!).
Oral Communication 97
© Licensed to ABE
C. USING THE TELEPHONE
Purpose of Telephone Calls
There is no area of business that is not affected by the use of the telephone. Using the telephone as an
effective communication tool requires an understanding of the purpose of the communication and the
effect that telephone communications can have on your audience. The postman may ring twice, but
your customers or colleagues may only ring once.
Using the telephone effectively can result in:
An increase the level of personal contact and the development of ongoing “live” relationships
– both internally and externally, crucially with customers/clients.
Immediate response to issues – which may be particularly important in maintaining good
customer relations.
Improved information flow within and around your organisation.
A reduction in time spent writing letters (and awaiting responses) and consequent reduction in
administrative costs.
An enhanced total quality performance of your business.
Figure 4.3 illustrates the range of business telephone calls within an organisation and how the
telephone can provide real customer and business support.
98 Oral Communication
© Licensed to ABE
Telephone activity Benefits to organisation/audience
Desk research Identify who to contact in a specific organisation. Must
have clear purpose.
Telemarketing Identify potential markets for goods/services.
List cleaning Updating databases. Check names, status and addresses of
contacts.
Direct mail Follow-up call reinforces message. Additional market
research opportunity.
Issuing invitations to customer
events
More likely to gain commitment. Recipient of call will
check diary. Letters may be filed or destroyed.
Questionnaires If brief and purposeful, useful information can be gained.
Prospecting Allows initial research. Establishes profile and referral
process.
Appointment making Give outline as to proposal to be discussed; give alternative
dates and times. Allows recipient to feel in control.
Customer care calls Most effective if timed correctly. 9-9.30 a.m. and 2.30-4
p.m. are often bad times for clients working from home.
Account management Saves client money as call cost borne by you rather than
lengthy written correspondence.
Renewing business contacts Re-establishes your position.
Selling Requires efficient support systems to deal with further
enquiries, sales and after sales.
Order taking Tell (sell) what you have in stock, not what’s unavailable.
Retrieving lost business Re-establish client contact. Client may feel more important
as a result of this selection.
Handling enquiries Key is to stay calm, listen carefully and respond quickly to
enquiries. Follow up referrals.
Dealing with complaints
Invoice queries
Credit control
Establish the facts. Ensures that there is a sense that an
individual, not an organisation, is concerned.
Internal calls May be more informal but a lot of important information
exchanges can be made.
External calls – customers and
suppliers
More effective if you ring at a time which suits them and
when you have all relevant data and questions.
After-sales service/follow-up
calls
Prospects for future business. Helps achieve client loyalty.
Figure 4.3
Oral Communication 99
© Licensed to ABE
Successful Calls
Listening is the key to a successful telephone call. People who communicate well on the telephone
are not easily distracted. They will listen attentively and let the caller know that they are listening by
utilising phrases like “Yes, I see”, “I understand”. This kind of feedback is extremely important in
using the telephone since there are no visual clues between the participants as to how the interaction is
going. (Have you ever had the experience that there was suddenly no one on the other end of the line
– “are you still there”?)
Speaking clearly and calmly is far more important than worrying about an accent or having to use a
“telephone voice”. Telephones are in the majority of homes and nearly all businesses (it is hard to
imagine a business which doesn’t use a phone), and most people are used to using the telephone
socially. In the business context there is no need to adopt a new persona and voice but you should be
clear as to the purpose of the call, who you are talking to and what the desired outcome may be.
Business telephone calls often appear casual or informal but will take place within the context of a
need to share, impart or acquire knowledge or information. Remember that every time you answer
the telephone or make a call, you should be representing the organisation to its fullest advantage.
Telephone calls, like all business communications, must be purposeful. Callers must have a clear idea
as to:
(a) Who their audience is.
(b) The nature of the organisation they are contacting.
(c) What information to convey.
(d) What questions to ask to elicit desired responses.
(e) What action to take as a result of the call.
Making notes prior to and during calls is a useful way of ensuring that you cover and remember the
salient points. Remember that your attitude to the audience or client is reflected in:
Your tone of voice.
The type of language you use.
The clarity with which you express your ideas.
How attentively you listen to their responses.
Your confidence and enthusiasm.
It is possible to write a successful business communication, however “bloody” you feel towards the
recipient. It is not possible to make a successful telephone call if:
You are unsure of the purpose of the call.
You don’t know who to contact.
You can’t be bothered. (“I’m so busy. I just managed to fit you in today.”)
You feel anger towards the person you will be contacting
You are unprepared.
“Smile when you dial” is more effective than to “groan on the phone”.
100 Oral Communication
© Licensed to ABE
Telephone Technique
An effective telephone call is one when you’ve sent your message to the audience, received
appropriate feedback and are able to take action. Even complaints can be positive and allow for more
efficiency in services provided. You must welcome calls and callers whatever the circumstances.
The following guidelines will aid towards all your calls being positive communications:
(a) Introduce yourself and be introduced to your caller (the verbal handshake).
(b) Explain why you are calling.
(c) Indicate what you expect to gain from the call.
(d) Use open-ended questions to elicit information and to gain the confidence of the person you are
speaking to.
(e) Respond to any information you receive.
(f) Always reflect the organisation you represent favourably in your own attitude and commitment,
even when dealing with a complaint or difficult negotiation. Whatever your personal views on
a matter, be consistent with company procedures or views. It may seem friendly to agree with a
client, but it actually makes you seem disloyal and your organisation characterised by
fragmentation and lack of teamwork.
(g) Acknowledge that you are still there if listening for a longish period of time.
(h) Gain agreement or consensus as to what has been said, agreed and what future action to take.
(j) Check that you have both drawn the same conclusions.
(k) Offer alternative options.
(l) Close by thanking the person for his or her time and state that you look forward to speaking to
him or her again soon.
Every call made from your organisation says as much about your company as any other area of
activity can do.
Using Answerphones to Your Advantage
Answerphones allow organisations to get on with their business without interruption at key moments,
mean that there is always a voice at the other end of the phone, and allow for 24-hour communication
worldwide.
They are at their most effective as a communications medium if:
(a) The answerphone message is clear, announces the name of the company or individual, and
repeats the telephone number so that the caller is certain that he or she has rung the right
number.
(b) The answerphone message requests name, company name, message or date and time called
(unless digitally recorded) from the caller.
(c) Messages are responded to quickly and appropriately.
(d) Instructions as to when to leave the message are given (after the long or short tone).
The caller must be able to leave his or her details clearly and suggest an appropriate time for a return
call.
Oral Communication 101
© Licensed to ABE
It is better to hang up before leaving a message if you feel unable to do so clearly, than to leave a
bumbling, incoherent one. The most confident telephone callers can be caught out by answerphones –
be prepared, have notes as to the purpose of your call and leave a clear, concise message.
Message Taking
If you answer a telephone call and take a message for someone else you must note down certain
important details:
The name of the person the caller wanted to speak to
Name, organisation, telephone number and possibly address of the caller
The day, date and time
The name of the person who took the message
The message and any action needed, e.g. call back urgently
102 Oral Communication
© Licensed to ABE
103
© Licensed to ABE
Study Unit 5
Visual Communication
Contents Page
Introduction 104
A. Nature and Purpose of Audio and Visual Aids 104
What Are Audio-Visual Aids? 105
Using Audio-Visual Aids Effectively 106
B. Designing Audio-Visual Aids 109
Using Words as Visuals 109
Overhead Projector Transparencies 110
Slide Projectors 110
Flip Charts 111
Whiteboards 111
Video 111
Physical Objects 112
Using Sound Effectively 113
Physical surroundings 113
C. Presenting Statistical Information 115
General Principles 115
Tables 116
Graphs 117
Bar Charts 118
Pie Charts 121
Pictograms 122
D. Design and Corporate Identity 123
Lettering 123
Reading and Interpreting Signs and Colours 124
Corporate Image 125
The Basis of Corporate Identity 126
Case Study: MCCormick Group of Companies 127
104 Visual Communication
© Licensed to ABE
INTRODUCTION
The written or spoken word are just one means of communication, albeit the most important. On their
own, though, they can tend to be somewhat boring – too many pages of text to wade through, listening
to a speaker for too long, etc. can turn off the best recipient no matter how good the form of
presentation. One way of alleviating this is the use of visual or graphical effects within reports,
booklets, manuals, information brochures and oral presentations.
We start by following up our examination of presentations and presentational skills by looking at the
role of audio and visual aids. In many forms of face to face interaction, it is very helpful to use visual
displays to assist in getting your message across – for example, jotting down a diagram to help
explain the way a system works to a colleague. The same principle applies in presentations, except
that the way in which such visual aids are used needs to be carefully integrated with the rest of the
presentation. Here, then, we shall examine the nature and purpose of audio and visual aids, and how
you can use them to enhance the giving of a presentation.
Our second area of study here is the presentation of statistical information. Figures on their own –
particularly lengthy tables – convey little to the average eye, and it is usually very difficult to pick out
the important relationships between various items without a thorough examination of the figures.
Graphs, bar charts, pie charts, etc. present the information in a more accessible form, enabling the
whole range of the subject and particular relationships to be seen at a glance. We shall, then examine
the way in which such visual representations can be used to draw attention to the key points.
Finally, we shall consider issues of design in general and of its application to the corporate image
which companies project in particular. Good design is essential in today’s competitive business
environment, as the expectations of the public are now very high in this respect. We shall, then,
review the contribution of design to good business communications and examine some of the many
vehicles for conveying corporate image.
A. NATURE AND PURPOSE OF AUDIO AND VISUAL AIDS
This study unit is concerned with the effective use of audio and visual aids. Although such aids can
greatly enhance a presentation, not every presentation will need them or be more effective because of
them. Using audio and visual aids in order to appear more professional but without reflecting the
purpose of the presentation is time-wasting, costly and can make you appear more concerned with the
trivia rather than the detail of your presentation. They can also detract from, rather than enhance, your
performance – unless they are well produced and relevant, they are a waste of everyone’s time. The
more sophisticated the technology, the worse the disaster if anything goes wrong.
So, what is the point of using audio and visual aids at all? (Note that we need to include the effective
use of audio – the notion that we only use visual aids in a presentation is incorrect.)
Appropriate audio or visual aids, if used selectively (with regard to timing, format, complexity) and
designed to a standard expected of the presentation, can enhance a good presentation and increase its
effectiveness through:
creating awareness;
encouraging interest;
retaining involvement;
achieving instant results/responses;
Visual Communication 105
© Licensed to ABE
describing in one image an entire proposal or concept;
being memorable;
complementing the spoken word;
reinforcing corporate identity.
If you are planning a presentation, you need to ask yourself:
(a) Would this presentation be improved by using audio-visual aids?
(b) What would be the most appropriate format?
Do not ask yourself “What audio-visual aids shall I use?”. The difference is a subtle one but the
message is clear. Only use audio-visual aids if they will enhance your presentation and are
appropriate.
If, after appropriate consideration, you do decide to use them to make more effective presentations,
then you must determine:
The range of audio-visual aids available and their advantages and disadvantages.
How to design audio-visual aids.
How to make the best use of all audio-visual aids at your disposal.
These are the key issues with which we shall be concerned in the rest of this unit.
What Are Audio-Visual Aids?
Quite simply, visual aids are those items which make use of pictures or visual images (including the
written word) in support of an oral presentation. We also need to include audio aids because,
increasingly, music or sound effects can be used to add impact to a presentation, and some (such as
video) combine visual and audio.
The range of AVAs available is illustrated in Figure 5.1.
106 Visual Communication
© Licensed to ABE
Figure 5.1: Audio-Visual Aids
Using Audio-Visual Aids Effectively
Before deciding to use audio-visual aids as part of a presentation, you need to be certain that they will:
Enhance the presentation.
Not detract from its effectiveness.
Be professionally produced and presented.
One of the best reasons for not using audio-visual aids is a lack of confidence in using them. In every
instance you need to be familiar with the equipment you are going to use and to have a fall-back
position if the unexpected (like a power cut) should happen. Remember that audio-visual aids support
and enhance presentations. Presentations are not showcases for the most technically advanced or best
produced audio-visuals.
Never forget that you have included audio-visuals in your presentation for the benefit of your
audience. It does not matter what type of audio-visual you use, the following criteria must be met:
Visual Communication 107
© Licensed to ABE
Language or images are selected which reflect the nature of the presentation and represent a
dimension of the subject under discussion/being presented.
Care is taken not to use offensive images, phrases or music. (Do semi-clothed people actually
sell cars?)
The seating arrangements/room layouts are designed (and double-checked by you) so that
everyone can hear or see what’s going on.
There is sufficient technical back-up.
You do not use effects which could upset your audience (e.g. loud bangs, flickering lights,
strobe lights, fireworks) or even endanger them.
You opt for simplicity and clarity rather than complexity and confusion.
Always make reference to a visual.
Don’t turn away from the audience to operate audio-visuals; either use technical support or
arrange for your and the audience’s convenience.
Try not to obscure visuals by standing in front of them.
To keep attention, use audio-visuals at low attention periods such as after lunch, before a break
or towards the end of a session.
Rehearse.
Figure 5.2 provides more details about the effective use of particular aids.
108 Visual Communication
© Licensed to ABE
F
i
g
u
r
e
5
.
2
:
E
f
f
e
c
t
i
v
e
u
s
e
o
f
s
e
l
e
c
t
e
d
a
u
d
i
o
-
v
i
s
u
a
l
a
i
d
s
Visual Communication 109
© Licensed to ABE
B. DESIGNING AUDIO-VISUAL AIDS
The reasons for using audio-visual aids are to:
Illustrate the point/concept you are making/introducing.
Reveal a product or image rather than describe it.
Engage and/or retain the interest of your audience.
Add variety to your presentation.
As we have said, there is little point in designing sophisticated audio-visual aids unless they have
relevance to your presentation and add value to it. Note, too, that badly designed, although well
planned and intentioned audio-visual aids, have a more negative impact than not using any audio-
visual aids at all.
However, not everyone is a graphic designer, cartoonist, calligrapher, desk top publisher and layout
specialist. In this section we will consider how best to design audio-visual aids using a variety of
formats but always bearing in mind that it may be necessary to call in the experts to aid in production
of the finished article.
The starting point that you need to be clear about is:
The purpose of the presentation.
The need for audio-visuals.
The most appropriate audio-visuals for this presentation.
How and when you plan to use the audio-visuals.
Using Words as Visuals
Clearly, many visual aids will include words – indeed, words will often be the dominant image on
overhead projector (OHP) transparencies, slides and flip charts, etc. You will probably want to use
them to summarise and highlight key words or phrases.
Whenever you use words in visual displays, always ensure that:
the text is clear, straight and large enough to be read easily throughout the room;
all words are spelt correctly
lower and upper case letters have been used properly
there is a clear margin around the edge of the whole display and that there is sufficient white
space around the words to enable them to stand out clearly.
It is preferable not to use hand-written text on any pre-prepared displays (with the exception of flip
charts which cannot be used in any other way), although obviously anything written on to a display
during the course of the presentation will have to be hand-written. The same points as above apply.
Note, though, that the point of a presentation is not to engage in a communal reading session. You do
not want your audience to be concentrating so much on assimilating the words that they do not follow
what you are saying or miss the context in which the visuals are being introduced. Putting words up
on display also makes people feel that they should be noting them down and you do not want this to
occupy the audience at the expense of listening or engaging in a dialogue.
110 Visual Communication
© Licensed to ABE
Overhead Projector Transparencies
OHPs project an image from a transparent sheet onto a wall or screen. The projection can be large or
small, depending on the needs of the room size and audience, making them a very versatile aid in
many different circumstances.
It is best not to include too much, or too complex, information on a transparency. You do not want
your audience concentrating on reading large amounts of text on the screen, or trying to work out a
statistical table, when they should be concentrating on what you are saying. They are, therefore, best
used to display summaries – either as an introduction to a topic to show the structure of how you are
going to work through it, or at the end as a précis of the main points covered. They can also be used
to present summary information, such as simple charts or diagrams, or examples to illustrate the
points you are making as you go along.
OHPs have the advantage that you can refer directly to the information being displayed – by pointing
to items on the transparency itself – without having to turn away from the audience. You can also
easily cover certain items on the sheet with a piece of paper so that, for example, a list of points can
be revealed one by one – as shown in Figure 5.3.
Using AVAs Using AVAs Using AVAs Using AVAs
OHPs OHPs OHPs OHPs
Slides Slides Slides
Flip Charts Flip Charts
Videos
1 2 3 4
Figure 5.3: Revealing points one by one
Being able to prepare OHP transparencies in advance means that you can obtain a very professional
looking finish. (This is in contrast to producing hand-written material during the presentation itself.)
Materials may be produced on computer – either from word processing packages or specialist
presentation packages – and printed directly on to transparencies to produce the best effect. Doing it
this way may mean that colour can be used, depending on the printer available, and that particular
styles can be consistently employed, perhaps including a company logo. However, even if you
produce transparencies by hand, effective results can be obtained by neat, clear handwriting and use
of different colours.
When using OHPs, ensure that the equipment is in working order and is correctly positioned – both
for you to use and for your audience to see.
Slide Projectors
These are used mainly to display photographs, but other high definition images may be produced on
film to be presented in this way. They are particularly useful for providing illustrations of real items
or events – such as a new product or a location.
Visual Communication 111
© Licensed to ABE
It is also possible to use tape/slide packages, with a recorded commentary alongside the slides.
However, this can detract from the relationship you have with your audience, so should be used with
care.
Again, if you are using slides, make sure the projector is in working order (and that you know how to
use it!) and is correctly positioned. You also need to ensure that your slides are correctly mounted and
in the right order.
Flip Charts
Flip charts are very useful in a small seminar, working group or brainstorming session, but present
real problems of visibility in larger groups.
They can be used, in a pre-prepared fashion, in a similar way to OHPs – displaying a framework for
the session (or parts of it), notes of key points, summaries, etc. – although you cannot reveal points
one by one. However, they come into their own as a means of displaying points during a session,
particularly those raised by participants during discussion, which can then be kept and returned to for
be review.
In using flip charts, the same principles apply as above in respect of the use of text generally, and of
handwriting in particular. In addition, you need to ensure the following:
that you have sufficient pens available, that they all work properly and do not dry out;
that there is a sufficient supply of paper;
that you do not obscure what you are writing;
that your writing is not too small, not that it trails off the page.
Also, beware the problem of having to keep cross-referencing to previous sheets which is time-
consuming and confusing for your audience.
Whiteboards
Whiteboards are plain surface display boards on which you write using a special marker pen, as for
flip charts. They may be wall mounted (as in some purpose built training rooms) or portable.
They are an alternative to flip charts in small presentations as a means of writing up key points during
a presentation, although they cannot really be pre-prepared. There are, though, a number of
drawbacks to them:
They need to be wiped clean when the board is full.
They cannot store material for reference as in flip charts, for example.
You must have clear, legible handwriting.
You need to check that pens and cleaning cloth are available and in working order.
If information is left for any time at all, it tends to distract.
They seem to establish a teacher-pupil relationship rather than a dialogue between presenter and
audience.
Video
Videos are widely employed in training situations and are increasingly being used in other forms of
presentations – particularly to show the active use of products or different aspects of
situations/locations, or to introduce someone else’s views in person, etc. There are very many
112 Visual Communication
© Licensed to ABE
commercially available videos in most areas of training and it is relatively inexpensive to produce
them oneself on specific topics, although producing in-house videos to the professional standard that
most audiences will expect is not easy.
Videos can be very effective if used properly – but remember that they should be a support for your
session, not a substitute for your own input. Thus you need to explain the relevance and purpose of
the video before showing it and give some pointers for the audience to consider whilst viewing it.
You need to be thoroughly conversant with a video before using it – exactly how long it is, where the
main points are which you want to emphasise, where you might want to break for discussion, etc.
There is a dilemma as to whether to pause a video for discussion or to discuss issues afterwards. If
the video is short – up to 10 minutes – and raises questions, then it is probably easier to discuss
afterwards. Try to avoid lengthy videos (anything over 20 minutes) unless you are in a training
session. Even then, think very carefully as to why that particular video fits your aims and objectives
and how you will draw your audience’s attention to the salient points.
Audiences tend to accept videos readily, but are not always happy to discuss them afterwards, and
there is sometimes a flat atmosphere. In addition, it is not a good idea to start a presentation with a
video because the rest of the presentation may then not appear so exciting, polished or professional.
Once again, make sure the machine is in working order (and that you know how to use it!) and is
correctly positioned. It is surprising how many times the equipment lets you down at the time when
you need it to be functioning perfectly! Make sure you know how to operate the equipment and set
volume, contrast, etc. in advance. Ensure that the screen is big enough for your audience to see the
video and that the video has been professionally produced. If you want to show several clips, have
them put on one tape and note the relevant tape section. Avoid using several tapes; you and your
audience will only get confused.
Physical Objects
It may be very useful to display materials to your audience or present them with examples of relevant
materials – samples of products, working models, presentation packs, etc. This is particularly
appropriate at trade fairs and exhibitions, but also at many other types of presentation.
All materials you use in this way must be:
Easy to control and present
Relevant to the presentation
Attention-grabbing
Large enough to be seen by everyone
You need to be completely familiar with the products you are handling. If you use working models,
check that they do actually work and have spares of everything just in case. In a demonstration,
“Here’s one that I made earlier” is a useful fall-back position.
Providing samples of products being presented can be very useful – the feel, smell and look of a
product you are discussing say so much more than words describing its values and properties. At a
small presentation you can hand out such samples, but at larger ones they are best included in a
presentation pack.. These should not, generally, be distributed during the presentation, as this will
distract attention from what you want to say, but can be provided either before – to be picked up by
the audience as they arrive, or by putting them on seats – or after the session.
Visual Communication 113
© Licensed to ABE
When handing out materials, do not push them into someone’s hand or bag – make a gift of them,
offer them up to your audience, and relinquish them slowly so that you can make eye contact with
your audience at the same time.
Using Sound Effectively
In certain circumstances, sound effects may be used on their own to enhance a presentation. These
include tape recordings, live musicians or actors, or even effects you introduce yourself.
Sound effects may be used to introduce examples of the sounds of products, contributions by other
people (although video is better for this), etc. into the presentation itself, or to smooth the transition
between sections of the presentation. The intrusion of external sounds into a presentation is likely to
be quite dramatic and you need, therefore, to ensure that any such effects are fully integrated into the
presentation. They must serve a purpose and that purpose must be made clear to the audience. Music
is quite often used for the second purpose – transition – with dramatic themes used for introducing
speakers or the unveiling of products, or suitably soothing music at the end or during a break.
You need to ensure that any technical issues are sorted out in advance – amplification is loud enough,
but not too loud, for the audience, the quality is crystal clear (no hiss, scratches, etc. on recordings) –
and that you have rehearsed any cues with the tape operator or live musicians as to when to come in.
One of the most effective ways of using sound in a presentation is to make use of the silences. Make
each pause one of anticipation. It can be used as a sound effect – for example, “Listen. Can you hear
that? That’s our new model XYZ. Silent as a lamb!”
Another possibility is not speaking until everyone is seated in order to create an expectant hush.
Physical surroundings
Whilst not an audio-visual aid in itself, the physical surroundings in which a presentation takes place
can have a dramatic effect upon its effectiveness. We can consider three such aspects.
(a) Lighting
The most important factor to remember is to check how lighting affects the audience. Try to
see your presentation from their perspective, not from your own position on the stage or
podium. It may be comforting to feel that you can’t see your audience, but from their
perspective the whole presentation may be leaving them in the dark.
All visual aids need their light projected from the place that causes least shadow when they are
in use. The lighting must be strong enough to produce a clear image. General lighting
available in a small presentation will be sufficient. In a large or dramatic presentation, spot
lighting, fading in and fading out, and coloured lighting might be used.
(b) Décor
When choosing an external location for your presentation, décor will certainly be a factor.
Internally it is more difficult to influence décor. Use company publications and brochures to
create an area of interest which will divert attention from hideous curtains or carpets. Screens
and curtains can be used to fence off unsightly areas.
(c) Seating and layout
Seats should be functional and comfortable and in positions where the audience is able to see
your presentation to its fullest advantage. If you want the audience to be able to write things
down during the presentation – either making a lot of notes or carrying out written exercises –
then you may want them to have desks or tables. If you want a lot of discussion, then a more
informal layout and speaker position may be appropriate.
114 Visual Communication
© Licensed to ABE
Some possible layouts for small presentations are shown in Figure 5.4.
Figure 5.4: Layouts for small presentations
For large presentations, the presenter is likely to be on a stage of some sort – a raised platform,
an actual stage or simply a separate area from the audience – facing the audience who will be
seated in rows.
Tables are useful for presenters and audience alike to rest on, store materials or act as a barrier.
How the presenter makes use of a table in a small presentation affects the audience response, as
illustrated in Figure 5.5.
The key is for the presenter to use all the available space and to dominate. Being mobile, the
presenter is a very effective visual aid him/herself and is in a good position to judge audience
reactions and responses.
Visual Communication 115
© Licensed to ABE
Figure 5.5: Presenter positions
C. PRESENTING STATISTICAL INFORMATION
Presenting statistical data in an effective visual way is an important and powerful skill in business
communications, whether it is used in reports, presentations or meetings.
Whether you are dealing with a small or a large amount of data, it is always necessary to consider how
you are going to present it. By choosing an appropriate method, you can demonstrate important
features of the data and highlight significant patterns. By using different techniques of tabulation and
presentation, you can transform raw data into meaningful information.
General Principles
Statistical information is the result of the analysis and manipulation of raw quantitative data to give it
meaning. Invariably, that meaning is in terms of its value to decision makers, and as such it is not the
statistics themselves which are important, but their interpretation. The key point, then, is that
statistics on their own are not necessarily significant, but they are important as a support for other
statements. Thus, statistical information should not be presented for its own sake, but should be used
in relation to the points being made in the report or presentation.
116 Visual Communication
© Licensed to ABE
As such, a number of general principles can be identified for the use and presentation of statistics:
All statistical information needs to be set in a context which explains its relevance to the points
being made.
The amount of detail needs to be kept to the minimum necessary to support the arguments in
the report/presentation.
The source of the data must always be stated.
In relation to this last point, it is important to distinguish between primary and secondary data:
(a) Primary Data is where data is collected for the specific purpose under discussion, in which
case, it will invariably be directly relevant;
(b) Secondary Data is where the data which has been collected for some purpose other than that for
which it is now being used – in which case, it needs to be used with care and you need to ensure
that it does actually provide the meaning you give it in the report/presentation.
Tables
Tabulation is an important element of visual or graphical enhancement – for statistical information or
as a means of structuring text. The use of tables to summarise information in terms of relationships or
under headings gains from the fact that, in tables, you do not need to use full sentences. The
information is presented in truncated form and is likely to be more easily absorbed, although it is
important to remember that this is a summary device and fuller discussion of the issue raised will
probably be necessary elsewhere.
The value of numerical data may be increased many times by effective tabulation. Tabulation is the
systematic arrangement of numerical data which has been collected, so that a reasoned account of its
interpretation can be facilitated. It depends on a logical classification of the data into clearly defined
groups, each with characteristics of its own (for example, customers by men or women, or by different
age groups, etc.). The information is then set out clearly in the minimum space and with the
minimum wording. The following rules should be observed in the preparation of statistical tables:
each table should serve a single purpose – attempting to show more than one group of
relationships in the same table tends to obscure the message;
the table itself should have a title or caption, and each grouping of information must have a
heading, all of which should be as short as possible and self-explanatory;
tables should not contain figures with a large number of digits – rounding numbers is
acceptable since a high degree of accuracy is not usually that important (it is the relationships
which are), and expressing all figures in, say, thousands is better than writing them all out in
full;
the number of columns and headings should be kept to a minimum – a multiplicity of headings
etc. prevents the proper emphasis being given to the key facts and tendencies shown by the
table;
units must always be stated (£,000’s, age, etc.);
figures showing relationships such as percentages, ratios, etc. should be placed as near as
possible to the figures from which they are derived.
The following example (figure 5.6) shows these essential features.
Visual Communication 117
© Licensed to ABE
Very Quite Not at all
Local press ads 23% 43% 34%
Classified ads in local press 19% 41% 40%
National press ads 11% 39% 50%
TV ads 15% 32% 53%
Direct mailshots 9% 23% 68%
Figure 5.6: Usefulness of Advertisements in Influencing Car Purchase
(Source: Hypothetical data, 199X)
Graphs
Line graphs illustrate the movement of one variable against changes in another variable. For example,
the graph shown in Figure 5.7 shows sales over time, and such diagrammatic representations of trends
over a period are the most common use. Other common examples are sales against changes in price
(as in demand and supply graphs used extensively in economics) or health indicators such as levels
lung cancer against, say, levels of smoking.
Figure 5.7: Example of a line graph – Car rental sales, 1999 – 2000
(Source: Hypothetical data)
Graphs can also illustrate comparative trends by including figures for several products or different
time periods on the same diagram. Thus, Figure 5.7 shows sales on a month by month basis over two
years. Lines may be differentiated by the use of different types of line or, where available, by colour.
There are some general rules to remember when planning and using graphs:
All graphs must be given clear but brief titles.
The axes of graphs must be clearly labelled, and the scales of the values marked. The origins of
scales should generally be included.
0
1
2
3
4
5
6
J an Feb Mar Apr May J un J ul Aug Sep Oct Nov Dec
Sales (£000)
1999
2000
118 Visual Communication
© Licensed to ABE
Wherever necessary, gridlines should be inserted to facilitate reading.
Bar Charts
The bar chart is one of the most common methods of presenting information in a visual form. They
are similar to graphs in that they display the incidence of one variable in relation to another (for
example sales against time), but are more flexible in that greater amounts of information can be
incorporated – for example, showing breakdowns of components of a variable.
There are. basically, three types of such charts:
simple bar charts – which are equivalent to line graphs, but provide a stronger visual image;
component bar charts – which are equivalent to a series of pie charts; and
histograms – which display grouped frequency data.
(a) Simple Bar Charts
A simple bar chart is a chart consisting of a series of bars representing the amount of one
variable in relation to another. Usually, a small space is given between each bar to allow them
to stand out from each other. The length of each bar corresponds with the magnitude of the
item it represents. In Figure 5.8, the height of the bars relates to revenue from theatre ticket
sales in a certain month.
Figure 5.8: Example of a simple bar chart – Revenue from theatre ticket sales by month
(Source: Hypothetical data, 199X)
Bar charts can be enhanced by the use of 3D effects, although you would need to use a
computer presentation package to display this effectively (an example is shown below).
In addition, you can add figures for comparative purposes and display these as bars next to each
other. Figure 5.9 shows the information on car rental sales from Figure 5.7 as a composite
simple bar chart.
0
1,000
2,000
3,000
4,000
5,000
6,000
7,000
J an Feb Mar Apr May J un
Revenue (£)
Visual Communication 119
© Licensed to ABE
Figure 5.9: Example of a composite bar chart – Car rental sales, 1999 – 2000
(Source: Hypothetical data)
(b) Component Bar Charts
A component bar chart can be used to give a breakdown of the total amount within each bar of
the chart. Thus, in the simple example above, we could divide the monthly figures into the
revenue generated by different types of ticket – perhaps showing the number of £20 tickets, £10
tickets and stand-by £5 tickets that are sold in each month.
Figure 5.10 shows a component bar chart, with a 3D effect added, for tractor sales over four
years by three different areas.
Figure 5.10: Example of component bar chart – Tractor sales by area, 1996 – 1999
(c) Histograms
Although histograms appear to be the same as bar charts, there are important differences. They
are used to display grouped frequency data – for example, information relating to the numbers
of people in different age groups.
0
10
20
30
40
50
60
70
80
1996 1997 1998 1999
North
Midlands
South
0
1
2
3
4
5
6
J an Feb Mar Apr May J un J ul Aug Sep Oct Nov Dec
1999
2000
N
u
m
b
e
r
o
f
t
r
a
c
t
o
r
s
s
o
l
d
(
t
h
o
u
s
a
n
d
s
)
120 Visual Communication
© Licensed to ABE
In Figure 5.11, the histogram shows numbers of managers in different salary brackets. Thus,
we can see that 2,000 managers earn between £15,000 and £19,999. This is called grouped
frequency data as it does not specify how many earn £15,000 or £16,000, but it groups the
data together in class intervals.
The following table of information is represented in Figure 5.11:
Class Interval Frequency
£15,000 – £19,999 2,000
£20,000 – £24,999 10,000
£25,000 – £29,999 6,000
£30,000 – £34,999 4,000
£35,000 – £39,999 6,000
£40,000 – £49,999 2,000
Another key difference between histograms and bar charts is that, with histograms, the area of
the rectangle, and not just the height, is significant. So, for the salary group £40,000 –
£49,999, the rectangle is twice the width of the others to represent the fact that this class
interval is twice as big as the other class intervals.
It also means that the height of the rectangle is half as high as the class frequency (2,000)
would suggest, to compensate for the fact that the class interval is twice the size of the standard
class interval of £5,000.
Remember it is the relative area of the bars that is significant, not just their relative heights.
12,000
10,000
8,000
6,000
4,000
2,000
N
u
m
b
e
r
o
f
m
a
n
a
g
e
r
s
15,000
- 19,999
20,000
- 24,999
25,000
- 29,999
30,000
- 34,999
35,000
- 39,999
40,000
- 49,999
Salary levels (£)
Figure 5.11: Example of a histogram: Managers’ salaries
(Source: Hypothetical data, 199X)
Visual Communication 121
© Licensed to ABE
Pie Charts
These diagrams are used to show the relative sizes of component elements of a total. They are so
called because they have the shape of a round pie, with the component parts appearing as slices. They
are used to display only very simple information.
Consider the following table of market shares in the UK car rental market:
£ million
Kevin Kars 15
Martin Motors 20
Others 65
This can be shown diagrammatically as follows
Figure 5.12: UK car rental market – Market share
(Source: Hypothetical data, 199X)
The chart is constructed as follows:
Using the market value figures shown in the table, the total market value is £100m. The whole
pie will represent this figure and as the circle being used will take up 360 degrees, each slice of
market share must be sized in proportion to this figure.
Kevin Kars’ market share is worth £15m – i.e. 15% of total market value. To calculate how big
the slice should be, you need to calculate 15% of 360 degrees (which is 54%).
Martin Motors’ market share is worth £20m – i.e. 20% of the total market value. 20% of 360
degrees works out as 72 degrees.
The other car rental companies’ share is worth £65m – i.e. 65% of the total, which works out as
234 degrees.
You need to use a protractor to measure out the size of each of the slices in the whole circle.
Alternative forms of presentation are the “exploded” pie chart, in which the segments of interest are
emphasised by separation from the main pie, and 3D charts. Both of these are far easier to produce
using computer presentation software. Examples are shown in Figure 5.13.
Total market value: £100m
Others: 65%
(£65m)
Kevin Kars: 15%
(£15m)
Martin Motors: 20%
(£20m)
122 Visual Communication
© Licensed to ABE
Figure 5.13: Alternative forms of pie chart
Make sure that the diagram is clearly labelled, using a separate legend or key if necessary, and
consider is the actual figures for each segment need to be shown (since it is not possible to read these
exactly from the diagram itself). Any written text must be clearly written and accurate. Shading or
colours can emphasise key areas.
It is best not to use pie charts with more than four or five component parts.
Pictograms
A pictogram is a statistical diagram in which quantities are represented by pictures or symbols. The
appropriate use of a picture or symbol can be a powerful tool in communicating a message, but their
use is confined to the simplified presentation of statistical data for the general public, rather than for
specialists in the field.
For example, the imports of oil in a particular year may be represented by a number of drawings of
barrels, and the imports for another year by a different number of barrels, as in Figure 5.14. If you
were showing pig sales, you could use drawings of pigs, or to show sales of satellite TVs you could
use pictures of satellites – and so on.
Figure 5.14: Imports of Crude Oil
(Source: Hypothetical data, 1994 – 1996)
It is important that there is a clear key which shows what the symbol represents. In Figure 5.14, a
complete barrel represents the sale of 10 million barrels. However, difficulties arise when sales do not
fall into neatly rounded quantities – thus, for 1995 and 1996, it is difficult to know what the partially
drawn barrels represents in terms of sales.
1994
1995
1996
Key:
= 10 million barrels
Visual Communication 123
© Licensed to ABE
This form of presentation is not, therefore, precise enough for accurate depiction of figures, nor can
they show more than a very limited amount of information. However, their advantage is that they
present the information in a simple, readily understood way, and as such, they are often used with
interesting graphics to convey statistics on news programmes.
D. DESIGN AND CORPORATE IDENTITY
What is good design? This is not easy to answer, since it is very much down to personal taste. It is
essentially a subjective matter.
However, there are a number of principles which can be identified. At the heart of design is the
attempt to communicate, visually, with an audience. An understanding of the characteristics of the
audience and of the object of the design are, therefore, essential. Given that, it may be said that good
design should be:
functional;
reflect the purpose of the object or organisation to which it is applied; and
be unique to that application.
There are an immense range of application to which design is applied, but we shall be concerned here
with corporate identity – principally in respect of company branding through the use of logos. Before
we consider these applications, though, we shall review certain common aspects of design which you
can use.
Lettering
Typefaces, typestyles, lettering style or fonts are all terms for the type of lettering used by designers
and printers.
Typefaces can facilitate the reader’s ability to read text easily. They can also convey a personality or
mood, and some convey formality or modernity.
There are literally hundreds of lettering styles or fonts, and we illustrate just a few in Figure 5.15.
Each font can itself be made larger, smaller, heavier, lighter or italicised. Computer graphics
packages are introducing new fonts on what seems like a monthly basis.
Emphasis and impact can be created not only by the use of different typefaces, but also by the size of
type, use of headings, line spacing, capitals or underlining, and by the weight and boldness of the
type. In fact the layout of the page, with the use of margins, ruled lines, and the use of white space all
contribute to the impact of the actual words being used.
124 Visual Communication
© Licensed to ABE
Figure 5.15: Standard Font Types
Reading and Interpreting Signs and Colours
Visual communication which does not include text has the advantage that it can be understood in any
language. International labelling for garments, road signs and electrical goods are all examples of the
efficiency of such purely visual communication.
Visual Communication 125
© Licensed to ABE
A sign or visual image can summarise a whole body of text and is much easier to “read”, so that its
impact is immediate. Reading written text is a longer process in that its messages need to be
internalised, understood, reflected upon and summarised. They may then need to be translated into
oral or written language themselves.
The following are excellent examples of the efficacy of signs and symbols:
Figure 5.16: Instantly recognisable signs
Colour psychology is an integral factor in visual image design and interpretation. Traditionally
colours have many associations, as shown in the following table:
Table 5.1: Colour associations
Blue: cold, restful, calming, sad, conservative.
Red: vibrant, young, angry, passionate.
Green: envy, environmentally friendly, naivety.
Yellow: sunshine, brightness, new life, cowardice.
Black: evil, night, darkness, sexy.
Brown: muddy, nondescript.
Grey: dull, boring, depressing, dirty.
White: clean, bright, pure, clinical, peace.
Colours are seasonal and reflect emotions or attitude; they are not merely the absence or presence of
light. The shade and tone of a colour can change our perception of the same logo. However,
remember that different colours have different meanings in different cultures.
Corporate Image
The purpose of a corporate image or identity is to distinguish the organisation in the marketplace and
to communicate values/attributes to various audiences. The most common facet associated with
126 Visual Communication
© Licensed to ABE
corporate image is the company logo, but this is not the only element involved. Rather, it
encompasses the use of typestyle, lettering, symbols, colour, pictures, slogans or any combination of
these, and is used to maintain consistency of style throughout all forms of communication, whether
text, oral presentations or purely visual forms such as in packaging.
The potential list of applications is vast. We note some of these below as a guide to the range and
diversity available. It also helps us to recognise how repetition of the corporate logo/slogan reinforces
corporate image and that the best corporate identity is established through clear design, is instantly
recognisable (i.e. legible) and is always the same in essence (colour backgrounds may change).
Stationery
Forms
Publications
Products
Packaging
Advertising
Promotions/give-aways
Vehicles
Interiors/exteriors
Signs
Clothing
If we are serious about corporate image, then it has to be applied wholesale, not selectively. If we
take the example of stationery, the range of uses will cover all internal and external correspondence,
and its application should be rigorously enforced – scrappy internal memos undermine the
purposefulness of well produced headed notepaper. The range of stationery applications includes:
Letterheads
Continuation sheets
Envelopes
Compliment slips
Business cards
Memos
Reports
In fact, any item of company material can have the logo represented on one or all of its surfaces.
The Basis of Corporate Identity
The purpose of the corporate image design is for potential and actual customers to:
Associate the product(s)/service(s) offered by the company with the logo.
Recognise instantly and be familiar with the company.
Adopt some of the values and beliefs of the company in the product(s)/service(s) it offers by
association with the design.
Visual Communication 127
© Licensed to ABE
One of the major problems in considering corporate image is merely to determine it in design terms.
All too easily it becomes a new logo, a new slogan, the introduction of particular colours or a uniform.
These elements certainly make up corporate image, and there are numerous image consultants
specialising in just that – a design package which is standardised for every possible application.
However, the factors which determine the design for the corporate image and which give an
organisation its internal and external “personality” can be referred to as the corporate culture or
company ethos. This is the real starting point for the development of the various facets of corporate
image design.
Thus, if the design is truly going to reflect the desired image of an organisation, then we need some
detailed answers to the following questions:
What are the name, location, size and function (i.e. product/service areas, range) of the
organisation?
What existing promotional activities are there?
Is there an existing logo/slogan/corporate colours? How and where are these applied?
Is a new corporate image required, an update, or a more uniform approach/understanding
necessary?
What are the company’s perceived markets?
What image does the company wish to convey? Key words may include: up-market,
sophisticated, wide audience, specialist.
Are there any preferences as to style, colour, etc?
Who will sanction any change/implementation?
What steps will be taken to introduce a new/updated corporate image? Is a transition period
necessary? How will the internal market be informed?
What potential applications will there be of any design? Even if, in the first instance, only a
stationery pack (letterheads business cards, compliment slips, etc.) is required, the design and
colours may need also to be applied to other non-paper media, such as mouse mats and T-shirts.
The answers to these questions often form the basis of a brief which can be given to a designer to
assist the development of the image/identity.
Case Study: MCCormick Group of Companies
The McCormick Group is a construction company. The following extracts from its literature,
reproduced by kind permission, show how corporate image is designed and give an indication of the
company ethos.
Figure 5.17: McCormick Company Logo
128 Visual Communication
© Licensed to ABE
The company logo is on a racing green background with white lettering. It appears on all McCormick
divisional notepaper and business cards, on building site hoardings where McCormick is building, and
on all company vehicles and workers’ uniforms.
The design is particularly effective as it allows different divisions to have their own identity as part of
the corporate identity (see Figure 5.18).
Figure 5.18: McCormick Divisional Logos
The Group produces a folder designed as a company portfolio rather than a throw-away glossy leaflet.
It contains separate sheets of information (see Figures 5.19 to 5.22) about each of the Group’s four
divisions, which allows a sense of integration and harmony within the company’s publicity materials.
The inside covers of the folder, which enclose the separate sheets, bears the text shown in Figure 5.23,
illustrating the effectiveness of design in the presentation of text.
Visual Communication 129
© Licensed to ABE
Figure 5.19
130 Visual Communication
© Licensed to ABE
Figure 5.20
Visual Communication 131
© Licensed to ABE
Figure 5.21
132 Visual Communication
© Licensed to ABE
Figure 5.22
Visual Communication 133
© Licensed to ABE
This page has been left blank to allow the following figure to appear across facing pages.
134 Visual Communication
© Licensed to ABE
Figure 5.23
Visual Communication 135
© Licensed to ABE
Figure 5.23 (Continued)
136 Visual Communication
© Licensed to ABE
137
© Licensed to ABE
Study Unit 6
Interviews and Meetings
Contents Page
Introduction 138
A. Interviews 138
Types of Interview 138
Principles and Practice of Interviewing 140
B. Meetings – An Overview 142
The Role of Meetings 142
Constitution 142
The Organisation of Meetings 142
C. Documentation for Meetings 144
The Agenda 144
Minutes 147
D. Procedure in Meetings 149
Constitution and Standing Orders 149
Roles Within Meetings 150
General Rules of Procedure 150
Effectiveness in Meetings 151
138 Interviews and Meetings
© Licensed to ABE
INTRODUCTION
If you were asked to identify the various work situations involving the conscious exercise of oral
communication, it is likely that you would include interviews in your list. Here, we shall look at the
different types of interview which are common in organisations, and at their underlying processes, and
then go on to examine some of the principles and practices involved in interviewing.
The existence of formal meetings – for example, boards or committees – as a means of expediting
business in many organisations brings with it its own particular forms of communication. The second
part of the unit presents an overview of the role of meetings in business and of the way in which they
function, before going on to consider the requirements for effective communication in respect of both
the procedures and documentation.
A. INTERVIEWS
Types of Interview
As we have emphasised throughout this course, the purpose of an interaction is crucial to determining
the communication which takes place. We can see this in respect of a number of different types of
formal interview, thereby distinguishing the particulars of each.
It is important to remember, at the outset, that there are two parties to any interview – the interviewer
and the interviewee – and that, in most circumstances, the purpose must be considered from both
sides, irrespective of the particular side you are on at the time. However, it is always the case that the
interviewer has “control” of the process, and there is a responsibility on him/her to ensure that the
process allows both parties to meet their objectives.
Note also that, whilst interviews generally represent examples of one-to-one interaction, it is by no
means uncommon for the interviewer side to comprise a panel. However, in essence, the interaction
that takes place continues to be one-to-one.
(a) Selection interviews
Recruitment and promotion interviews are the most common perception of the interview, and
are the one type of which you will almost certainly have experience – either as an interviewer
or as an interviewee.
The objectives of any selection interview are to:
find out whether the candidate is suitable for the job and the organisation; and
find out whether the job and the organisation are suitable for the candidate.
The first objective is well understood and forms the basis of most questioning, designed to
allow the candidate the opportunity to demonstrate his/her abilities in relation to the
requirements of the post. The second objective is less well acknowledged, but should be clear
if you consider the interview from the perspective of the candidate – he/she will not only want
to show the capability to do the job effectively, but also to find out more about it and assess
whether he/she does actually want it. As a result, the interviewer has to provide the scope
within the interview to allow the candidate the opportunity to explore his/her concerns.
Interviews and Meetings 139
© Licensed to ABE
(b) Appraisal interviews
Appraisal interviews are less well-understood and, if the objectives are not clearly stated, have
the potential to become the opposite of their purpose.
The intention of appraisal interviews is to provide a focus for employee development, usually
as part of an on-going system which includes the provision of development opportunities. The
interview is not, therefore, a one-off event, but one of a series between the employee and
his/her manager (or other designated appraiser). The purpose is two-fold:
to review past and current performance in the job, from both the appraiser and
appraisee’s points of view; and
to plan the future development of the individual.
It has, therefore, a positive focus which should condition the interview process. If conducted in
a careful and sensitive way, appropriate to this central focus, the appraisal interview can be a
positive experience, and will be of benefit to the individual and the organisation.
(c) Disciplinary interviews
Disciplinary interviews are held to consider whether disciplinary action should be taken against
an employee, usually in accordance with the organisation’s disciplinary procedure. This can
have very serious consequences. It is crucial, therefore, to be clear about the objectives of the
formal interaction.
The most important point is that the interview must aim to establish the truth about what has
occurred. As such, it cannot be regarded as one-sided, but rather must be a two-way process to
tease out the facts of the situation. The principles of natural justice demand that the employee
concerned must have the opportunity to put his/her case properly, and issues of personal
prejudice and partiality have to be very carefully dealt with.
The need for careful preparation is paramount in this situation. In particular, it should be the
culmination of a process which has included a thorough and impartial investigation of all the
issues.
In disciplinary interviews, it is usually the case that the interviewee is able to be accompanied
by a representative or “friend” – to advise, support and possibly speak on his/her behalf, as well
as acting as a witness to the proceedings.
.
On the face of it, the aim of the interview is to resolve the grievance. However, having said
that, it isn’t necessarily the solution which is the most important outcome. Often the way in
which the solution is arrived at can be just as important – even an ideal solution may be
ineffective if it leaves the participants still feeling aggrieved (for example, because it was
arrived at only after bitter argument, accusation and counter-accusation).
This indicates that the way in which the grievance is handled is every bit as important as the
solution itself. Employees arrive at grievance interviews with a sense of injustice. They should
leave with at least the feeling that they received a fair hearing and consideration.
140 Interviews and Meetings
© Licensed to ABE
The aim, therefore, in handling a grievance interview is to arrive at a solution through a
discussion which, as far as possible, provides a satisfactory conclusion to all parties.
Principles and Practice of Interviewing
Although the contexts for these interview situations are different, we have established a number of
common themes to them all – the need for the process to be two-way, acknowledgement of the
objectives of both parties to the process, etc. We can, then, look at them in the same way when it
comes to understanding the way in which interviews are conducted.
The principles and practice of interviewing derive directly from the basic two-stage process we
considered earlier – preparation and delivery. We can work this through in respect of the particular
requirements of interviewing.
(a) Preparation
Each type of interview has its own general aims, as we saw above. In preparing for a specific
interview, it is important to identify the particular objectives which apply within these. Thus, in
respect of a job interview, the particulars of the job itself – and the knowledge, skills and
attitudes required for it – will inform the framing of the desired outcomes and the structuring of
the interview to achieve them. Similarly, the particulars of an individual case will condition the
approach in a grievance interview.
Gathering and organising relevant information means ensuring you are fully conversant with
the subject area of the interview – for example, the job requirements, the employee’s appraisal
records and employment history, the details of the disciplinary or grievance case. Picking out
the salient points is likely to provide the structure for the interview. Thus, a selection interview
can be built around the details of the job description and person specification, or an appraisal
interview planned around the employee’s recent work experience and development activities.
It is surprising how often interviewers do not really inform themselves about the person or
persons they are interviewing. It necessitates considering the background information available
about the interviewee to form a picture of the specific person, such that the interview itself can
be tailored to him or her in particular. Thus, for selection interviews, the candidates’
application forms will provide details of education and employment background, together with
some indication of experience and skills. These can be used develop the general lines of
questioning in respect of the job description and person specification, which should be common
to all candidates, into specific questions appropriate to each individual.
Arranging the venue and setting means getting the administration of the process right –
notification of times (and keeping to them), reception arrangements if necessary, etc. – and
establishing an environment for the interview itself which will be supportive of the objectives
and help, rather than hinder, the interaction. Thus, there should be a comfortable, private room
available, with no distractions in or around it. This may mean arranging for phone calls to be
re-directed, warnings to prevent interruptions, etc. The physical layout needs some thought – it
is usual to make the setting informal, with no barriers between the interviewer and the
interviewee (such as an imposing desk), although some people find that a complete lack of
formality makes them feel somewhat exposed.
Finally, most good interviewers – even very experienced ones – generally run through what
they are going to say. This can take the form of actually rehearsing questions, particularly in
respect of the style and intonation used, or simply talking through the planned structure with a
colleague to ensure that it is correct. Clearly, where there is a panel of interviewers (i.e. more
than one), this process is essential so that all participants are aware of the proposed procedure.
Interviews and Meetings 141
© Licensed to ABE
(b) Conduct of the interview
It is important for the interview to be structured in order to keep the process focused on the key
points and to avoid irrelevant discussion and time wasting. Remember too that the interviewer
is responsible for conducting the process and ensuring its successful outcome.
The interview itself can be seen as a four-part event, characterised by the acronym WASP.
W Welcome – greetings and introductions, each party to the other, with the objective of
establishing rapport and relaxing the participants. Particular points include:
putting the interviewee at ease;
explaining the purpose of the interview and outlining the way in which it will be
structured;
explaining, if appropriate, about taking notes.
A Ask – the process of questioning whereby information is sought from the other party in
relation to the objectives of the interview. We shall be considering questioning
techniques in detail in the next unit, but other points include:
using questions prepared in advance, based on the general aims and specific
objectives of the interview and the particular circumstances of the interviewee;
using open questions (which encourage developed responses and further
discussion), working from relatively general and easy ones to more specific and
difficult ones;
listening to, and probing the interviewee’s responses.
S Supply – providing full and honest responses to questions which will show the
respondent in the best possible light, according to their objectives. Particular points
include:
backing up assertions with examples wherever possible;
being reasonably concise, particularly in the case of the interviewer (the
interviewer should only do 20 – 30% of the talking).
P Parting – ending the interaction on a positive and cordial note, with a clear idea of what
has happened and what will happen next. Particular points include:
summarising conclusions, where appropriate;
identifying when, what and how any action arising from the interview will be
communicated.
142 Interviews and Meetings
© Licensed to ABE
B. MEETINGS – AN OVERVIEW
Formal meetings of committees and boards, sub-committees, steering groups and working groups are
widely used in both public and private sector organisations. In addition, all sorts of different groups,
within and outside business organisations, hold formal or informal meetings on a regular or ad hoc
basis. Thus, it may be said that all organisations have a committee or meetings structure of some sort.
Note that, whilst the discussion here will be mainly focused on committees or other formal meetings,
the principles apply generally to most types of meeting.
The Role of Meetings
The main functions of any of these meetings may be summarised as:
providing for a dialogue between members, allowing the exchange of information, views and
opinions;
generating ideas or solutions to problems;
monitoring and evaluating performance or progress;
making policy and other decisions.
These general functions hold true for the meetings of informal working groups, a school’s parent-
teacher association, and company boards and governmental bodies. There are, clearly, differences in
scale and the issues considered, but the general purpose is the same.
Constitution
The particulars of the meetings of a body are determined by the nature of the body itself and this will
be laid down in its constitution. The constitution of a body will cover such fundamental matters as:
membership – who is entitled to be a member and how membership may be determined,
numbers, length of service, etc.;
terms of reference – the powers and duties of the body (what it can and cannot do, and what it
must do), so for example, it may have the power to make proposals and suggestions, but not
actually to commit the financial resources of the organisation;
timing and frequency of meetings – this will vary according to the functions and purposes of
individual bodies, so for example, a company AGM will be an annual event, but a school
governing body may meet once a term, or a finance committee may meet every six weeks.
All bodies holding meetings have a constitution of some sort. Formal committees will certainly have
a written constitution, sometimes governed by legal regulations, which spells out in detail all these
issues. However, even informal groups will have an implicit understanding of these matters –
whether they are discussed and agreed among the members or simply taken for granted.
The Organisation of Meetings
Meetings don’t just happen – they have to be organised. This can be considered in three stages:
before the meeting – the planning of what will happen;
at the meeting – the conduct of business during the course of the meeting itself; and
after the meeting – wrapping up the proceedings by producing the record of the meeting and
following up on the issues discussed and decisions made.
Interviews and Meetings 143
© Licensed to ABE
We shall review these in very general terms now, and then go on to look at specific aspects of the
procedures and documentation in the next two sections.
(a) Preparation for meetings
Meetings have to be planned. Efficient undertaking of the necessary work prior to any meeting
– whether it is for the AGM of a public company, a local government committee, or a work
group – will invariably smooth the conduct of business at the meeting itself.
The starting point is the preparation of an agenda. This is fundamental to any meeting as it sets
out, in order, the business to be transacted. It provides, then, not only the statement of what the
meeting will consider – its content – but also defines its structure.
However, prior to that, perhaps the first step is to determine if the meeting is really necessary!
Many of us will have felt the frustration of spending two or three hours in a meeting where no
progress has been made, or there was nothing of substance to discuss, or even where it was
evident that decisions had already been taken elsewhere. Meetings are an expensive way of
using staff time and effort, so they need to be cost-effective. Therefore, if it is not a required
meeting of a formal committee, its appropriateness or necessity should be questioned and
alternatives considered for achieving the desired outcomes.
(b) The conduct of business
The proceedings of a meeting may be considered as a sort of structured discussion. The
structure is partly provided by the agenda, but the way in which the discussion is conducted is
governed by rules of procedure. Again, formal bodies will have very specific rules of
procedure, usually codified and written down as standing orders, but even informal groups
will have some generally understood rules about how the meeting will be conducted.
There are a number of specific roles within all meetings. Some of these are implicitly agreed,
but more often there is a deliberate appointment to these positions – either by election, or as a
consequence of holding a particular post in the organisation. Two of these roles are particularly
important:
the chairperson; and
the committee secretary/clerk.
At the meeting itself, it is the chairperson who actually controls the meeting. This is the key
role in any meeting, setting the tone and style of the meeting and generally ensuring that the
business of the meeting is efficiently and effectively conducted. However, this role is not
simply one of a passive, neutral referee of proceedings. It is invariably a very powerful
position, giving the holder the ability to control what is discussed and how that discussion
progresses.
The secretary’s role is to ensure the effective administration of the meeting, including all work
before and after the proceedings, and to advise the meeting on the application of the rules of
business. This is a key role and, for formal committees and boards, will be fulfilled by a senior
officer of the organisation. He/she will have a close working relationship with the chairperson
to ensure that the proceedings go smoothly and the desired outcomes are achieved. In informal
meetings it is often the case that the secretary and chairperson’s role are held by the same
person.
The clerk’s role is essentially that of carrying out the work of agenda preparation and writing
the minutes, including (of necessity) taking notes of proceedings at the meeting itself. In many
smaller bodies, this work is actually carried out by the secretary.
144 Interviews and Meetings
© Licensed to ABE
It is worth pointing out that these roles – committee secretary and clerk – should not be
confused with the general office positions of secretary and clerk. They are specialised and very
important positions in relation to meetings specifically.
(c) Work after meetings
This breaks down into two areas – the preparation of the record of the meeting, and ensuring
that decisions taken at the meeting are subsequently implemented.
The particular requirements of the formal minutes of proceedings go much further than the
recording needs for most business meetings. In essence, all is required is:
a record of all essential information, particularly what has been decided;
a statement of who has to take what action.
This preserves a record of salient information and can be circulated to all participants and
others involved or interested. It is important to remember that the information must reach all
those who need to know – either for general awareness or because action is required – rather
than just those who were present. It is helpful, though, to direct the recipient’s attention to the
relevant items in what may often be very large reports or minutes.
Finally, it is worth noting that meetings exist to facilitate the execution of work. It is sometimes
tempting to think of them as talking shops which have to be serviced, but have no relevance after the
event. However, if they are to have any meaning, the discussions and decisions must be followed up
and put into effect. They then form a key participative element in the decision making and operating
processes of the organisation, rather than a distraction.
C. DOCUMENTATION FOR MEETINGS
The Agenda
The main purpose of the agenda is to set out, in order, the business to be transacted at the meeting. As
such, for formal committees and boards, it will usually be the subject of some discussion between a
number of interested parties – the committee chairperson, senior officers and the committee secretary.
For other types of meeting, preparation of the agenda may be the sole responsibility of the person who
will chair the meeting, but advice may be sought on what items of business should be included.
An agenda should normally include the following elements:
the time and place of the meeting;
apologies for absence;
provision for confirmation of the minutes of any previous meeting, and for consideration of
matters arising from them (where the issues are not included as items elsewhere on the agenda);
provision for the reporting and consideration of any correspondence received (where the issues
are not covered by items elsewhere on the agenda);
a subject heading for each item of business to be transacted, together with a brief explanatory
comment, if necessary (often by reference to attached reports, correspondence, etc.);
a final item of “any other business“ to allow for discussion of any issue which has arisen since
the production of the agenda; and
a final, final item to determine the date of the next meeting.
Interviews and Meetings 145
© Licensed to ABE
For most formal committee or board meetings, it is the job of the committee secretary (or
administrator or clerk, however the post is termed) to prepare the agenda. He/she will usually
maintain a file of items which may potentially require the committee’s attention. These items may be
derived from:
correspondence received;
matters referred by other committees, etc.;
circulars and directives from other bodies (particularly government);
matters – usually policy issues and usually in the form of “motions” – referred by members or
officers for discussion and/or resolution.
Although it is usual for items for formal committees to be submitted in writing, in practice there will
often be the need for discussion between the secretary and individual members, perhaps also with the
involvement of the chairperson, to clarify how items will be presented on the agenda.
It is important to remember that, if a meeting is to be effective in its deliberations and decision-
making, members will need time to familiarise themselves with the agenda and any supporting papers.
This means that the agenda must be sent out some time prior to the actual date of the meeting.
When exactly will vary. The required notice of business to be transacted may be formally stated in
the constitution or standing orders of some formal bodies. Local authority committees, for example,
have a statutory duty to have the agenda and relevant reports, etc., available for public perusal three
clear days before the date of the meeting.
In some organisations, notice of the meeting may be sent out separately – prior to the agenda itself. In
others, notice of the meeting and the agenda may be combined.
Agenda may appear in a variety of formats, depending on the conventions of the organisation in
question. The example in Figure 6.1 combines the notice of the meeting with the agenda, and the
agenda contains all the usual necessary elements.
You should note the following points about this example:
The headed paper gives clearly the contact number for the secretary, so that apologies for
absence can be sent, and discussion about items of urgent business can take place.
The prior notice provided by the date of dispatch of the agenda – in this case, almost four
weeks.
The date, time, and place of the meeting are clearly set out. Here, they are included in the letter
which gives notice of the meeting. If the agenda was sent on its own, this would need to be
included at the top of the agenda.
Members are specifically reminded about considering “any other business“ in advance of the
meeting.
The first four items are usually fixed for all regular meetings and generally appear in this order.
Items 7 and 8 are also fixed.
The items which form the variable subject matter of any meeting should have sufficient detail
to enable members to understand the nature of the item. Where appropriate, there should be a
reference to any relevant documentation.
146 Interviews and Meetings
© Licensed to ABE
HAMSHIRE ASSOCIATION OF PARISH COUNCILS
SALEM AREA COMMITTEE
Chairman: Mr.J .Tobey
Bragdale Farmhouse
Bragdale Road
Feversham LX53 8XY
Tel: 01878 555555
Hon Sec.: Mrs J Pride
16, High Street
Lower Allwood
Settingly LX95 7DY
Tel: 01878 888888
7 February 200X
Dear Sir/Madam,
The next meeting of the Salem Area Committee will be held on Monday
March 2nd 200X, at 7.30 pm in the Council Chamber, Salem House,
Settingly.
The agenda and supporting papers are appended. If you have items for
inclusion under “any other business“, they should be with the Secretary
no later than 5.00 pm on Friday 27 February.
Yours sincerely,
J Pride
Secretary
AGENDA
1. Apologies for absence.
2. Minutes of the last meeting.
3. Matters arising.
4. Correspondence.
5. Reports from representatives on:
(a) Police Consultative Committee
(b) Executive Committee
6. Rural Lanes Survey – Report AB/123 refers
7. Any other business.
8. Date and topic for next meeting.
Figure 6.1: Example of an agenda
Interviews and Meetings 147
© Licensed to ABE
Minutes
It is generally the case that, after any meeting, a record of what transpired at the meeting is made.
This may be in the form of a few hand-written notes, a memorandum, a note for filing or a report of
some kind, possibly with notes for action. The appropriate form will vary with the type of meeting
and the importance of what took place.
The situation with regard to formal meetings of a committee or board is rather different. The
proceedings of such meetings are recorded by the minutes.
Minutes are the factual record of the proceedings and resolutions of a meeting.
They constitute a true and impartial record of the events.
The prime function of minutes is to place on record the proceedings of a meeting as the basis for
subsequent action. The minutes constitute the authorisation for such action to be taken.
(a) The format of minutes
The way in which the events at a meeting are recorded in the minutes is likely to vary between
organisations. Each has its own particular conventions about what should be recorded and how
they are set out.
However, there are a number of general principles which can be identified.
As noted above, the primary purpose of the minutes is to provide authorisation for actions to be
taken. As such, then, the key element which must be recorded is the decisions taken at the
meeting.
This may be done by simply stating the motions passed by the meeting, using the exact words
of the motions as voted on. For example:
Resolved: That the Treasurer’s Report (ref. FD.045) be adopted, subject to the
assumed Government funding becoming available for development of the new site
by the end of the financial year.
This may mask considerable debate about the issue, including the proposing of, and voting on,
various motions and amendments. However, at the simplest level, the only important point is
the final decision at which the meeting arrived.
Whilst this is the essential element of minutes, it is often the case that they need to go further
than this in order to accurately convey the sense and meaning of a meeting. Indeed, this may be
necessary since, in the event of a dispute as to what transpired or was agreed, the minutes may
be cited as legal evidence.
Thus, it is quite possible that the minutes will record all motions and amendments put to the
meeting (with their proposer and seconder), together with brief details of discussion and the
subsequent vote. It is also sometimes necessary to record details about the voting on particular
motions – either as totals “for“ and “against“, with abstentions, or even the way individual
members voted.
Finally, in addition to decisions taken by the meeting, it is normal for the minutes to record
events in respect of each item on the agenda, including:
those members present, together with absences for which apologies were made at the
time;
agreement about the minutes of the previous meeting(s), together with any changes made
to them;
148 Interviews and Meetings
© Licensed to ABE
brief notes about items or issues introduced to the meeting, but not specifically referred
to on the agenda or supporting papers – as in the case of reports or discussion about
matters arising from the previous minutes, correspondence and any other business;
the start and finish times.
(b) Minute writing
The production of clear and accurate minutes is an exercise requiring many of the
communication skills we have considered previously. It is important to listen effectively and
consistently, to take accurate notes, and then to translate these into a coherent and
comprehensible written statement.
There are a number of points of good practice in minute writing, as follows.
The essence of minutes is that they are a brief note – i.e. a condensed statement – of the
proceedings at a meeting. As such, they are not the same as a report. They are designed,
basically, to record the decisions taken, and that is all. On the other hand, they need to be
sufficiently detailed and complete to convey what transpired at the meeting and to
provide clear instructions and authorisations for action.
Where it is accepted practice that minutes should record, in some detail, the discussions
which take place, this should not become unwieldy and over-long. It should not obscure
the central point about the decisions made.
The minutes – as a whole and in each individual statement – should be positive, free
from ambiguity and capable of standing on their own. For example, resolutions should
not merely say “resolved accordingly“ or “resolved as agreed“, but state precisely what
the decision was, using the exact wording on which voting took place.
Minute writing requires accurate and concise language, involving objectivity and the
absence of ambiguity. The minutes should be written in third person – i.e. using
“he/she“, “they“, “them“, etc. – and in the past tense.
It is important to emphasise the word “factual“ in the definition above. Minutes must not
express opinions or give interpretations of what has been said. They should be simple
statement of fact. Thus, it would be wrong to write:
“The Treasurer displayed such excellent persuasive skill in putting forward
her argument that she took all the members with her.“
This should be expressed as:
“There was unanimous agreement to accept the Treasurer’s report.“
Minutes should be completed as soon as possible after the meeting. It is surprising how
quickly your understanding of your own notes can fade, and your memory of a certain
discussion grow cloudy.
It is normal practice in many organisations for the accuracy of the minutes to be checked
with the chairperson before circulation.
The following example (Figure 6.2) of an extract from the minutes of a meeting illustrates
many of the points made above.
Interviews and Meetings 149
© Licensed to ABE
SALEM PARISH COUNCIL
GENERAL PURPOSES COMMITTEE
Minutes of the meeting held on 9 J anuary 200X, between 7.00 pm and 9.00
pm in the Assembly Room at Salem House
1. Members present: Councillor Green (in the chair); Councillors
Brown, Black, Cyan, Grey, Maroon, Purple, Red, Tan and White.
2. Apologies were received from Councillor J ones
3. The minutes of the meeting held on 12 December 200V were
approved and signed as a true record.
4. Pay rise
After a full discussion, it was proposed by Cllr. Red and seconded by
Cllr. White that the opinions of all employees be sought by means of a
questionnaire. An amendment that the questionnaire should also ask
if employees would prefer a one-off or staged arrangement was
proposed by Cllr. Cyan and seconded by Cllr. Black. This was passed
by six votes to three, and the motion that the questionnaire be
produced and circulated was then passed unanimously.
Figure 6.2: Example of minutes (extract)
D. PROCEDURE IN MEETINGS
The proceedings of a meeting may be considered as a sort of structured discussion. The issues for
discussion, and their order, are structured by the agenda, but the way in which the discussion itself and
general interaction of the participants is conducted is structured by the various rules of procedure.
Constitution and Standing Orders
The proceedings of any formal meeting are generally governed by the constitution of the committee or
board, etc. – which states what it is allowed to do – and written rules of procedure, usually known as
standing orders. The constitution and procedural rules of some bodies are governed by legal
regulations, which may lay down specific requirements.
The constitution of the body, as we have seen, is fundamental, in that it defines the terms of reference
of any meeting and, thus, conditions what powers and duties may or must be exercised. The
constitution also sets out the framework of meetings in terms of their timing and frequency and also,
possibly, the establishment of certain roles.
Standing orders are concerned specifically with the way in which meetings are run. These rules are
essential if meetings are to be conducted properly since they cover such matters as:
the number of members who must be present in order for the meeting and its decisions to be
valid (the quorum);
how and when questions may be put;
150 Interviews and Meetings
© Licensed to ABE
how motions and amendments may be moved;
the length of debates;
the methods of voting;
control over the behaviour of members.
Here we have a very clear example of the inter-relationship between the written and spoken word.
Written standing orders exist to promote the effectiveness of oral communication.
Roles Within Meetings
As we have seen, there are a number of specific roles within all meetings.
At the meeting itself, it is the chairperson who actually controls the proceedings. This is the key role
in any meeting, setting its tone and style and generally ensuring that the business of the meeting is
efficiently and effectively conducted.
His/her role can be summarised as being:
to ensure that the meeting is properly constituted and that there is a quorum;
to control the meeting in accordance with the standing orders and any other legal requirements
that apply;
to take the business in the order that it appears on the agenda (unless the committee determines
otherwise), by opening the discussion and guiding the debate such that all those who wish to
speak may do so;
to ascertain the sense of the meeting at the conclusion of the discussion on an item (by reaching
common agreement or by voting on a specific motion) and ensure that the decision reached is
properly recorded.
In all these matters, the chairperson is assisted by the committee secretary. This is certainly not the
same as an office secretary. He/she is likely to be a senior officer in the organisation and will be
responsible for:
advance notice of the meeting, agenda preparation, and general housekeeping and
administration (room bookings, resources required), etc.;
advising on the application of standing orders and any legal matters (such as statutory
provisions and common law requirements) during the course of the meeting;
recording the proceedings accurately, distributing the minutes and following-up any decisions
after the meeting.
In many meetings, the secretary is not a formal member of the body itself and, therefore, has no
voting rights or any formal role in discussions. However, as a senior officer, his/her contribution is
likely to be sought (or provided) on the issues involved in agenda items and the implications of
proposals and decisions.
General Rules of Procedure
All members have a general responsibility to participate actively in the proceedings of the body. This
requires a commitment to the work of the committee and careful preparation by all concerned so that
each member is knowledgeable about the topics under discussion.
Interviews and Meetings 151
© Licensed to ABE
It also means that each member has a responsibility to other members to allow contributions to be
heard and to enable discussion to flow freely and positively. Thus, order is not just the responsibility
of the chairperson – it resides in all participants!
In order to ensure that chaos does not reign, there are a number of conventions – general rules of
behaviour – which need to be followed, including:
acknowledging that the chairperson is in charge;
speaking through the chair – waiting for permission to speak, and always addressing remarks to
the chairperson, not directly to other members (although this may not be so necessary in less
formal, smaller meetings);
keeping to the point – avoiding digression or pursuing one’s own particular agenda to the
detriment of consideration of the items before the meeting;
interrupting other speakers only for procedural reasons – for example, to seek clarification
through a “point of order” or to seek to give a “point of information”.
Obviously, the degree of regulation of formal committee or board meetings is far in excess of that
applying to most other types of meeting. However, the principles discussed here apply to all
meetings. There will always be some formal or informal rules about what the meeting is competent
either to discuss or to decide, and how it should go about it. Such rules may be extant and clear to all
participants (or may be clarified in the course of the meeting), or they may need to be considered and
determined during its course – as may be the case with informal meetings of work groups. There will
always be a chairperson with a role to ensure the proper conduct of the meeting in accordance with
the points outlined above. And there will always be someone responsible for planning the meeting
and recording the proceedings.
Effectiveness in Meetings
Let us now take a little more time to consider how these general rules and conventions actually apply
within meetings. Although the procedures followed for meetings and committees will vary from one
organisation to another, the existence of these “rules”, in whatever form, will go a long way towards
ensuring that the business is conducted in a coherent and professional way, using time and resources
efficiently, and minimising the risk of personality clashes which would be counter-productive.
As a structured interaction, meetings can be held to conform to the same basic principles as any other
form of structured communication – they need to be properly planned and should have a beginning, a
middle and an end.
(a) Planning
We have seen that the start point for any meeting is the preparation of the agenda and its
circulation to members. However, whilst this sets out the structure of items for discussion, it
does not constitute a detailed plan for the way in which the meeting may go. As with all forms
of interaction, it is advisable to prepare carefully beforehand – considering the objectives of the
interaction, the participants involved and the information required.
Accordingly, before the meeting itself, there is invariably some kind of prior consideration of
the agenda by the chairperson, together with the secretary and, possibly, other officers. This
will concentrate on identifying the various issues involved in each item of business, together
with any desired outcome. This process of considering how best to handle the discussion and to
achieve objectives is always useful for any type of meeting. Time for most meetings is likely to
be restricted, so it is essential that there is clarity about what needs to be covered, and the best
152 Interviews and Meetings
© Licensed to ABE
way of achieving it. These pre-meeting briefings do not, however, take decisions about the
outcomes of agenda items.
(b) Opening the meeting
The introductory phase of any meeting should outline the business to be conducted and set the
proceedings in the context of previous meetings, as well as covering any particular
administrative arrangements (such as time constraints, etc.). This is very much the
responsibility of the chairperson.
The chairperson will first call the meeting to order, to ensure that everyone present is giving full
attention, and will formally declare the meeting open, usually stating the time of the start of
business. A check may be made that everyone has received the agenda and any supporting
papers, and is clear about the business to be conducted and any administrative arrangements.
The first agenda item to be taken will be “Apologies for absence” to establish a formal record
of attendance. Apologies are normally read out by the secretary and will be recorded in the
minutes.
The minutes of the last meeting need to be approved as a true and accurate record, and signed
by the chairperson. At this stage, the responsibility lies with every member to have checked the
minutes, and to be prepared to speak up to correct any inaccuracies. This is of particular
importance if the minutes have legal significance. Adjustments can then be made before the
minutes are signed.
It is likely that action will have been taken on the basis of decisions made at the previous
meeting, or that there will be issues arising from the discussion then which need clarification in
the light of present circumstances. The opportunity to consider such matters, where they are
not specifically covered elsewhere on the agenda, is provided by the agenda item “Matters
arising from the minutes”. The chairperson him/herself, or any other member, may seek
information, usually from the secretary, in order to complete the picture presented by the
minutes. The chairperson needs to ensure that there is no duplication here – the purpose is not
to go over old ground, but merely to clarify any issues arising subsequently. Even if certain
members were not present at the original discussion, the temptation to allow them to ask a lot of
questions should be resisted!
(c) Main business of the meeting
Having completed the introductory phase, the meeting can move on to the substantive business
before it, according to the agenda.
Discussion of each item generally follows a set pattern – again reflecting the beginning, middle
and end structure we have seen in all forms of communication.
Introduction to the item
This will be done by the chairperson, one of the members, or an officer or other person
attending specifically to provide information about the particular item. The intention is
to focus attention on the key issues about the subject, in order to direct the following
discussion.
It is often the case that agenda items are supported by reports or other documents which
provide background information. It is customary for the report’s author to introduce it by
means of a short presentation. The requirements of this are the same as have been
covered extensively above – careful and detailed preparation and delivery. It is not
appropriate to read verbatim from the report or other paper(s), and the level of detail does
Interviews and Meetings 153
© Licensed to ABE
not need to be that great where the material has been circulated in advance. Rather, the
introduction should concentrate on the key issues and pick out specific points, expanding
and clarifying them as necessary, on which the discussion should focus.
Discussion of the item by members
It is likely that a good many members of the meeting will have points to make in respect
of the issue under consideration. The purpose of the procedural rules is to facilitate them
doing so, such that they can put their thoughts to the meeting and have them heard and
considered. This requires some degree of formality and order to the discussion.
It is the chairperson’s duty to take control and impose such order. Normally, all
comments should be addressed through the chairperson. This means that individual
members do not address each other directly and get involved in personal, potentially
acrimonious, debates across the meeting. It also helps to ensure that only one person is
speaking at a time. In order to make a contribution to the discussion, members need to
attract the attention of the chairperson and signal their desire to speak. This, in turn,
means that the chairperson must be aware of members’ intentions at all times. The power
to bring individual members into the discussion can allow the chairperson to exercise
considerable control over the discussion, and it should, therefore, be exercised fairly and
even-handedly. It can be a source of friction where members feel excluded, particularly
if their views are opposed to the chairperson’s.
As a sanction to maintain order in the face of members flouting the rules and conventions
of discussion, the chairperson has the power explicitly to exclude individuals from
speaking – ruling their contribution “out of order” – or even to banish them from the
meeting.
Discussion of many items in formal meetings often takes place around specified
proposals to be adopted as decisions of the meeting. We shall consider the details of this
below.
Conclusion of the discussion by means of taking a decision
The purpose of discussing a particular item is to come to some sort of conclusion about it
which reflects the views of the meeting. This may take the form of adopting a specific
decision, or it may simply be a matter of the chairperson summarising the key points of
agreement. However, even such a summary constitutes a decision of sorts in that it is
likely to form the basis of further action, sanctioned by the meeting.
Formal decisions taken within a meeting need to be based on a motion proposed by one
member and supported (“seconded”) by another member. Such motions may be simply
to adopt the recommendations set out in a report, or they may be detailed suggested
courses of action put forward at the time by a member (including the chairperson), based
either on a perceived consensus of opinion at the meeting, or their own particular
viewpoint.
The wording of a motion can be very important, as it may establish policy or commit
resources. They need, therefore, to be clear and unambiguous. For example, the
following would meet this requirement:
“That the committee authorise the expenditure of £5,000 to G. Gnomes &
Co. to carry out landscaping work on the HQ grounds in accordance with
the proposals made in their tender document.”
154 Interviews and Meetings
© Licensed to ABE
On a motion being put to the meeting, and following appropriate discussion, the
chairperson will take a vote among those present as to whether it should be agreed and
become a decision of the body. The rules about voting are normally set out in the
standing orders, and they are likely to include provision for the chairperson’s “casting
vote” – a second vote available for the chairperson to use in the event of a tie between
those for and those against the motion.
It is open for any member to put forward amendments to a motion. An amendment is a
suggested change in the wording which will alter, to some degree, the meaning of the
proposal. Amendments which negate the intention of the original motion are not allowed
– the same effect may be had by simply voting against it. So, for example, the following
amendment to the above motion would be acceptable:
that the additional sentence “Payment to be made in two equal instalments,
based on completion of works on the front and rear of the premises.” be
inserted at the end of the proposal.
However, the following amendment would be ruled out of order:
that the word “not” be inserted before the word “authorise”.
Any amendments also need to have a formal proposer and seconder, and should be voted
on before the initial motion, so that, if carried, the revised motion can then be considered
and voted on.
All decisions made by a meeting need to be recorded precisely by the committee
secretary and included in the minutes.
Conclusion of the meeting
The final phase of the meeting is entered when all the substantive items on the agenda
have been considered.
There is always an item of “Any other business” on the agenda in which members can
raise issues of significance which are not covered elsewhere. Sometimes, this is put on
the agenda as “Any other urgent business”, and this is really the key to this item. It is
not intended that important and substantial new business should be brought up at this
stage of the proceedings. Members should usually clarify with the secretary or the
chairperson in advance if they have items they wish to raise here, and the chairperson
may need to take a decision about what can and cannot be accepted, perhaps suggesting a
full discussion at the next meeting instead.
The last element is to agree the date and time of the next meeting, after which the
chairperson declares the meeting closed, noting the exact time of closure.
155
© Licensed to ABE
Study Unit 7
Electronic Communication Systems
Contents Page
Introduction 156
A. Modes of Communication 156
Non-Electronic Communication 156
Electronic Communication 157
B. The Internet 159
Background 159
Operations 161
Electronic Mail (e-mail) 164
Videoconferencing 165
C. The Use of IT in Business 166
Workgroup Computing 167
Bulletin Boards 168
Commercial Services 169
The World Wide Web (WWW) 169
D. Input Devices 170
Keyboard 171
Pointer Input 172
Scanners 172
E. Output Devices 173
The Monitor 173
Printers 173
Human Computer Interaction, HCI 174
156 Electronic Communication Systems
© Licensed to ABE study.
Electronic Communication Systems 157
© Licensed to ABE
Letters
This traditional method of getting information to people without being in the same place at the same
time is also the slowest form of communication and is only really suited to formal communication
such as initial introductions, contracts and specifications. Letter formats have little to offer very fast
electronic communication.
Memos
This means of communication allows people to get basic information to others within organisations.
The assumption is that the recipient will understand the full context. Nowadays, memos have been
replaced by email (electronic mail).
A forerunner of email, it is just a method of sending a hard (paper) copy of some document over the
telephone. It allows letter type communication without the built-in delay of carrying the specific
piece of paper from the communicator to the recipient. You could include fax communication within
the section on electronic communication as fax does depend on computing facilities although it is an
older form of communication. The original document needs to be read electronically and it is the
electronic version that is transmitted over the telephone system. At the receiving end, the electronic
document is printed onto paper before becoming accessible to the recipient.
Electronic Communication
Electronic communication is the basis of our Information Society as it gives everyone ready and easy
access to vast quantities of information.
There are several forms of electronic communication, but they all involve the conversion of the
information to a format suitable for transmission over a particular medium. No matter which format
the original information is in, be it on paper as words or graphics, or be it spoken, it is converted, by a
computer, to the binary form of 1s and 0s. It is digitalised. It is not necessary for you to understand
exactly how this is done or even what it means, but you should be aware that computers use
digitalised data consisting of groups of 1s and 0s representing the two states of off and on, of any
electrical circuit.
We are familiar with the normal undulating wave format of sound, light and radio. This is known as
the analogue format. The digitalised wave format consists of discrete values so that the waveform
appears in a square format.
Figure 7.1
Electronic communication relies on a communications infrastructure consisting of telephone lines,
fibre-optic and other types of cable, microwave and radio links, satellite links and computer networks,
which we call the communications medium.
If the information is being transmitted over the traditional telephone system it will first be converted
back to analogue form, as this is the form the telephone system was originally designed to handle.
Speech is in analogue form. If it is to be transmitted through modern fibre optic cables, it will be
converted to light waves. And, of course, radio involves radio waves. We will refer to these format
changes as coding.
158 Electronic Communication Systems
© Licensed to ABE
It is then a relatively straightforward process to transmit the data from computer to computer. The
first machine codes the information into the required format and the second reassembles it into the
form we wish to view it.
Figure 7.2
The main problem in the above scenario is the interference of the transmission noise. This is anything
that interrupts or distorts the signal. Allowance must be made to check for this and to correct any
distortions. If, at any time, you have attempted to connect your computer to a computer network via
the telephone system you will have heard a series of sounds. These are the computers ‘speaking’ to
each other. Typically you will hear something such as:
Whatever communications medium we are using, it provides a communications channel for the
transmission. The capacity of the channel depends upon its bandwidth. This is just a measure of
how much data the channel can carry. Coaxial (TV style) cable has the lowest bandwidth whilst fibre-
optic cable has the highest.
We must not confuse bandwidth with speed of transmission. They are related, but not necessarily
directly. The speed of transmission will depend directly on the amount of data being sent through the
channel. The more informative we transmit, the slower it travels as the channel becomes congested.
On the other hand, with a greater bandwidth, the channel is less likely to become congested. At the
other end of the scale, if only small amounts of data are being transmitted, they can travel equally fast
over a narrow bandwidth as congestion is not an issue. The usual metaphor used here is an airport
carousel. Its moving speed (bandwidth) remains constant. If the aircraft is half full, your bags appear
sooner and possible all together! If the aircraft a full 747, the bags will be all jumbled up and can take
a long time to appear.
The communications medium will always allow information to be transmitted in both directions. This
then leads to problems in co-ordinating the two-way communication link so that messages in one
direction do not interfere with messages in the other. You need to be familiar with the following terms
as you will certainly come across them.
Simplex communication: only travels in one direction (i.e. a radio transmitter).
Half-duplex communication: allows transmission in both directions, but only one at a time.
Information Source
encode decode
Information receiver
Transmission noise
Translation
Beeeeep are you there?
Peeeeep yes, I’m here
Chuuusssh I’m sending a message
Burrrrr not understood
Whaaaan do you understand this? Noise interference here
Zzzhuussst too fast for me!
Burrrzzzzz what about this?
Chirp OK, go ahead.
Electronic Communication Systems 159
© Licensed to ABE
Full-duplex (or just duplex) communication: allows transmission in two directions
simultaneously. The telephone system uses this system and so do computers.
It follows that any system we are interested in will be full duplex. This then leads to another problem
- how to maintain a separation of the messages.
Synchronous transmissions are co-ordinated by transmitted data being sent at a fixed rate and
the received data arriving at the same fixed rate. Each message is then recognised as it all
arrives at this specific rate. Internal computer communication is made this way.
Asynchronous transmissions use a recognised marker at the start of the message and another
at the end. This is the method used in computer to computer communication.
Parallel transmissions involve breaking the message into separate chunks, which are then sent
by different routes to the receiver where the chunks are reassembled into the message. This
technique is fast and is used between the computer and its printer or a network.
Finally in this section, we will look at way in which telephone companies are meeting the demand for
more transmission capacity.
The first requirement is for a dedicated or leased line. This is just a permanent connection
between two points in contrast to the normal telephone system, which routes the connection
through a dial-up switching telephone exchange. A dedicated line is clearly more reliable and
the connection, considerably faster. There is also much higher security for the information.
In conjunction with the dedicated line, the service will offer ISDN (integrated Services Digital
Network) transmission. ISDN is also available over normal dial-up facility. As its name
suggests, ISDN enables the information to be transmitted in digital format. Not only does this
cut out the need for encoding the information before transmission, it also offers greatly
enhanced transmission speed and accuracy.
B. THE INTERNET
Background
You may ask: ‘What is the Internet?’ In reality, it is nothing more than an enormous network of
computer networks. It is thousands of computers connected together.
The Internet originated with the United States military and their fear of nuclear attack following the
Soviet Union’s launch of Sputnik, the first satellite, in 1957. To protect vital communications within
the university based technical and research facilities of the Department of Defence, four universities
in the US west (Stanford University, UC in Los Angeles and Santa Barbara and the University of
Utah) were connected together via a dedicated line. By 1969, four other US networks were connected
in so was born the internet. Once connections were expanded into the normal telephone dial-up
system, it became possible to bring in computers across the world. Local comparable set-ups were
developed in many places and whole groups of computers were connected into the system. It did not
take long before we reached the stage that we now know in which the Internet stretches to every part
of the world and, using cell or mobile phones, to places remote from the actual computer.
The basic component of the Internet is a computer network. At this stage, there are two types of
network of interest to us. We will introduce two more later in the section:
1. A LAN (Local Area Network) is, as you would expect, a group of computers, which are
geographically close to each other, connected together. Typically, computers within a business or
part of a business will be connected in a LAN.
160 Electronic Communication Systems
© Licensed to ABE
There are two principal ways (or protocols) in which data is transmitted around a LAN:
The Ethernet standard requires the sending computer to first check whether the network is
busy or not. If it is not, the packet of data (we shall define a packet later) being sent is
despatched to every computer in the LAN, but only the computer to which it is addressed
will take receipt of it. Others just ignore it. If the network is busy, or if two computers send
out a data packet at the same time causing a collision, then the sending computers wait a
random amount of time and try again.
Figure 7.3
The token ring standard involves signals or tokens continuously travelling around the
network (see Figure 7.4). The sending computer waits until a token is passing by and, if the
token is not already carrying a data packet, attaches the data packet it wants to send, to the
token. As the token passes each of the other computers, each checks the token and the
address of any attached packet. If it is addressed to that computer the packet is accepted and
the token is then free to accept another packet.
Figure 7.4
The next point we need to consider is how the data is actually sent. As some of the messages can be
very large, such as a video or other multimedia message, to send the message intact would clog up the
whole network. We have only to think of a very large load travelling up a motorway. The police
escorting the load require everyone else using the motorway to wait behind, much to their frustration.
It would be the same across the network if entire messages were sent intact. Instead, the message is
divided up into sections called packets. Each packet is given the destination address of the whole
message and any other information necessary such as the sender’s address. The packets are then sent
out individually. If alternative routes are available, then each packet will take whichever route is
available and convenient. When all the packets for the message have arrived at their destination, and
they need not arrive in order, the message is reassembled.
11
22 33
44
55
55
sender Not mine Not mine Not mine mine
Token for 33
Free token
Waiting packet
11
44
22
33
Electronic Communication Systems 161
© Licensed to ABE
The complete message individual packets The complete message
Packets sent by separate routes the message is reassembled
2. A WAN (Wide Area Network) is more or less the same as a LAN except the geographical
restriction does not apply. A packet switching protocol, as for a LAN, is used in the same way.
A WAN will probably consist of several LANs connected together. To co-ordinate the delivery of
resources across the WAN, a server machine will be used. A server is a computer wholly
dedicated to a specific task. There are several different tasks that servers provide:
Some will store resources such as files and application software which they can then serve,
on demand, to the various computers within the WAN. In those kinds of systems, the
individual computers do the processing, the server simply holds the files.
With application servers, the server does the processing on behalf of the client computers.
It will be provide with more powerful processing facilities in order to do this.
In some other cases, the server is in charge of the routing of the messages around the WAN.
Servers can fulfil a number of different tasks within the network, but the common feature is that they
are all accessible from the individual computers and they provide some kind of service on behalf of
individual computers.
The Internet will rank as the world’s largest WAN! However, the Internet lacks the control and
cohesiveness of a WAN. At the level of the Internet, however, much more than simple servers are
required.
Operations
Now we will have a look at the Internet itself and how it works. As we have already seen, it is a
network of networks of computers.
The following illustration of a segment of the Internet, shows that, as well as various LANs
connecting together, there is a central connection known as the backbone. This is a connection
specially designed to move information around the Internet at very high speeds and it connects all the
principal servers on the Internet.
A
A
A
B
B
B
C
C
C
D
D
D
162 Electronic Communication Systems
© Licensed to ABE
Key = Internet server = LAN or WAN computer
Figure 7.6
We have already discussed the packet switching protocol used to move information around networks.
In the following discussion, I freely refer to messages, as that is what we are sending. But in reality,
as we have seen, the message is broken up into packets. The particular version of this protocol used
by all computers on the Internet is called TCP/IP. This stands for Transmission Control Protocol/
Internet Protocol. This is just the label given to the set of rules followed for sending messages across
the Internet.
The address of anything on the Internet is known as a Uniform Resource Locator (URL). Both email
and web addresses are known as URLs. The crucial part of any URL is the domain. This identifies
the computer at the receiving end of the transmission. For instance, the domain or destination address
is given by the user with an extension such as:
name.com,
name.co.uk,
name.edu,
name.ac.uk,
name.gov.uk.
If there is no country extension such as uk, fr, de, ir etc, then the address is registered in the United
States.
backbone
Electronic Communication Systems 163
© Licensed to ABE
The first thing the computer does is convert the address that we type in, into a unique IP number.
(You will sometimes see the IP number used in the address, especially in error messages). All
such addresses are held on domain name servers or DNS server. These servers hold groups of
addresses in the dot.com style. For instance, a DNS may hold all the .gov.uk addresses of the
UK Government.
Whenever a message is sent to such an address, the name server used by the sender’s computer
(the ISP’s computer referred to below) will consult the .gov.uk DNS for the IP address required.
Each network has at least one router connected to its own network and to one adjoining.
A sent message first goes to the router, which then determines the path the message should
follow across the Internet. The message is first directed to the backbone, and then is sent at high
speed across the backbone to the point closest to the ISP computer. From there it goes to the ISP
and then on to the designated recipient.
Frequently used paths are held in store by the router to save time.
If the path to the address is not known, the message is passed to a higher level router, and so on.
The success of the Internet is due to its ability to reroute the path followed by a message should the
normal or obvious path be unavailable for any reason. Messages can even be stored for a short time
until a path becomes available.
Individual users gain access to the Internet via an Internet Service Provider (ISP). This is a
specialist company that provides a host computer into which the user can dial and make a connection
with their own computer. At this point the user will be requested for a user name and a password,
both of which having been registered on making the agreement with the ISP. Once these are checked
and accepted, a full connection is made with the ISP computer and the user’s computer becomes part
of the Internet for as long as it remains dialled in.
Now we return to the final two types of network referred to some pages ago.
1. An intranet is a closed network which uses the TCP/IP packet switching protocol and whose
visible pages will look just like Web pages. The network is, however, only accessible by those
with authorisation, typically within one organisation. In other words, it is like a private mini
Internet.
2. An extranet is a secure extension to an intranet that has a constantly open link to persons outside
of the Intranet authorisation. These are likely to be customers, suppliers, trading partners and so
on. Of course, an extranet will not give access to the whole of the intranet.
Intranets are developing extremely quickly as businesses realise their potential. Basically, where a
business has operated a LAN, by the addition of web servers, it can readily be turned into an Intranet.
By creating a common interface across the internal network in this way, there is a possibility of all
kinds of uses. Typically these will include: -
pages of company, product and market information;
on-line conferences and discussion points;
bulletin boards, which we discuss later;
and, through a connection to the Internet, all that is available there.
Should the intranet be connected to the Internet, and most are, a secure interface is required. This will
prevent outside unauthorised access to the intranet and the import of certain web pages into the
164 Electronic Communication Systems
© Licensed to ABE
intranet. A ‘firewall’ is used to provide the secure interface. This is special software designed for this
purpose, as its name implies. Most large organisations use the Internet to provide the communication
connections between their various site centred intranets and so firewalls are used to protect the
intranets (see Figure 8.7).
The company intranet firewall software the Internet
Figure 7.7
There must be no other external connection other than through the firewall. Not only does the
firewall protect the company networks from outside threats, it also allows the company to monitor all
communications between the internal and external networks.
Electronic Mail (e-mail)
e-mail or electronic mail has become common place in recent years. It is simply correspondence
between two or more users over a network. Where the network is a LAN, WAN or intranet, the
network is tightly controlled and the email correspondence will be virtually direct. E-mail is also sent
over the Internet using a version of the TCP/IP protocol for addressing. This will then involve the
services of an ISP and their router.
When an e-mail message arrives at its destination server, it is stored in an area of that server which the
user calls their mailbox. It will wait there until the actual recipient logs into their ISP’s e-mail
system. There are two types of system used for mailboxes:
Messages can be retrieved to the users’ own computer where they can be opened, read,
edited and so on.
Messages remain on the ISP’s server and the user opens and reads them there. This
method has the advantage of making the mailbox accessible from any computer when the
correct user name and password are entered.
An e-mail address or URL has the form:
My-name @ my-ISP.com
first part second part extension
The first part of the address is the user name. The @ symbol is just a separator. The second part of
the address is the name of the ISP server to which the user is registered. It has a unique IP number.
The final part of the address is the domain name that designates the DNS server holding the address
Electronic Communication Systems 165
© Licensed to ABE
over the Internet. As we saw previously, this means the message will be forwarded to a server on the
Internet backbone and then by any available route over the backbone to the nearest point to the
ISP server. It is then directed to the ISP server and to the recipient’s mailbox at that server..
A very realistic solution is to make the connection using ISDN technology. It is economical and gives
high-quality videoconferencing. ISDN works over the normal phone lines and provides enough
bandwidth for smooth audio and video transmission. This is typically 15-30 frames per second. In
contrast, an Internet-based connection has to share bandwidth with other Internet data and this can
cause some loss of audio and produce a jerky video.
Videoconferencing connections may be limited to a closed network such as a LAN or they may use
dial-up phone links.
It is the way in which these two systems transmit the data that marks out the difference between
videoconferencing systems.
ISDN has most of the advantages:
It adheres to standards, so systems created by different vendors can still connect together.
It works over regular phone lines, so no special wiring is necessary.
Once a connection is made, the bandwidth is available and the quality is predictable.
In most systems, bandwidth can be extended by increasing the number of ISDN lines.
On the other hand, it is even more inexpensive to use the Internet. As always, it comes down to
making a choice based on the way the videoconferencing is used. If it is just to make brief phone
calls, then the Internet is fine. But if a number of people are involved in a technical conference, then
ISDN technology will be best. Only in the biggest organisations will a satellite connection be
feasible.
Videoconferencing over normal phone lines requires a piece of equipment called a codec (short for
coder-decoder). The codec takes the analogue video signal, digitises it and then compresses it. The
codec also has to decode the received transmission, and this can take its toll on the video and sound
quality. The most obvious consequence of a slow codec or low-bandwidth connection is a jerky
picture and an audio time delay.
As you will have noted, I have mentioned that the signal is compressed. The reason is simply that
without compression, a digitalised video requires far too much storage. In fact it would require a
large computer to store and play a full-length feature film without compressing the size of the file.
This is achieved by losing some of the data. For instance, as we noted above, the normal video frame
166 Electronic Communication Systems
© Licensed to ABE
rate is about 30 frames per second. Whilst more than this is required for television quality, a lesser
rate would take less storage. This is where the jerkiness comes from.
Another, more satisfactory, technique is to only store any changes from one frame to another. For
instance, a video of a person talking will have a fairly static background. It is therefore not necessary
to transmit the background with every frame. Even more can be achieved in such a case as it is likely
that only the person’s mouth and eyes move to any great extent. Not even all the person’s face
features need be transmitted with every frame. All of this allows a great deal of compression to be
achieved without significant loss to the picture. Another technique is just to reduce the size of the
displayed picture!
With audio, other compression techniques are used. The basic technique here is to take a cross-
section sample of the signal at regular intervals. The number of such samples obviously affects the
play-back quality. Low quality systems use about 8000 samples per second, whereas music quality
take about 44000 samples per second. More than this is not practical for the normal PC computer..
(a).
(b) It has also been found to heighten the motivation of learners.
(c) It will improve the participant’s communication and presentation skills as each participant is very
aware of the person at the other end.
(d) It Increases Connections with the Outside World, especially where a live visit is not possible
except on rare occasions. Videoconferencing is usually easier than visiting, so communications
can be more frequent, saving time and resources.
C. THE USE OF IT IN BUSINESS
In this section we will look at some specific ways in which the modes of electronic communication
can help in business situations, and how working practices are changing as a result.
Telecommuting
In the Middle Ages, people mostly worked from their homes in cottage industries of one type or
another. With the advent of the Industrial Revolution, people were drawn into the cities and factories.
These factories were able to use steam power to drive many machines simultaneously, thus hastening
the end of the cottage industries. For about one hundred and fifty years or so, everyone lived close to
the factory or coalmine that they worked in. Then, with increased prosperity, families moved to the
outskirts of the cities, to the suburbs and back into the country areas. This brought about the need to
Electronic Communication Systems 167
© Licensed to ABE
commute to the cities where the work was. At the same time, the cost of maintaining an office or
other facilities in city centres escalated.
Computing facilities have developed to such an extent that network technology can be used to take the
work back out the people in the country and so reduce the considerable costs and time involved in
maintaining central facilities and travelling. In other words, cottage industry has, to some extent, been
re-established.
The benefits to the company are considerable:
There are lower costs in office and infrastructure.
There is less absenteeism.
Generally productivity will increase.
For individuals there are also benefits:
time saving through avoiding commuting;
a better quality of life generally; and
lower costs in a number of areas, and tax advantages.
However, there are some problems for the individual, and ultimately, for the company:
The individuals can quickly become isolated from co-workers. They are taken out of the
‘information loop’.
It is difficult to develop a company career structure, as individuals are remote from each
other and from higher management. inter-personal skills. Network
technology also makes it possible to move the workplace out of the cities and closer to the country
living workers. This is, without doubt the growing trend, especially with the new IT industries.
Several of these remote sites can be set up, all inter-linked
168 Electronic Communication Systems
© Licensed to ABE
automatically forward the documentation throughout the group. A typical use of a workgroup
approach is the processing of a major request within the company, as illustrated in Figure 7.8.
1. The proposal is formally submitted to the departmental manager.
2. He/she forwards it to the appropriate
director
3. Who then submits it to the board members for approval.
4. Their response is fed back down the line and,
if approved
5. Implemented by the original applicant.
Workgroups need not be sited together. Because of the networks used, the group can be scattered
anywhere in the world. Of course, this will involve a network larger than a LAN. An intranet might
be most appropriate. Taken to its extreme, 24-hour global working is possible whereby part of the
group can start the project in Europe, which is then taken over during the second half of the day by
another part of the group working in Northern America. As they finish, yet another part of the group
in Asia can work on the project. Finally, the European workers return for.
Electronic Communication Systems 169
© Licensed to ABE
Commercial Services
The principal electronic commercial service that we are now all aware of is shopping .
1. There is the matter of the security of credit card details. There are several systems available to
protect against this, but, as yet, no absolutely safe one.
2. The delivery system suffers from all the weaknesses of normal trading and is subject to all the
usual delays. Again, several companies are trying to avoid these problems by having their own
delivery vehicles or dedicated contracts with specialist carriers.
Another electronic commercial service is EDI (electronic data interchange) or ‘paper ‘just
systems, the required items may even be manufactured on a just-in-time system. Such systems are
normally known as VANs or Value Added Systems as they, unsurprisingly, add value to the company.
At this stage, you should have realised that there is little difference between these just-in-time systems
and intranets. Usually we can say that a just-in-time system is a subsystem of an intranet using an
extranet.
The World Wide Web (WWW)
The World Wide Web, or WWW, or just ‘the web, is the whole collection of information pages that
can be viewed over the Internet. We can therefore differentiate between the ‘Internet’ and ‘the web’,
two terms that are often incorrectly interchanged. Whilst the Internet is the network of computers, the
hardware, the web is what we actually see on our computer screens.
We saw that the Internet had grown out of the cold war era. The web came along much later, in
March 1989 when Tim Berners-Lee proposed a hypertext system for the exchange of documents at
CERN, the physics laboratory in Geneva. In 1991, the first web browser was developed. It was
called Mosaic and this became the Netscape Navigator browser in 1994.
The web is officially described as a ‘wide-area hypermedia information network’. Most of that term
is understandable to all of us, but maybe ‘hypermedia’ needs additional explanation. It is the
electronic linking of text, sound and pictures and the ability to jump from
170 Electronic Communication Systems
© Licensed to ABE:
http:// www. myCollege. ac. uk / filename/ filename
protocol web page domain server domain group country extension extension
the domain
‘www’ tells the computer that it is a web page that is required.
the domain indicates which computer the web page request is addressed to. This will
display the ‘home’ page of the web site.
The forward slashes (//)indicate a path to the required file. The extensions are optional,
as the domain part of the address will take the user to the correct location. It is then a
matter of following the hyper links to the required file. Alternatively, by specifying the
file, the user can go direct to the specified file.
In order to access the web we need to use a web browser. This is a piece of software that runs on
your computer and enables it to connect to the Internet. There are quite a few browsers available, but
the most familiar are Microsoft Internet Explorer and Netscape Navigator. The browser gives dial-
up contact with a web search engine. This is a another piece of software which accesses an extensive
index of web sites and identifying key words within the site web page. We do tend to think of the
search engine as a computer, but it is the program that performs the index search on our behalf. Other
more well known search engines are Yahoo, Alta Vista, Excite, Look Smart, Netscape, and so on.
We can therefore access the web in two ways. Either by specifying a known URL and going straight
to the web page, or by using a search engine to search its indexes for certain words, and then display
the URLs of the locations identified. The URLs will be displayed as hyperlinks, or just links. This is
an HTML tag called an anchor. When users click the mouse over a link on a web page, the system
moves immediately to the new location specified by the URL. It need not be an actual URL that is
displayed on the web page. HTML allows a user friendly name or phrase to be displayed, but
underlying it will be the URL. This seems a suitable point at which to draw the distinction between
web pages and a web site. Basically, a web page is one displayed page, although we often need to
scroll down its full length. A web site is a collection of such pages, connected by links. Each web
site starts with a web home page. This is the introductory page to the site. It will contain a series of
links to each of the other pages in the site.
D. INPUT DEVICES
We now have two short sections on what we require for input and output to and from electronic
communication.
Electronic Communication Systems 171
© Licensed to ABE
Keyboard
This is the most familiar, and probably the most essential input device that we use.
Figure 7.9
A keyboard contains a range of numerical, alphabetical, punctuation, symbol and control keys
(Figure 7.9). When a key is pressed, an electronic signal is sent to the computer, which then responds
by displaying the character, number, symbol or mark on the screen.
As the keyboard is very familiar to us all, I shall concentrate on the main features only.
First of all, we note that the screen cursor flashes at the exact point where the typed characters
will appear. This insertion point can be moved by using either the keyboard arrow keys, or the
mouse pointer.
The main character and punctuation keys are grouped together in the largest part of the
keyboard, the typing pad. The top mark and character uppercase are obtained by pressing the
shift key at the same time. Uppercase can also be obtained via the ‘caps lock’ key, but this will
not give the upper marks on these keys. The ‘shift’ key is duplicated on each
side of the typing pad, and is sometimes shown as an arrow. There is also a
control key, labelled ‘ctrl’ on each side of this pad.
The top row of the typing pad has the has numbers 0 to 9. There are also a series of symbols on
these keys, again obtained by pressing the shift key simultaneously.
The numeric pad is to the right hand side. There are two symbols on most of these keys, and
the top numbers are only activated by pressing ‘num lock’ first. There are also the arithmetical
function keys around the side of this pad.
The central control pad has the directional arrows to move the screen insertion point, either one
space at a time, or a page at a time. The ‘home’ and ‘end’ keys will take the insertion pointer to
the corresponding part of the displayed document. However, depending on the software being
used, the ‘ctrl’ key may be required as well.
At the top of the keyboard is a row of function keys, labelled F1 to F12. Each of these
performs a special function which may depend on the software being used, but F1 generally
brings up a help facility. Others will save, highlight, format etc. What each key does will
depend upon the software used. Sometimes it is necessary to press one of the ‘ctrl’ keys at the
same time.
There are other functions available by pressing combinations of keys simultaneously. These
combinations will very much depend on the software being used, and the instruction manual
will be required to identify these. However, the most common and useful combination is
numbers,
arithmetic &
directional
esc F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12
numbers
ctrl
character and punctuation
directional keys
172 Electronic Communication Systems
© Licensed to ABE
‘ctrl’ +‘’alt’ +‘del’. This will close the currently running program and is mostly used when the
software goes wrong!
The ‘print screen’ and ‘scroll lock’ keys are not used very often with modern software.
At the top right is an escape key, ‘esc’. This will often be used to make an emergency stop of a
program.
Although we are quite familiar with the standard keyboard, we must be aware that it is our primary
input device. It is through the keyboard that we compile our electronic messages.
Pointer Input
The main pointer input device is the mouse (Figure 7.10). This was invented in the 1970s as an
intuitive manipulation device. It is generally easier to use than the keyboard for manipulation of items
on the screen as all we are expected to do is click and move the mouse.
to the computer
a mouse
Figure 7.10
As the mouse is moved across a surface, a ball underneath revolves correspondingly. This sends a
signal to the cursor, which also moves correspondingly.
There are one, two or three buttons at the front of the mouse, and by clicking these, the system will
react in specified ways. The left-hand button generally selects the items being pointed at by
highlighting them and the right hand button causes a pop-up menu to appear. The menu will have
various options depending upon what is currently being pointed at. Sometimes a double click is
required. The central button is only used for specialised purposes, and the Macintosh computer uses
only one button.
When a screen item has been selected, it can be dragged across the screen by holding down the left
hand button. It is possible to reset the mouse buttons for left handed people.
Notebook computers use a trackball, track point or touch pad for pointer input. These are more
portable than a mouse. The trackball is like an upside down mouse, and is used by directly rolling the
ball. The track point is just a rubber type ball within the keypad and is used by pushing the ball in the
required direction. It doesn’t actually move; it leans in the required direction. A touch pad is used by
touching the pad and dragging the finger across in the required directions. In each case there are
separate buttons equivalent to the mouse buttons situated at the bottom of the keypad.
Yet another pointer input device is the light pen. This is a light sensitive stylus that can be used to
write or draw directly onto a screen. It can also be used to select screen items.
Scanners
This an electronic device which converts text and pictures on paper to a digital format. These can
then be stored and displayed by a computer and be transmitted electronically between computers.
Electronic Communication Systems 173
© Licensed to ABE
a scanner
to the computer
Figure 7.11
A scanner generally works in one of two ways.
1. The main one is to scan a very bright light across the image and then digitise the reflection
obtained. This can then be stored as a file and, when required, merged with text documents.
2. The other way it can be used is as a text character reader, or optical character reader, (OCR).
This is quicker than scanning the whole image, as only the formal text will be recognised. The
digitised image is then passed to the designated word processor as a normal document file.
E. OUTPUT DEVICES
The Monitor
The computer visual display screen or monitor is, of course, the principal output medium.
Sometimes it is called the visual display unit, or VDU. More or less everything that the computer
does is presented in the first place via the screen.
Modern screens use graphic display, or bit-map display technology. This means that the screen is just
a matrix of dots or pixels. Everything displayed is made up as a pattern of these pixels. Nowadays
we are quite familiar with simple displays on notices using this concept.
Figure 7.12
Figure 7.12 shows two areas of screen made up of 20 pixels each. By selecting specific pixels I have
displayed the number 37. The greater the number of pixels in a specified area, the greater the
resolution of the image.
Printers
After the monitor, the most commonly used output medium is the printer.
174 Electronic Communication Systems
© Licensed to ABE
New
Open
Save As
Print
Figure 7.13
The paper is fed in at the top of the printer and emerges from the bottom.
Most modern PC printers are inkjet printers. These squirt black or coloured ink onto the paper
to form the image. The normal print rate of such printers is about 4 - 8 pages per minute, which
can be quite slow, but the quality is good and they are inexpensive to run.
Another common type of printer is the laser printer which uses the same technology as copying
machines. They give very high quality results at high speed but tend to be expensive when
compared to ink jet printers.
Human Computer Interaction, HCI
In connection with output, we do also need to look at the important topic of HCI. This refers to the
interaction between the computer display and the computer user. In other words, how the display is
constructed.
In earlier machines, the display was given in textual form and the peculiar language had to be learned
before the user could access the machine. All requirements were input as commands causing this to
be known as command line technology. Clearly this severely limited the range of users to those who
had the time and inclination to learn the command language of the machine. To minimise the
difficulty, menus were introduced, listing the available commands. Using the keyboard directional
keys, one would chose the appropriate command. Having selected one of the options, this often opens
up a further menu, and so on, as seen in the highlighting below
Click first on ‘file’
And then on ‘save’.
Whilst this was a considerable improvement, it was still extremely limiting, although all computers
still use them for some of the basic functions, again as illustrated above. In 1984, the Apple Lisa
computer was introduced with not only pull down menus, but also screen icons accessed via a mouse.
This was soon followed by the Apple Macintosh computer and the concept was established.
Microsoft followed with the Windows 95 software and now all computers use the principle of
windows.
Edit View Insert Format File
Save
Electronic Communication Systems 175
© Licensed to ABE
The bases of the HCI concept is that the screen interface should be:
be intuitive to use in that the icon should suggest its purpose, although a short meaningful name
is often attached;
react to selection, giving the user who clicks on an icon, the appropriate picture, name or
explanation. For instance, in Microsoft word software, the printer picture at the top of the
screen should start the print operation and not something else such as saving a file;
show that an expected effect is taking place. For instance, clicking on the icon should either
start the operation immediately or some specific operation dialogue panel should appear
requesting further action as expected.
This is best achieved by the use of icons on the screen. These are small graphical pictures that
represent program features and which convey that feature. For example, the
telephone symbol or picture or icon could be used to suggest a network dial-up
facility within the computer. Any telephone suggests dialling, and so it would be reasonable for a user
to expect that selection of this icon will dial some pre-set number of a network computer.
The use of such graphical objects gives rise to the graphical user interface or GUI (gooies). When
used in conjunction with a mouse pointer, their use is intuitive and fast. By pausing the mouse pointer
over the icon, a small dialogue box often appears to give further explanation of the purpose.
By selecting an icon and then keeping the mouse pointer depressed, the icon can be dragged across
the screen either to another position or so that it is incorporated within some other icon.
A further important concept of HCI is that of metaphors. This means that what you see on the screen
looks as much like its real world counterpart as possible. For example, a page of a document is set
out to look like a real page, and when it is printed out it still looks as it did on the screen. The
metaphors we are now all used to are drawn from the world of offices. In fact, Microsoft even call
their software Microsoft Office! We are presented with a desktop metaphor on which are arranged
document icons, telephone icons, file icons, etc. There is even a waste paper basket called the
‘recycle bin’ into which we can place any documents or programs that are no longer required. Every
so often we are invited to empty the recycle bin.
176 Electronic Communication Systems
© Licensed to ABE
177
© Licensed to ABE
Study Unit 8
IT and Presenting Information
Contents Page
Introduction 178
A. Word Processing 178
The Software 178
B. Desktop Publishing 181
C. Electronic or Web Publishing 182
178 IT and Presenting Information
© Licensed to ABE
INTRODUCTION
This study unit is wholly concerned with how we use the computer for the presentation of textual
information. We will be concentrating on the use of word processing software and need to look at
various aspects of word processing such as formatting, using typefaces, and graphics. We will also
look at the use of multimedia and the rules of direct manipulation on the screen interface. Finally we
will look at the concept of electronic publishing, including desktop publishing.
At the end of the study unit, you may be able to appreciate the value of personal computing in word
processing, desktop publishing, electronic publishing and presenting information.
A. WORD PROCESSING
Word processing is by far the most popular application on personal computers. All of us use our
computers for this purpose and, certainly in the business world, word processing is the main reason
for the phenomenal growth of personal or individual computing. There are very few offices where
typewriters are still in use, as a simple word processing computer is no more expensive and is far
more versatile.
The Software
A word processor is a piece of software. It is not a computer, although many computers are dedicated
to being used only with word processing software.
Each word processing package of software is a proprietary package and they differ greatly as a result.
However, as we would expect, they do have common features. In some of the descriptions below I
am following the style of Microsoft Word.
The ability to create a new documents of several types:
Document pages,
Letters,
Reports,
Manuscripts, and others to virtually any requirement,
An editing facility whereby text can be:
Amended by moving the mouse screen pointer directly to the point at which you wish to
edit. This can be the beginning of the particular word or section, or the end of it.
Deleted by dragging the mouse screen pointer over the word, part of a word or a whole
section to highlight it and pressing the erase arrow at the top right corner of the typing
pad, or the space bar or clicking on the scissors icon at the top of the screen.
Copied by highlighting with the mouse pointer and then either clicking on the double
page icon at the page top and which has the ‘copy’ flag which pops up when the pointer
is paused over the icon, or by right clicking the mouse and choosing the similar icon and
option in the pop-up menu.
Replaced by choosing from the very top tool bar and in succession edit & replace and
then typing into the window that appears the word or words to be replaced and what it is
IT and Presenting Information 179
© Licensed to ABE
to be replaced with. Either one occurrence of the word(s) can be replaced or some of
them or all of them by choosing the correct options presented in the menu.
Moved from one part of the document to another. To do this, first use the mouse pointer
to highlight the word or piece of text, then click on the copy icon (double page picture)
and cut icon (the scissors picture). Next move the mouse pointer to the place in the text
where the word or piece of text is to be moved to, and click on the paste icon (the
clipboard and page picture).
Move up and down the document by either using:
The up-pointing or down-pointing arrows, or
One of the ‘Page Up’ (PgUp) or Page Down (PgDn) arrows which are quicker
when moving across a longish document, or
When going to the beginning or end of a document, simultaneously press Ctrl +
Home (or End).
Moved from side to side by highlighting the required piece of text using the mouse
pointer and then clicking on the right or left arrow at the top of the page.
Saved by either:
Clicking on the ‘tv’ style icon at the top of the page, or
Choosing from the very top tool bar, and in succession, File & Save, or
Selecting File & Save As the file either does not have a name as yet or you wish a
second copy with a different name. This brings a window up onto the screen and
it is necessary to navigate through its sections in order to save the file:
(a) in the correct place,
(b) as the correct type of file; and
(c) with the chosen name.
Changed in font type and size, by selecting either the whole text if the whole document
font is to be changed, or a particular word or section of text. The whole text is chosen by
using the mouse at the very top tool bar and by clicking in succession Edit & Select All.
A particular word or text section is chosen by highlighting with the mouse the word or
piece of text whose font is to be changed. Then, in both cases, click on the little arrows
to the right of font type and size as displayed at the top of the page and from the drop
down menus make the new choices. The exercise can be repeated as often as you wish
until a suitable font is decided upon. Some care is required however, as when the font is
changed, the whole text will move one way or another as the word processor realigns the
new style text to the page. This can cause misalignments at page ends, or around
diagrams and so on.
Formatted by choosing from the very top tool bar, Format. The drop down menu
presents several options such as changing the case of the character(s), changing
paragraph settings such as the line spacings, indentations and text alignment to the left,
right or centre, or even a complete change of document style.
Numbered and bulleted either via the Format list of options if the style of bullet or
number is not yet set. In this case a window appears with a range of options and settings
from which it is necessary to make the appropriate choice. Alternatively if the style of
180 IT and Presenting Information
© Licensed to ABE
bullet or number is already set, by clicking on the appropriate icon at the top of the
document
Underlined, italicised, typed in bold by placing the mouse pointer within the word, or
by highlighting a piece of text and clicking on the appropriate button at the top of the
page. These are labelled B, I, U.
Word and grammar checked - options can be tailored to different versions of the
language (particularly English) and different grammatical requirements. There is usually
also a thesaurus.
Word counted - there is a facility to produce other statistics.
Illustrated by inserting graphs and pictures and wrapping text around in a variety of
ways.
Reused after minor editing for the new requirements.
Viewed and proof read prior to printing.
Scanned to search for the occurrences of a word or phrase.
The list of features can go on and on as modern word processing packages become more and more
sophisticated. The whole strength of word processing and its popular success is its ease of use. This
is in part due to the GUI interface used with suitable icons for most of the editing and other features.
However, it is also due to the actual features listed above. The compiler of the document can type
away happily with no thought to reaching the end of the line, capitalising the first character of a
sentence, spelling, consistent, flexible and changeable formatting or any of the hundred and one things
we need to bear in mind when typing. The software takes over that kind of responsibility, sometimes
automatically, and at other times by prompting and suggesting. For example, the spell checker
automatically detects spelling errors, and then suggests a range of correct spellings.
In Figure 8.1, a word processor has been used to:
IT and Presenting Information 181
© Licensed to ABE
Create the initial document page.
Insert a title box and a title.
Import a picture into the page.
Insert a subtitle with a special effect.
Create a two-column table in the page.
Fill in the table with a mixture of text, numbers,
characters and punctuation marks.
Number the page, using the automatic page numbering
system of the word processor. A ‘footer’ comment
was also added.
One of the most popular features of a word processor is the ability to create standard letters and a
whole host of documents that can then be constantly reused with different names etc. To help with
this there is a mail merge facility. This allows a file of names, say, to be merged with a standard
letter so that an individually named letters are produced. This is especially useful in offices for mass
mailings of promotional material.
B. DESKTOP PUBLISHING
Desktop Publishing is an advanced form of word processing. It is another software package and
publishing system designed for use on personal computers. It provides facilities to create a variety of
document types such as letters, envelopes, brochures, magazines, and so on.
There are many tools provided within the package to customise the document to give a professionally
finished publication. As well as the normal word processing facilities, there are enhanced features to
import diagrams, merge text and pictures, provide colour finishing effects, arrange the pages of a
brochure with a choice of folding styles, and many other features (Figure 8.2)
Figure 8.1
WORD PROCESSING
It shows that
we can select
a word,
highlight it
and edit it by
correcting
spelling,
deleting or
moving it
The spell
checker
automatically
corrects spelling
errors, and the
word processor
can be used to
suggest a
range of correct
spellings and
formats.
numbers 1,2,300,4000
characters @ & % $ * >
punctuation ; , / ‘ [ “ ! ?
Page 1
example document
1 ‘Courier new’ font, point 11
2 ‘Times New Roman’ font, point 9
3 underlining, italics & bold type
4
182 IT and Presenting Information
© Licensed to ABE
Figure 8.2: A brochure
Desktop publishing packages are used less often nowadays because modern sophisticated word
processing packages are incorporating many of their features, this making them redundant. However,
desktop publishing is still the best software when producing a magazine or newspaper.
C. ELECTRONIC OR WEB PUBLISHING
Electronic publishing is a fast growing field of communication. It encompasses almost everything
you will have heard of in electronic communication.
By ‘electronic publishing’ we really mean ‘web page publishing’. This is not quite the same as
‘publishing on the web’, although this is indeed the main medium used. In fact, there are two media
used for electronic publication: -
(1) The web, and
(2) A CD-Rom.
In both cases, the publication is in the form of a web page, and the medium used is whichever is most
appropriate for transmission between one person and another. Clearly, where the number of recipients
is finite, a CD-Rom is often best. This is also the case if the recipient dislikes the web or is unfamiliar
with it. On the other hand, if the number of recipients is infinite, such as with promotional material,
then the web is the only feasible medium to use.
By publishing in web page format, a web browser will be required for the sender to prepare the
publication and for the receiver to read it. In most cases Microsoft Internet Explorer and Netscape
Navigator will be the browsers used. The reason for using a browser is that the publication will be
prepared in one of the web languages capable of being read across different systems and with a built-
in link system between the document pages. We have already noted some of the languages used.
However, HTML is still the favourite.
The main components of a web page are:
A file name for the page
Meta tags, which are used to activate the browser in some way. Meta tags are used to describe
the pages in a few words. They are an opportunity to include some keywords that the search
IT and Presenting Information 183
© Licensed to ABE
engines will recognise and use to make your publication known to people browsing the web.
This is not, of course, important when publishing on a CD-Rom.
The actual text and graphics to be included in the page between tags. This will be a title, a
picture or graphic, a piece of text and links to other pages.
The first two components are for the use of the system, the only part seen by the recipient or reader of
your publication will be the last part. The following picture of a web page shows the introductory or
home page. It simply introduces the subject. First of all, the page has a heading. Then a picture is
included, as pictures are much better at conveying the subject matter than words. Finally, there are
two clear links via buttons, to other web pages.
Figure 8.3
Whilst the web page is prepared in HTML language, it is not necessary for the ordinary user to learn
such a language. There are many software tools available. Many are included with the word
processor package and others are available free from the web. By following the usual menu options,
and with very little practice, it is possible to compile a brand new web page in about ten minutes.
Once the basic web page has been constructed, it can be edited in much the same way as any
document. You will be able to paste in or import documents that you have previously prepared in
your word processor. Graphic images, and even sound, can be imported from other stored files, either
in your computer or from a CD-Rom.
Once the page has been completed, it can be saved to a CD-Rom or placed on the web. There are
software tools available for transferring or uploading, the page onto the web. And again, just follow
This is the story of the Great War, 1914 – 1918, at sea.
To read about the following, click on the links:
1. The life of a sailor
2. The Battle of J utland
Life at sea
J utland
Clicking on the buttons activates the links to other pages
184 IT and Presenting Information
© Licensed to ABE
the menu suggestions. However, you will need to know the URL (address) of the web server to which
you are placing the page. This will be, in most cases, the web server of your ISP (the dial-in contact
number you use) or it may be the web server of your Intranet. You will also be required to provide a
password that is used to protect the web page so that only the author can change it.
Summary of the Web Page Creation Process:
1 Prepare the document and/or images you wish to be included on your page, using the word
processor and other facilities of your computer.
2 Using an HTML editor, write the HTML document. This will give a defined outline of the page,
remembering that HTML is actually just a layout language. There are different types of HTML
editors, from the simple to the more advanced.
3 Place all the documents and images previously prepared into the HTML document, between the
tags. These documents can be edited at any time, once you have found what works and what does
not.
4 Load the whole web page into your browser. This will now need to be checked to make sure the
page appears as you intended. If not, editing will be required. It is usually a good idea to load the
page into several browsers as they each interpret the HTML document differently. You should
certainly test both of the main browser types.
5 Having finished the preparation, either copy the web page file to a CD-Rom, if that is what is
required, or transfer it to the web server using file transfer protocol (FTP) software.
Design of Web Page
The following are a few relevant points but we must always remember that design is very subjective
and we all have our preferences. The overriding golden rule is, keep the appearance of the page
simple and uncluttered.
The page should be easy and intuitive to read and use by the recipient, so that what your
communication is effective. Use a simple heading to the page.
The recipient should receive as much of the whole communication (page) as possible within the
screen area. If scrolling up and down a page is required, whilst keeping it to a minimum,
provide easy and obvious ways in which to do this. At the very least a ‘return to top’ button
should be included at the bottom of the page. The recipient should not need to do anything
beyond this, other than moving onto other pages in the site.
The communication on the page should be meaningful and complete.
Graphics and pictures are powerful support to what you wish to say on the page. Avoid
complex and moving graphics, as these are slow for the recipient to download. The
communication will be ineffective if the recipient does not have time to wait for your fancy
design to download to their machine.
These are the main points, but there are plenty of others. As there as many tools and devices for
enhancing web page design, it is very easy to overload the page. Your message then gets lost in all the
clutter, defeating the whole point of the communication. Before attempting to design a web page and
place a communication on it, it is a good idea to look at a wide example of existing pages and decide
which you personally like best. The following are ten common mistakes in web design:
1. Using Frames. A technique whereby the visible screen area is broken up into individual, free-
standing sections.) Splitting a page into frames is very confusing since frames break up the
IT and Presenting Information 185
© Licensed to ABE
visible screen. All of a sudden, you cannot bookmark (save the URL) the current page and
return to it as the bookmarks will indicate a frame rather than the page.
2. Over-use of Bleeding-Edge Technology. Avoid trying to attract visitors to your site by using
the latest web technology. You may attract a few enthusiasts, but mainstream visitors will care
more about the usefulness of the content and good customer service. Using the latest and
greatest before it is in wide spread use will discourage visitors. Doing so may cause their
system to crash while visiting your site and you can be sure that many of them will not be back.
Unless you are selling Internet products or services, it is better to wait until some experience has
been gained with respect to the appropriate ways of using new techniques. When desktop
publishing was young, people over-enhanced their documents: We can avoid doing similar
things on the Web.
3. Scrolling Text and Constantly Running Animations. Never include components that move
constantly. Moving images have an overpowering effect on human peripheral vision. Give your
web page visitor some peace and quiet to actually read the text.
4. Complex URLs. Even though link addresses like URLs should never be exposed on the screen
interface, they should exist. Experience shows that visitors actually try to decode the URLs of
pages to infer the structure of web sites because of the lack of support for navigation and sense
of location in current web browsers. A URL should therefore be presented in human-readable
form using file names that reflect the nature of the information space. Also, visitors sometimes
need to type in a URL, so try to minimise the risk of error by using short names with all lower-
case characters and no special characters (many people don't know how to type a ~).
5. Orphan Pages. Make sure that all pages include a clear indication of what web site they belong
to since visitors may access pages directly without coming in through your home page. For the
same reason, every page should have a link up to your home page as well as some indication of
where they fit within the structure of your information space.
6. Long Scrolling Pages. Only a minority of visitors scroll beyond the information that is visible
on the screen when a page comes up. Whilst web visitors are now more willing to scroll down a
page, and are certainly more likely to do so than to follow a link to the next page in the site, it is
important to ensure that all critical content and navigation options are on the top part of the
page.
7. Lack of Navigation Support. Don't assume that visitors visitor. Provide a site
map and let visitors know where they are and where they can go.
8. Non-standard Link Colours. Links to pages that have not been seen by the visitor are blue;
links to previously seen pages are purple or red. Don't change with these colours since the
colours have become standardised and the ability to understand what links have been followed is
one of the few navigational aides that is standard in most web browsers. Consistency is key to
teaching visitors what the link colours mean.
9. Outdated Information. Keep your web site up-to-date. Maintenance is a cheap way of
enhancing the content since many old pages keep their relevance and should be linked into the
new pages. Of course, some pages are better off being removed completely from the server
after their expiration date.
186 IT and Presenting Information
© Licensed to ABE
10. Overly Long Download Times. Traditional guidelines indicate 10 seconds as the maximum
response time before visitors lose interest. On the web, visitors have been trained to endure so
much suffering that it may be acceptable to increase this limit to 20 seconds for a few pages.
Bandwidth is getting worse, not better, as the Internet adds visitors faster than the infrastructure
can keep support.
187
© Licensed to ABE
Study Unit 9
Information Processing
Contents Page
Introduction 188
A. Data And Information 188
B. Gathering And Organising Information 190
Spreadsheets 190
Databases 194
Information Systems 197
Management Information Systems (MIS) 197
Data Warehousing 198
188 Visual Communication
© Licensed to ABE
INTRODUCTION
We now move on to the processing of the information prior to transmission. First we must understand
the difference between data and information and just what each is. Then we can look at the various
tools used for processing. Primarily these will be spreadsheets and databases. However, we will again
examine the role of browsers in this respect. And finally, the large topic of information systems needs
to be considered, as this is the source of most information available within the corporate environment.
A. DATA AND INFORMATION
We will begin with two definitions: -
Data are raw facts such as, words, numbers, people, things. By itself, data means nothing.
Information is the meaning we derive from the facts. For example, the number can be a
telephone number, the ‘people’ may be everyone in the building, and so on.
In short, we say,
Let us consider an example. It is easiest for us to understand the difference through numbers.
3 and 68 are just a pair of numbers and with no further explanation, they will for ever remain a
meaningless set of numbers.
But, if we put these numbers into the context of this course, we then understand them to be a reference
to Study Unit 3, page 68, the Unit on ‘Writing Articles’. Within this context, the bare facts that are
two numbers, become information conveying a reference to the reader.
Data is stored in the computer. This is important. You will recall that everything is stored in the
computer as a digitised number in the form of 1s and 0s, i.e. in binary code. This is so whether it is a
word, a number, a picture, a sound or anything at all. These 1s and 0s by themselves are meaningless
to us. For example, can you tell what the following represents?
10101010 11001100 11110000
Even if you decipher the digitised groups into their normal number equivalent, they still do not tell us
anything. And so, to repeat, it is data that is stored in the computer.
You might then ask: ‘Where is the information in that case?’ And the answer is that the information
is nowhere until we supply it.
An example will best help us examine the concept of information: -
We will start with the following simple series of numbers: 100100
The first thing for us to do is to ask: -
1. Why were those particular numbers chosen?
2. Is there a familiar pattern or format?
3. What do they mean?
My answers, in order, would be:
data = facts
information = meaning
Visual Communication 189
© Licensed to ABE
1. No particular reason as another six digits could equally have been chosen.
2. Yes.
3. I’m not saying at this stage.
In other words, I know what I intend them to mean but at this stage you do not. Even if you have
made a guess, you cannot be sure.
As the numbers stand, they do not tell us anything with confidence. They convey no meaning, and
therefore no information to us. We have arrived back at the definition.
Of course the representation need not be numbers. For instance:
baa baa
could be another representation of the same information. It still tells us nothing with certainty.
Examining the two data representations: 100 100 baa baa
We can think of each as a further encoding of the other. In other words they are the same thing.
The possible meanings conveyed to us could include:
1. The number one hundred thousand and one hundred.
2. A date. But is it the 10
th
J anuary 2000, or the 1
st
October 2000 as expressed in the North
American style?
3. The binary equivalent of the number we normally give as 36. This is the numbering system used
inside computers.
4. The sound made by a sheep.
5. Musical notes in series as for the tune ‘Three Blind Mice’.
6. Any others you may have thought of.
To choose the correct option from these we need to know the context in which the data is presented.
Each of the options can be correct within its own separate context. We can now say that to fully
understand a piece of information we need to interpret the data representation within a previously
understood context.
This has a knock on effect on our understanding of information however. For an example we will
further consider the option number 3, above, which shows the binary numbering system used inside
computers. If you are one of the many who do not know what ‘binary numbers’ means, then the data
representation is still just data to you. No information is conveyed. We can say that what is
information to one is usually just data to another. So all representations are both data and information
at the same time and it depends upon a context and further understanding to turn data into information
One final note about data. It is common to use data for both singular and plural forms, although data
is the Latin plural of datum.
190 Visual Communication
© Licensed to ABE
B. GATHERING AND ORGANISING INFORMATION
As mentioned above, we will now discuss the collection of information and its organisation into a
presentable form.
Spreadsheets
A spreadsheet is a piece of software that presents a grid on the screen and into which we can enter
numbers and apply calculations and formulae across the grid. The following is a simple outline of the
page display presented by spreadsheet software.
A B C D E F G H I
1
2
3
4
5
6
Cell A1
Cell C5
Given that any specific cell can be directly referenced, it is possible to insert all sorts of cross
references in the spreadsheet page. Thus, if cell D4 contains the reference A1, then both cells will
contain the same data. In addition, any change made to cell A1 will also be copied to cell D4.
Page before change page after change
Cell D4 references A1. Therefore, a change in A1 will be copied to D4.
This is a very powerful facility, especially as formulae and calculations can be included in the
references.
A B C D
1 80
2
3
4 A1
A B C D
1 100
2
3
4 100
Visual Communication 191
© Licensed to ABE
Two examples using a calculation in the first sheet and a formula in the second
(B1+C3+A2+D3) =(23+20+9+13) =65 sum(D1 to D3) =17+24+13 =54
There are many formulae possible in each of the spreadsheets that are available. And these are
applicable to data such as text, numbers, dates, financial and, statistical figures, and so on. As well as
entering values into the cells, we can include labels.
Spreadsheets are particularly useful in evaluating ‘what if’ scenarios. This is a facility much used in
decision support systems whereby the decision-maker can input different values to a projected
scenario, and then examine the range of outcomes.
First, the spreadsheet is set up with various data trails, as required.
In the following example, using the basic Table 1, with formulae, we get Table 2: -
Table 1 Table 2
A B C D
1 10 23 21 17
2 9 21 18 24
3 0 12 20 13
4 15 16 18 65
A B C D
1 10 23 21 17
2 9 21 18 24
3 0 12 20 13
4 15 16 18 54
A B C D E
1 if x = 10
2 and y = 20
3
4 then z = D1+D2
5
6 gives 5*D4
7
8 and result E8
A B C D E
1 if x = 10
2 and y = 20
3
4 then z = 30
5
6 gives 150
7
8 and result 150
A B C D
1 income 1000
2 expenses 200
3 profit 800
4 Tax at 20% 160
5 Profit after
tax
640
(B1 – B2)
(B3 * 0.2)
(B3 – B4)
192 Visual Communication
© Licensed to ABE
Table 3 Table 4
Table 5 Table 6
And, by sequentially doubling the value of x, the result, which started at 150, becomes 200, 300, 500
and 900 etc. In other words, a simple doubling of the basic value, x, results in a doubling of the
increase in the result.
x =10 result =150
x =20 result =200
x =40 result =300
x =80 result =500
x =160 result =900
However, the actual result increase is by a lesser percentage than the x increase of 100%. The figures
are: -
x =10 to x =20, result increases from 150 to 200, that is, by 50, which is 33.33% of 150
x =20 to x =40, result increases from 200 to 300, that is by 100, which is 50% of 200
x =40 to x =80, result increases from 300 to 500, that is by 200, which is 66.66% of 300
x =80 to x =160, result increases from 500 to 900, that is by 400, which is 80% of 500
A decision would have to be made on the understanding that although doubling the initial input value,
which could be a production input, does not give a corresponding doubling of the output. This
exercise not only shows the usefulness of the ‘what if’ facility in spreadsheets, it also emphasises that
the spreadsheet is no more than a support tool in decision making. The personal judgement of the
decision maker is still very necessary.
A B C D E
1 if x = 20
2 and y = 20
3
4 then z = 40
5
6 gives 200
7
8 and result 200
A B C D E
1 if x = 40
2 and y = 20
3
4 then z = 60
5
6 gives 300
7
8 and result 300
A B C D E
1 if x = 80
2 and y = 20
3
4 then z = 100
5
6 gives 500
7
8 and result 500
A B C D E
1 if x = 160
2 and y = 20
3
4 then z = 180
5
6 gives 900
7
8 and result 900
Increase =50
Increase =
Increase =200
Increase =400
50 to 100 =100%
100 to 200 =100%
200 to 400 =100%
Visual Communication 193
© Licensed to ABE
Out of interest, you may be thinking that if we were to continue the exercise just a little further we
would achieve a doubling of the result figure. Should you try the calculations, you will find that this
is never so!
Another very useful spreadsheet facility is the creation of charts or graphs. There are many styles
available and it is quite easy to choose the most appropriate for some situation by examining the menu
of styles presented and the illustrative examples provided. When using the Microsoft Excel
spreadsheet, the chart menus are accessed by clicking on the button with the coloured column chart
icon.
Using the following example spreadsheet which expands the earlier profit calculation over several
years, we can show some examples of the corresponding charts. As charts are a picture, they are
much easier for people to assimilate and to understand a changing situation as we have in our
example.
First, the spreadsheet (Table 7).
Table 7
The first two charts are both column charts. Figure 9.1 is a cluster column chart, while figure 9.2 is a
stacked column chart.
Figure 9.1 Figure 9.2
A B C D E
1998 1999 2000 2001
1 income 1000 1500 900 1200
2 expenses 200 300 150 250
3 profit 800 1200 750 950
4 Tax at 20% 160 240 150 190
5 Profit after
tax
640 860 500 760
0
500
1000
1500
income 1000 1500 900 1200
expenses 200 300 150 250
profit 800 1200 750 950
Tax at 20% 160 240 150 190
Profit after tax 640 960 600 760
1 2 3 4
0%
20%
40%
60%
80%
100%
Profit after tax 640 960 600 760
Tax at 20% 160 240 150 190
profit 800 1200 750 950
expenses 200 300 150 250
income 1000 1500 900 1200
1 2 3 4
194 Visual Communication
© Licensed to ABE
income
expenses
profit
Tax at
20%
Profit after
tax
income
expenses
profit
Tax at 20%
Profit after
tax
Next are two pie charts. Figure 9.3 is a standard pie chart and figure 9.4 is an exploded pie chart.
Figure 9.3 Figure 9.4
And finally we have a line chart (Figure 9.5).
Figure 9.5
Each of these charts shows the same information in a different style. The style chosen will depend on
what information we want to highlight and that we feel shows this aspect off best. This is a subjective
choice and we will each have our preferences. The important point, as always, is that the
communication must be successful. To achieve this, simplicity is always the best course to take.
Databases
Databases dominate all of today’s computing activities. There are databases at the root of nearly all
systems, and their number is growing fast. So, the first question we need an answer to is, ‘What is a
database?’
A database is a single store of data files. The files are stored in a structured form and each data item
is, as far as is possible, stored once only. The database is capable of being used by many users
simultaneously and each of these users can use the database in a number of different ways.
This is quite a long definition, but it boils down to saying that a database is data stored in one place
and it can be used by many people in many ways.
There are different types of database. But most modern databases and all small system databases are a
type called relational databases. This just means that the data is stored in a series of tables. A table is
0
200
400
600
800
1000
1200
1400
1600
i
n
c
o
m
e
e
x
p
e
n
s
e
s
p
r
o
f
i
t
T
a
x
a
t
2
0
%
P
r
o
f
i
t
a
f
t
e
r
t
a
x
Visual Communication 195
© Licensed to ABE
called a relation, hence the type of database. The following two tables are examples of relations.
There is little that is special about them. However, the columns are labelled and, within any one
relation, there are no duplicate rows.
Table 8 Table 9
Car Student
The above tables are two examples of relations as they could be held in a database. Each relation has
a name and each has several named columns. Each row is equivalent to a stored record.
You may also have noticed that each table has a column with the same values within it, although the
columns are labelled differently. That is the car registration columns. This indicates that there is a
relationship between the tables.
A relationship such as this gives the user of the database flexibility in accessing the data, and so helps
the database comply with the requirement of being able to be used in a variety of ways.
Worked Example 1
Suppose we need to know the type of car owned by a particular student. By following these steps, we
can find the car.
1. In Table 9, we access the Student’s name, and number if it is known. Suppose this student is
R Thomas.
2. The third row of Student relation tells us that R Thomas has a car with registration number J 54
XYZ.
3. Access the Car relation with this registration number.
4. The second row of this relation tells us that the particular car is a green Peugeot 406.
Therefore we now know that R Thomas drives a green Peugeot 406, registration J 54 XYZ.
Worked Example 2
This time we want to find the owners of all the black cars in the car park.
1. In Table 8, we find that rows 1 & 3 have details of black cars, registration numbers S123 ABC &
Y344 DEF.
2. Using both of these values, obtain the details of rows 2 & 4, in Table 9 giving students N Black &
A Brown.
All sorts of similar queries can be asked of the database. The language used for this work is known as
Standard Query Language (SQL). SQL has virtually monopoly on database use. The good news is,
again, that we do not need to learn the language as there are many software tools on the market which
enable us to access the database via a series of window displays and by clicking on various screen
buttons.
The database is controlled by a very complex piece of software known as the Database Management
System (DBMS). All users access the database through the DBMS.
Type Model Colour Reg No
Ford
Mondeo Black S123 ABC
Peugeot 406 Green J 54 XYZ
Rover 45 Black Y344 DEF
Vauxhall Astra Red X43 J J U
Name Number Age Car Reg
G Smith 3456 25 X43 J J U
N Black 2345 37 S123 ABC
R Thomas 4563 22 J 54 XYZ
A Brown 2534 51 Y344 DEF
196 Visual Communication
© Licensed to ABE
The DBMS performs a number of functions:-
It controls who is allowed to access the database by using different passwords and
authorisations. Once a user has been granted access, they will need to produce further
passwords to gain access to different parts of the database. This is both a security mechanism
and it protects the privacy of the data. For example, the company payroll department needs to
know the detailed salaries of all employees, but few other personnel need this information.
Therefore it is protected from general access.
It controls the data being entered into the database by performing a series of checks to ensure
the data conforms to the required format, is a reasonable value and not, say, having a month 13
date, is not already stored, and so on.
It processes the data being retrieved from the database as in our two worked examples above,
although further processing of the results may occur elsewhere,
It maintains a log of who accesses the database and how and how often it is used.
And there are many other specialist functions that the DBMS performs.
Each user accesses the DBMS in one of two ways: -
(1) By making a direct query as in our queries above,
(2) Through a special application program.
Figure 9.6
In Figure 9.6,
Three users access via the first application program. These users are all making similar use of
the database and so may all be in the same company department.
Two users use the second application program,
One user has direct access to the DBMS via a standard SQL query.
If the same query is to be made many times, greater efficiency is obtained by writing an application
program. If the query is an ad hoc query, then a direct SQL query will be most efficient.
DBMS
Application
Program 1
Application
Program 2
User 1 User 2 User 3 User 4 User 5 User 6
The computer database
Direct query
Visual Communication 197
© Licensed to ABE
Databases store millions of individual pieces of data. As far as possible, each is stored once only as
that when a value is updated, as this needs to be done in one place only, then the integrity of the data
is ensured. Where it be necessary to have more than one copy of a data item, then there must be
simultaneous updating of each copy of the item. In our illustrative relations above we stored the
registration numbers in two places so that we could have a relationship.
Information Systems
An information system is a computerised system that provides information. However, that definition
is much too simplistic to be of use to a company. The system must be capable of providing
information that is both reliable and timely.
Virtually all companies use an information system of some kind. At its simplest, as people in the
company go about the business of the company, they generate data. For example, the production
department generates supply needs, finished product numbers and maintenance requirements and
schedules. It will also generate data on personnel work schedules, hours worked and personnel
required. Other departments generate similar data. All this data is stored in the corporate database.
It is then made available to those with the authority to access it so that other activities of the company
can be efficiently completed. For example, whilst the production department generates the hours
worked by each individual worker of the department, it is the payroll department that will retrieve the
data from the database to calculate the wages of the workers. There is no need for paper to be used
and a record of the hours is readily available.
Communication of information around the company is through the common database.
Management Information Systems (MIS)
One of the principal uses of a company information system is to provide management with reliable
and up-to-date information on the performance of the company. Furthermore, management at
different levels will have different information requirements. We will start with an outline of the main
management structure (Figure 9.7).
Figure 9.7
The operational management will require information in the form of a detailed report. This would
contain details such as a full production list and schedule, detailed sales figures for each sales person
and so on. This information is used for supervisor purposes.
Executive level management
Strategic or middle level management
Operational or lower level management
198 Visual Communication
© Licensed to ABE
Strategic level management require information in summary report form. For example, the report
may contain a summary of the sales for the previous month, a summary of the supply flow over the
previous three months, and so on.
Executive level management also require summary reports, but over a longer time scale. The report
may contain the production figures for the previous year or projected half-yearly profit figures, etc.
All management will be provided with exception reports. These are generated by the system
whenever something goes wrong or something strays outside previously prescribed limits.
To produce these reports, the MIS will extract the relevant data from the database, sort it and process
it and it will then present the data in some prescribed manner.
A Decision Support System (DSS) is a special type of MIS. As its name suggests, it is intended to
help decision-makers with their decision. We have already examined one of the tools used by a DSS
when we discussed spreadsheets and the ‘what if’ scenario. As well as a spreadsheet, the DSS will
have a statistical tool, which can be used to discover trends in the data. A DSS has the facility for the
manager to call up the summary data and to then directly manipulate it.
As we noted before, it is most important not to think of the DSS as being a tool that make decisions.
It is a support tool, as there is no substitute for an experienced manager who can bring many other
skills and judgements to the decision making process.
You may also come across mention of Executive Information Systems, (EIS). This again, is a
special version of the MIS. It is intended to help the executive level managers analyse long term
trends and to build a strategy for the company to move forward.
Data Warehousing
Data warehousing is a more recent development, but its popularity is growing very fast.
A data warehouse is like the database of the MIS, but it is historical and so has a time factor built into
the data. The operational MIS processes vast amounts of data, but once it has been processed it is
discarded. The data warehouse imports data resulting from the processing of all the different
transactions. As this data comes from a number of different systems, assuming the company is large
and spread over several sites, it arrives at the data warehouse in many formats. These are collated to a
common format and then stored in the data warehouse. And there it stays. As a result, data
warehouse data is very stable.
It is then possible for the data to be analysed at leisure. One technique is known as knowledge
discovery. This involves trawling through the data using a further technique called data mining,
which looks for trends in the data. Largely supermarkets use this, as they search for people’s
shopping patterns. They may look for the pattern of late night or young men shopping, and patterns
for other identifiable groups. | https://www.scribd.com/document/188319765/Business-Communication | CC-MAIN-2018-51 | refinedweb | 60,120 | 51.78 |
Forum:Add UnNetHack source code in Source namespace
This would allow providing references in articles. Bulwersator (talk) 20:56, 25 January 2013 (UTC)
- Doing this might be slightly problematic as keeping all versions might be a lot of data ("all versions" as in "all revisions", which might be necessary to reference things in the most recent version). I thought about this at some point but discarded the thought, but: perhaps a MediaWiki extension could work? I'm not sure whether such a thing exists or whether it would be helpful, though.
- The UnNetHack source is also viewable using the web. It might not be the nicest way, but I think I could get Template:Refsrc (and, for non-references, Template:Sourcecode) to allow parameters like {{refsrc|monst.c|42|game=UnNetHack|changeset=1032}} (or something like that) and target that source browser for now. If another solution (that allows to target a specific changeset) is later introduced, Template:Refsrc could be adjusted. —bcode talk | mail 21:54, 25 January 2013 (UTC)
- …and {{refsrc}} works now. See the example on the Template:Refsrc page. —bcode talk | mail 22:22, 25 January 2013 (UTC) | https://nethackwiki.com/wiki/Forum:Add_UnNetHack_source_code_in_Source_namespace | CC-MAIN-2022-40 | refinedweb | 192 | 55.34 |
Hi Dick,
An XSGrammar is a collection of schema components for a given target
namespace. The schema validator will consult the grammar pool once per
namespace, so you only have one shot to return an XSGrammar object from
your pool for each namespace. That doesn't prevent your grammar pool
implementation from doing something clever like merging XSGrammars (see
org.apache.xerces.impl.xs.XSLoaderImpl.XSGrammarMerger [1]) but that may
be a bit difficult for you to do particularly if the schemas aren't
disjoint. I would go the entity resolver route instead of trying that. You
can register an XMLEntityResolver [2] with the XMLGrammarPreparser by
calling the setEntityResolver(XMLEntityResolver) method. The parser's
default behaviour is to open a URLConnection for the location specified.
If you're unable to create an InputStream from the URLConnection in your
entity resolver the parser won't succeed at doing that either.
Thanks.
[1]
[2]
Michael Glavassevich
XML Parser Development
IBM Toronto Lab
Dick Deneer <dick.deneer@donkeydevelopment.com> wrote on 07/04/2006
01:59:17 PM:
> Hi,
>
> I am using a grammarpool to cache schemas and want the user to point
> to a number of schemas that will be added to the grammarpool. Then
> the grammarpool is used to validate a XML instance document.
> One of the schema (=top ) uses a include to another schema (=sub
> ). If I can rely on the location mentioned in the include there is
> no problem. Just add "top" to the pool and everything is fine.
> But when the path in the top schema is invalid, the included schema
> cannot be found. My first idea was just let the user add the
> subschema also to the pool. But this has no effect. The result is
> that the subschema is just ignored and will not be in the
> grammarpool (likely caused by the fact that there is already a
> grammar with the same namespace in the pool, namely "top").
> Validation will be incomplete because the type definitions mentioned
> in sub are ignored.
>
> Working in the other direction (first add the sub, then the top
> schema) does not not work either: only the sub schema will be added
> to the grammarpool
>
> The ideal situation for me would be: just add another schema to the
> pool if the parser gives an error that something cannot be found.
>
> Is there no other way then using a entityresolver?
> If so: can I detect in the entityresolver that the schema will or
> will not be found by the parser.if "not" , I have to return my own
> inputsource.
> Can I also use such a entityresolver when using a XMLGrammarPreparser?
>
> PS
> You can easily "replay" the above situations with
the XMLGrammarBuilder.java
> program that is supplied with xerces. But also using direct (without
> preparsing) the dom or sax parser with a grammarpool will give the
> same results.
> I used these xml and schemas
>
> top.xsd:
> <?xml version="1.0" encoding="UTF-8"?>
> <xsd:schema xmlns:
> <xsd:include
> <xsd:element
> <xsd:complexType
> <xsd:sequence>
> <xsd:element
> </xsd:sequence>
> </xsd:complexType>
> </xsd:schema>
>
> include.xsd:
> <?xml version="1.0" encoding="UTF-8"?>
> <xsd:schema xmlns:
> <xsd:simpleType
> <xsd:restriction
> <xsd:enumeration
> <xsd:enumeration
> </xsd:restriction>
> </xsd:simpleType>
> </xsd:schema>
>
> instance.xml:
> <?xml version="1.0" encoding="UTF-8"?>
> <myRoot>
> <label>028</label>
> </myRoot>
---------------------------------------------------------------------
To unsubscribe, e-mail: j-users-unsubscribe@xerces.apache.org
For additional commands, e-mail: j-users-help@xerces.apache.org | http://mail-archives.apache.org/mod_mbox/xerces-j-users/200607.mbox/%3COF612F628A.4EACFED8-ON852571A4.001A144A-852571A4.001CA720@ca.ibm.com%3E | CC-MAIN-2017-13 | refinedweb | 569 | 55.54 |
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Sets11:51 with Craig Dennis
A java.util.Set interface does not allow for duplicates. There are also SortedSet which allow for custom sorts and add new methods for getting different ranges of the items.
- 0:00
Okay, so now let's start using all the tweets we received.
- 0:03
I think we should finding out all the unique hashtags that were used.
- 0:07
Let's flip back to our manual way of thinking.
- 0:10
How would we achieve this by hand?
- 0:13
I guess we would do something like this.
- 0:14
I'd take, I'd take this list.
- 0:17
And I look for each hashtag and I write it on a unique list over here.
- 0:24
So here we have #treet, so I'll write #treet, and I'll go
- 0:29
look at my next one, for hashtags.
- 0:34
And I see treet again, so I'm not gonna add that to the list.
- 0:37
Come over here, here's java.
- 0:39
So I'm gonna #java to the list.
- 0:44
And here's one, here's data.
- 0:45
I'm gonna add #data.
- 0:48
And Java's already on there, and treet's already on there.
- 0:50
I just keep working my way through this list, only writing the unique words.
- 0:54
So ready for the good news?
- 0:55
There's a collection interface that represents the unique list we created.
- 0:59
It's called Set and it's used for stuff just like this.
- 1:02
There are several implementations of the Set interface, so
- 1:05
let's go familiarize ourselves with them.
- 1:07
The first Set implementation that I'd like us to look at is HashSet.
- 1:11
Now, I don't want to confuse hashtags with hashes.
- 1:14
In most programming languages, a hash is a way to uniquely identify objects.
- 1:20
In Java,
- 1:20
every object has a method called hashCode, which is a 32-bit signed integer.
- 1:25
And it, like almost all methods, can be overridden.
- 1:29
When we talk about hashes here, we're talking about that hashCode.
- 1:32
It's used heavily in several of these data structures.
- 1:35
So let's pop open a ripple.
- 1:36
[BLANK_AUDIO]
- 1:43
Okay, so, let's make a new set.
- 1:46
And again, the interface is on the left.
- 1:51
Let's make a set of the meals I had this week.
- 1:53
And the implementation is on the right.
- 1:58
[BLANK_AUDIO]
- 2:04
Okay, so you add items to a hash with the add command.
- 2:07
So let's add what I had this week.
- 2:09
So let's see, had tacos on Monday, and
- 2:14
on Tuesday I had tacos, on Thursday I had tacos.
- 2:21
I skipped Wednesday.
- 2:22
On Wednesday I had tacos.
- 2:25
And I had french dip on Friday.
- 2:29
And then, I also had, on Saturday, I had a burrito.
- 2:37
Okay, so let's take a look at those meals.
- 2:41
So I, you'll see that there's only three items in here.
- 2:44
It's burritos, tacos, and french dips.
- 2:45
And you'll notice that when I was typing add,
- 2:48
the first time it went in it was true, but after that it was saying false each time.
- 2:52
So it returns false if it's not a new entry in there.
- 2:56
Kinda nice.
- 2:57
Now I was thinking that we could do is build a couple of lists so
- 3:00
I can show you how the two interact, how sets and list interact.
- 3:03
Okay, so let's build a list with interface and
- 3:08
the name is frontendlanguages and we'll use that handy dandy Arrays.asList.
- 3:17
And the front end languages that we teach here.
- 3:20
HTML, CSS, and all its flavors, and JavaScript, okay.
- 3:28
And let's talk about some back end languages that we teach here as well.
- 3:31
[BLANK_AUDIO]
- 3:36
Again, we use Arrays.asList.
- 3:39
We'll do Java, Python, Objective-C,
- 3:48
Swift, PHP, Ruby.
- 3:54
And now, with Node, we're starting to teach JavaScript on the backend.
- 4:00
[INAUDIBLE].
- 4:02
Okay, so we have two lists there.
- 4:06
So let's go ahead and let's make one more list.
- 4:11
And we'll make a list of all the languages and
- 4:12
I'll just kinda combine those two together.
- 4:17
So we'll make a brand new ArrayList and all, all these collections take
- 4:22
another collection usually as the, as a, an argument to the constructors.
- 4:27
So let's go ahead and let's pass this in frontEndLanguages.
- 4:30
So it's going to make a copy of that list basically.
- 4:34
And then they also have, most of them have a method called addAll.
- 4:38
And I'm going to add all the backEndLanguages to that set.
- 4:44
All right so now if we take a look at allLanguages.
- 4:53
See that it's all coming across to be, we see that JavaScript's in there twice.
- 4:57
Sets, much like that list also take that, so
- 5:00
let's say a set uniqueLanguages
- 5:06
equals new HashSet.
- 5:11
And we'll pass in the allLanguages.
- 5:16
Cool. So we see
- 5:16
now JavaScript's only in there once.
- 5:20
But you'll also notice that they're unsorted.
- 5:22
So here's a case where we can just change the implementation to another one and
- 5:27
get new functionality.
- 5:28
So if we come back in here and we change this to TreeSet.
- 5:31
[NOISE] So tree sets are sorta automatically.
- 5:36
They use a tree structure under the covers.
- 5:39
Which uses branching to arrange it's elements.
- 5:42
So let's, let's change it.
- 5:44
And now if we take a look,
- 5:45
we'll see that it's in alphabetical order which is awesome.
- 5:47
And the cool thing about this is if I go ahead and add a new one here.
- 5:52
So I'm gonna add C# which we're planning on doing here shortly.
- 5:55
And now if we look at uniqueLanguages again.
- 6:03
We'll see that it kept the order.
- 6:05
See how C#'s in the front there?
- 6:06
All right, so TreeSets have a couple of new features as well.
- 6:12
But we need to also remember to upgrade its interface to sort its sets.
- 6:17
So, but if we don't, let me show you with the, what happens just so
- 6:20
you're familiar with this.
- 6:21
So if we say.
- 6:22
There's a thing called headSet which I'll get the first,
- 6:25
first half of things before the letter J.
- 6:28
It doesn't know about that with the sorted, with the set, all right.
- 6:33
So if we come in here and we change this, to a SortedSet.
- 6:40
With implementation of the now SortedSet.
- 6:42
Now if we do the headSet of J,
- 6:43
what this does is it shows everything that happens before J.
- 6:47
So you'll see it's the CSS and the HTML, and then we can do the same thing.
- 6:50
We can do the, the tailSet.
- 6:52
So anything that happened after J.
- 6:55
And that's, you know, everything after J.
- 6:57
There's also one that goes right in the middle.
- 7:00
That is called subSet.
- 7:06
And this is a good thing for type ad.
- 7:08
So, like, let's say that somebody typed, Java.
- 7:10
And you just say, you give again what they typed.
- 7:13
And if you do character.MAX_VALUE.
- 7:15
So it's adding, like, whatever the largest value is there, afterwards.
- 7:20
It will show you everything that matches the start of that,
- 7:23
it's a pretty cool little trick.
- 7:25
Okay, so why don't we figure out how to use sets to figure out
- 7:28
all the unique hashtags and mentions used in our Treets.
- 7:31
Let's start with the hashtags.
- 7:32
[BLANK_AUDIO]
- 7:41
[BLANK_AUDIO]
- 7:46
Okay, so I'm gonna remove this to a loop we had working here, so
- 7:50
we proved that we could get the hashtags out.
- 7:53
And let's go ahead and make a new Set,
- 7:56
allHashTags is a new HashSet.
- 8:03
[SOUND] Cool, so we need to import,
- 8:09
import java.util.Set,
- 8:15
and we need to import java.util.HashSet.
- 8:23
Okay, so we have this new unique HashTags there.
- 8:29
And let's go for, for Treet.
- 8:33
[BLANK_AUDIO]
- 8:40
Say allHashTags addAll treet.gethashtags.
- 8:46
Remember, that's just taking a list and
- 8:51
we're just at doing the add all to the set.
- 8:54
So let's print that out.
- 8:56
[BLANK_AUDIO]
- 9:08
allHashTags, so we'll print out the string representation of that,
- 9:11
which is pretty nice, which we've already just seen in that REPL there.
- 9:14
Okay so, we, let's do the same thing for mentions.
- 9:18
We'll say
- 9:21
Aet String allMentions,
- 9:29
new HashSet.
- 9:34
And let's do the same thing here.
- 9:35
And we'll say allMentions.
- 9:45
And again here we'll, [BLANK AUDIO] get mentions.
- 9:52
Okay? And we'll duplicate this line.
- 9:54
And we'll say the mentions are [BLANK AUDIO].
- 9:59
[BLANK_AUDIO]
- 10:01
allMentions, cool.
- 10:09
So let's go up here, and then we'll say clear.
- 10:13
[BLANK_AUDIO]
- 10:25
>> Cool. So there are 58 treets and the hashtags
- 10:27
are #data, #treet, #selfie, #last call, #tries, #Java, #learn, #wisdom and #joke.
- 10:34
And there's the mentions there that everybody who was mentioned in one
- 10:36
of those.
- 10:38
It's pretty great.
- 10:40
So it would be nice though, see how there's kinda out of order,
- 10:43
what could we do to make those be in order, that last list.
- 10:47
Let's do the mentions, let's let's see if we can't order this correctly.
- 10:51
So, what we just saw, if we just make this a tree set, first we gotta implement,
- 10:56
import it as well.
- 10:58
[BLANK_AUDIO]
- 11:05
So we've now imported it.
- 11:09
And if we scroll up here again.
- 11:11
Let's run that one more time.
- 11:16
And bam, there they all are, alphabetical.
- 11:19
Cool. Good use of sets.
- 11:21
There.
- 11:22
I think we've learned what we set out to do.
- 11:24
Now I'm gonna toss out a slight word of warning here.
- 11:26
That the comparative interface that we implemented earlier on our tree class,
- 11:30
the ordered sets used that to do their ordering.
- 11:33
Returning zero should only happen for true equality, or
- 11:36
things will be considered duplicates.
- 11:38
Now I just wanted to give you a heads up,
- 11:39
there's lots of warnings about this.in the comparative documentation.
- 11:42
But it's worth pointing out here so
- 11:44
that you're aware if your sets start behaving wacky.
- 11:47
So let's set out to tackle this challenge and then navigate our way over to maps. | https://teamtreehouse.com/library/java-data-structures/exploring-the-java-collection-framework/sets | CC-MAIN-2017-17 | refinedweb | 2,068 | 93.03 |
Yesterday I made a category for these ruby profiler posts on my blog because I think there will be a lot of them. It’s at.
Hello! Today I am excited about bindgen, an awesome Rust tool for generating bindings from C header files. It has a great user’s guide.
This post is about what bindgen is, why I think it’s cool, and experiments I have been doing with bindgen for my Ruby profiler.
bindgen: #include for Rust
To me the dream of Rust is “it gives you all the power of C, but with a more powerful compiler, better documentation, better tools (
cargo), and a great community”. I think bindgen is a really important part of “great tools”!
Suppose you want to include a C library in your program. In C, this is easy: just include the header file.
#include <library_header_file.h> …. call functions from library here ...
So if Rust has “all the power of C” (and interoperates so well with C), you should be able to just
#include a header file from a C library and have it just work, right?
Almost! You can run
bindgen cool_header_file.h -o rust-bindings.rs and it’ll automatically generate Rust struct definitions or function declarations that will let you link in the C library. So simple!
Here’s the bindgen output for Python.h as an example. It’s 24,000 lines. Here are a couple of representative bits: the PyCodeObject struct & the declaration of the eval function.
// A struct! #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct PyCodeObject { pub ob_refcnt: Py_ssize_t, pub ob_type: *mut _typeobject, pub co_argcount: ::std::os::raw::c_int, pub co_nlocals: ::std::os::raw::c_int, pub co_stacksize: ::std::os::raw::c_int, pub co_flags: ::std::os::raw::c_int, pub co_code: *mut PyObject, … and more ... } // A function declaration! extern "C" { # [ link_name = "\u{1}_Z15PyEval_EvalCode" ] pub fn PyEval_EvalCode( arg1: *mut PyCodeObject, arg2: *mut PyObject, arg3: *mut PyObject, ) -> *mut PyObject; }
Then you can include this file in your Rust project as a module, link with libpython, and start using libpython in your Rust program! Cool!
cool bindgen features
Bindgen can do some really cool things:
- Whitelist types that you want to generate bindings for if you don’t want the whole header file
- Generate #[derive(Debug)] annotations for C structs so you can easily print them out with
println!(“{:?}”, my-struct). This is SO USEFUL when debugging!!!!
- It seems to handle
#ifdefsand stuff okay – I threw a pretty complicated set of header files at it and it seems ok so far.
- Pick which Rust compiler version you want to target
what I’m doing with bindgen
I wanted to do something weird:
#include vm_core.h, which is an internal header file in Ruby. And I didn’t actually want to just include one
vm_core_h, I wanted to generate bindings for 33 different Ruby versions (since vm_core.h is an internal header file, the structs I care about are constantly changing).
This appears to be something that
bindgen can help with me with! Here are the generated bindings for 33 Ruby versions (2.1.1 to 2.5.0rc1):. Bindgen generated about 6MB of code. (the rest of the code on that branch is kind of a mess since I’m hacking around trying to see if this approach is workable).
Once I have all those bindings in my repository, I can
use bindings::ruby_2_2_0::*; to get the right types for Ruby 2.2.0. Really simple!
Here’s the bindgen incantation I ran to get the bindings for Ruby 2.3.0. (I just put this in a script and ran a for loop to generate all 33 versions).
bindgen /tmp/headers/2_3_0/vm_core.h\ -o bindings.rs \ --impl-debug true \ --no-doc-comments \ --whitelist-type rb_iseq_constant_body \ --whitelist-type rb_iseq_location_struct \ --whitelist-type rb_thread_struct \ --whitelist-type rb_iseq_struct \ --whitelist-type rb_control_frame_struct \ --whitelist-type rb_thread_struct \ --whitelist-type RString \ --whitelist-type VALUE \ -- \ -I/tmp/headers/2_3_0/include \ -I/tmp/headers/2_3_0/ \ -I/usr/lib/llvm-3.8/lib/clang/3.8.0/include/ # my bindgen doesn’t find the clang headers properly for some reason
generating bindings at build time
You might have noticed that I committed the bindings I generated into my repository. This is not actually the recommended way to use bindgen – they recommend in general that you generate your bindings during your build.
How to do that is documented really nicely in the bindgen user’s guide.
Basically you create a
build.rs file that runs during your build and uses the bindgen library to generate bindings. I think I like the approach of having a
build.rs + Cargo.toml instead of a Makefile a lot – it seems easier to maintain. And you can declare separate build dependencies in Cargo.toml!
cbindgen: reverse bindgen
Someone on Twitter pointed me to cbindgen, a tool to go the other way and generate C bindings for your Rust code. Neat!
gonna continue experimenting
I’m still not sure if this approach of “let’s generate bindings for 33 different ruby versions and commit them into my repository” will work. But I figure the best way to find out it to keep trying it and see how it goes! If it doesn’t work then I’ll go back to using DWARF. | https://jvns.ca/blog/2017/12/21/bindgen-is-awesome/ | CC-MAIN-2019-09 | refinedweb | 878 | 63.59 |
I am now in my first C++ class, and I am learning it fairly well, but it seems like the simplest programs are giving me the most trouble.
This program uses the function FindSum() , and tells the user to input positive integers (negative integer to quit), and then adds all of the positive integers together as one positive output sum. I know some of you guys are probably laughing at me right now, I know it is a simple program, but I just can't get it to output the correct numbers.
Here is what I have so far, please feel free to run it yourself and let me know what I am doing wrong. Thanks! Brent
#include <iostream>
using namespace std;
int FindSum(int, int);
int main ()
{
int a, b;
cout << "Enter a positive value (negative value to stop): ";
cin >> a;
b=FindSum(a,b);
cout << "Your numbers added is: "<<b<< endl;
return 0;
}
FindSum(int x, int y)
{ while (x > 0){
cin>>x;
y=x+y;}
return y ;
} | http://cboard.cprogramming.com/cplusplus-programming/11954-very-simple-program-confusing-me-help-please-printable-thread.html | CC-MAIN-2016-07 | refinedweb | 170 | 55.71 |
Components and supplies
Apps and online services
About this project
This project is basically what it sounds like - a smart outlet. This smart outlet can apply to any device that has a plug FOR 120V only! (Targeted mainly at lamps using low amps.) This outlet is an outlet controlled by a 1-channel relay. This project also uses an RTC (real time clock) to determine what time it is and, based on the 24 hr clock, it will either turn on or off (depending on the time) because it actually has predetermined times to turn on and then to turn off. Also, another thing is that this will have a plug coming out of it that has to be plugged into a wall socket!
Link to the library:
IMPORTANT SAFETY INFORMATION!! PLEASE READ!
1) Use a Grounded Cord and Interrupt the Hot Wire
As can be seen in the pictures below, a 3-prong plug is used. The hot (black) wire from the line is connected to the common terminal of the relay module. The normally open (NO) output of the relay is then connected to the brass screw of the outlet. The white wire (neutral) connects to the silver screw and the green (ground) connects to the green screw of the outlet.
2) Use a Relay Module
A single-channel relay module from Elegoo was used to switch the hot wire. This module is identical to the Keyes SR1y module () and contains a flyback diode connected to the control input (for back EMF), a transistor to control the relay coil and a series resistor to limit the current into the transistor. As the relay is only rated up to 10A, either limit the load connected to the outlet, or use a fuse in line with the hot wire. If possible, a single channel relay with an optocoupler would provide additional isolation for the Arduino.
3) Physical Separation
Make sure to mount the relay module in the plastic housing away from the high voltage wires ensuring that the solder side of the relay module faces the plastic housing so that low voltage wiring does not inadvertently come into contact with high voltage wiring if the unit is subjected to shock or vibration.
Image of the wiring on the inside of the smart plug (yours should look like this).
Close-up image of the relay module.
Code
The codeArduino
#include <DS3231.h> int Relay = 4; DS3231 rtc(SDA, SCL); Time t; const int OnHour = 07; const int OnMin = 15; const int OffHour = 07; const int OffMin = 20; void setup() { Serial.begin(115200); rtc.begin(); pinMode(Relay, OUTPUT); digitalWrite(Relay, LOW); //rtc.setTime(21,10,00);//set your time and date by uncomenting these lines //rtc.setDate(26,6,2018); } void loop() { t = rtc.getTime(); Serial.print(t.hour); Serial.print(" hour(s), "); Serial.print(t.min); Serial.print(" minute(s)"); Serial.println(" "); delay (1000); if(t.hour == OnHour && t.min == OnMin){ digitalWrite(Relay,HIGH); Serial.println("LIGHT ON"); } else if(t.hour == OffHour && t.min == OffMin){ digitalWrite(Relay,LOW); Serial.println("LIGHT OFF"); } }
Custom parts and enclosures
Schematics
Author
xXarduino_11Xx
- 14 projects
- 12 followers
Published onJune 27, 2018
Members who respect this project
you might like | https://create.arduino.cc/projecthub/xXarduino_11Xx/smart-plug-7b3e6a | CC-MAIN-2019-43 | refinedweb | 535 | 64.41 |
25 April 2013 17:12 [Source: ICIS news]
HOUSTON (ICIS)--Ferro may look at consolidating its global manufacturing plants as part of its current valuation growth plan, the CEO of the US-based specialty chemical producer said on Thursday.
“It would be consistent to think that further consolidation would occur,” said Peter Thomas during a conference call about the company’s Q1 2013 earnings.
Such consolidations would not occur in the “near term”, Thomas said.
The CEO then pointed out that the company has six plants globally making pigments. “That has to be addressed at some point,” he said.
Ferro is targeting sales growth of 4-5% through 2015 as part of its valuation growth plan, which comes at a time when ?xml:namespace>
Ferro called A Schulman’s bid earlier this year of $6.50/share for the company as a “low-ball” offer. A Schulman has rejected that notion but has said it would be willing to adjust the offer following due diligence investigations into Ferro’s financial | http://www.icis.com/Articles/2013/04/25/9662696/us-ferro-may-look-into-consolidation-of-manufacturing.html | CC-MAIN-2014-41 | refinedweb | 170 | 61.97 |
I'm haveing a bit of an issue with the function SetTextColor()..and i'm pretty much lost. I'm getting the errors of "invalid conversion from", and "too few arguments to function `COLORREF".
Heres my code:
Anyone have a clue what i'm doing wrong?Anyone have a clue what i'm doing wrong?Code:/*Headers for this file*/ #include <windows.h> #include <conio.h> /*Namespaces*/ using namespace std; /*Globals*/ HANDLE m_Screen = GetStdHandle(STD_OUTPUT_HANDLE); HANDLE m_Keyboard = GetStdHandle(STD_INPUT_HANDLE); WORD m_TextColor; WORD m_BackgroundColor; /*Console Colors*/ enum ConColor { ConRed = 1, ConGreen = 2, ConBlue = 4 }; int main() { char *title = "WinCon exp."; SetConsoleTitle(title); SetTextColor(ConRed | ConGreen | ConBlue); DWORD Written; char *write = "Hello World!"; WriteConsole(m_Screen, write, strlen(write), &Written, NULL); getch(); return 0; }
*scratches head*..I'm kind of new to all of this stuff, just so you guys know.. starting out on windows.h stuff today. | https://cboard.cprogramming.com/windows-programming/52932-problems-settextcolor.html | CC-MAIN-2017-09 | refinedweb | 145 | 53.27 |
Send Mails from within a .NET 2.0 Application
Most enterprise applications today need to send mail. This means the platform should provide the necessary support for applications to send these mails. In the case of .NET applications, .NET provides excellent support for sending e-mails through a set of intuitive classes. This article introduces the new ways of sending mails through the System.Net.Mail namespace by showing examples. You also will see the steps involved in sending attachments as part of the mails, as well as sending mails to multiple recipients in the form of CC and BCC lists. Finally, it explains the use of XML and XSL in formatting the bodies of HTML-based mails.
.NET 2.0 Mail Functions
Microsoft made some interesting changes in how you can send e-mail in version 2.0 of the .NET Framework. With .NET 1.x versions, you had to utilize the classes contained in the System.Web.Mail namespace for sending mails. Now, with the release of .NET 2.0, the System.Web.Mail namespace is obsolete and its functionality is now available in the System.Net.Mail namespace. This is a welcome change because the mail functionality was intended to be used for all .NET applications and should not have been under System.Web assembly.
In addition to moving the functionality under the System.Net.Mail namespace, the .NET team also completely rebuilt the implementation of SMTP functionality. There are new classes, properties, and methods that provide an elegant and clean way of performing operations related to sending mails. This long list of new enhancements includes quality improvements, different methods, and asynchronous support out of the box.
Now that you have a general understanding of the support provided by .NET 2.0 for sending mails, let us dive deep into the actual classes contained in the System.Net.Mail namespace.
System.Net.Mail Namespace
The System.Net.Mail namespace contains all the classes required for sending mail from within a .NET application. The classes contained in this namespace work a bit differently from the classes in the Web namespace. Table 1 describes the classes contained in the System.Net.Mail namespace.
Table 1. Important Classes in the System.Net.Mail Namespace
Of the classes that Table 1 lists, MailMessage and SmtpClient are the two core classes that you need to work with to send the simplest of mails.
Implementation
The SmtpClient class handles the actual sending of e-mail. For a simple mail, you can directly pass in the To address, from, subject, and body of the mail to one of the SmtpClient's overloaded send methods. However, this approach works only for simple mails that don't need any advanced formatting, which is normally provided by the MailMessage class.
To have complete control over the mail message, you need to create an instance of the MailMessage class and set its properties to appropriate values. For the purposes of this example, create a Visual C# Class Library project named MailServer using Visual Studio 2005. Once the project is created, rename the default class to MailService. To the MailService class, add a method named SendMail and modify its code to look as follows (an example of how to use the MailMessage class to create a mail message and then send it using the SmtpClient object):
public void SendMail(string from, string to, string subject, string body) { string mailServerName = "smtp.test.com"; try { //MailMessage represents the e-mail being sent using (MailMessage message = new MailMessage(from, to, subject, body)) { message.IsBodyHtml = true; SmtpClient mailClient = new SmtpClient(); mailClient.Host = mailServerName; mailClient.UseDefaultCredentials = true; mailClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis; //Send delivers the message to the mail server mailClient.Send(message); } } catch (SmtpException ex) { throw new ApplicationException ("SmtpException has oCCured: " + ex.Message); } catch (Exception ex) { throw ex; } }
In the above code, at the time of creating an instance of the MailMessage class, you pass in the From, To, Subject, and body of the message as arguments. Then, you set the IsBodyHtml property to true to indicate the type of mail you want to send. After that, you create an instance of the SmtpClient object and then set its properties, such as Host, UseDefaultCredentials, and DeliveryMethod, to appropriate values. Finally, you send the mail using the Send method, which sends out the mail in a synchronous manner. Note that at the time of sending a mail, if an SMTP exception occurs, it will be handled in the SmtpException catch block. All other exceptions are caught by the generic Exception block. Also note that in the above method, you directly set the To property of the MailMessage object to the supplied value. If you are sending mails to multiple recipients, you need to create that many instances of MailAddress objects and add them to the MailMessage.To property, which represents a collection of MailAddressCollection objects.
Now that you have created the SendMail method, it's time to call that method from a client application.
There are no comments yet. Be the first to comment! | http://www.codeguru.com/csharp/csharp/cs_misc/e-mail/article.php/c9957/Send-Mails-from-within-a-NET-20-Application.htm | CC-MAIN-2015-18 | refinedweb | 839 | 57.16 |
Hello all
I am a student and I am new to Java. I have created a simple Java program. We have been given a package to import into the program we have developed. The classes of the package are stored in a folder called "pack" which is placed inside project folder called "tictactoe". The example program we were given imports the package as follows and it works fine.
import pack.*;
Is it that simple or do I need to do more.
It gives me the error "The import pack cannot be resolved"
Thanks
Cross posted
db
Yes but are these not two different websites?
Firstly, you have to include jar file that containing your pakage in your project. In Eclipse is setting build path.
Then is using import statement to import the needed class.
By the way, I recommened that you shouldn't import like that : import package_example.*
Should importing exactly what classes you need, e.g : import package_example.Class_A;
Thank you Phillip
The package "pack" is just a folder containing files with .java and .class extensions. We are asked to create a program that contains four classes which should use the files inside the folder called "pack" by importing the "pack" i-e
import pack.*;
It does work for the example program given by the teacher but not for me. I am sure I am missing something. Could you please tell me the the way it is set in the build path?
Hi gulHK,
If you having java source code files, just copy them into your package.
e.g : in package 'pack' already contains java source code like this : LibraryA.java, then just copy this file into your package. And using import statement like this in your code : import your_package.LibraryA;
You can set build path in Eclipse , if the classes you intend to 'import' have already packaged in jar file.?
Why you have to need to import class files?
If you already having java files of those classes, just copy them to your program and use.
I have just tried the program without the .class files and copying only the .java ones and it worked. You were right and thanks a ton for that
Hi gulHK,
You are welcome.
Originally Posted by gulHK?
Hi gulHK,
You dont need to import java class for using, because that the class that be used in your program ( e.g Main.java ) is located the same package (folder) with Main.java. If it's belong to another package, you have to import in Main.java to use.
Forum Rules | http://forums.codeguru.com/showthread.php?530549-Java-POST-help-with-binary-data&goto=nextoldest | CC-MAIN-2014-15 | refinedweb | 427 | 76.01 |
At our recent Unite event in Berlin, we shared an update talk on our roadmap. We aim to do this more regularly, as we know it’s important to help you plan ahead. We know that seeing what features we have in production and understanding our goals with Unity as a tool is essential to making sure you can scope your work this year, and in the years to come. Thanks to all of you who continually give us great feedback on our roadmap and help make Unity better.
For an ongoing view of the Unity roadmap, check out the dedicated Roadmap page.
Watch the Unite Berlin Roadmap Talk
For those of you who missed it, here’s the video from the event. Note that whilst we couldn’t cover every single thing in development or at the research phase, the roadmap we shared is fairly complete up to 2019.1 (ETA around March next year).
Download the deck as PDF
Want a closer look at the deck? Grab the PDF version of the deck here. Please remember that dates and version numbers were correct at the time of presentation at Unite Berlin 2018.
Give us your Feedback!
We always want to hear more of your wants and needs here at Unity! Tell us your feelings on the roadmap we shared in the video above, and please give us a heads up on anything we missed. Use the comments below to give us your feedback.
Etimesgut Mobilya九月 12, 2018 10:58 上)
BW九月 5, 2018 9:17 下午
Subsurface scattering and volumetric light improvements?
Mitchell八月 29, 2018 9:46 上午
The new GUI looks nice and clean, nothing useless like gradients and no longer looking like some basic program designed by a beginner programmer from the early 2000’s on windows XP.
One of the main things I kept wanting to go back to Unreal was that their UI was a lot better, but now with Unities new UI has become a lot more clean, I’ll stay.
As I like to say, K.I.S.S. Keep It Simple, Stupid.
Emre Yılmaz七月 27, 2018 8:38 上午
I’m actually more stressed over an outright absence of intelligibility, I mean if everything is level, I can’t tell a content foundation from a catch or an information field. Which resembles absolute opposite to plan. The “monstrous jumbled” plan had in any event the advantage of having “affordances” their frame took after the capacity, expelling mess should come to this detriment. Additionally it’s not present day nor decline millennial stuff, level outline is extremely old and is a get back to the Bauhaus upset. Can you help me for 3D model this website
Saaamoth七月 24, 2018 2:10 下午
I
Saaamoth七月 24, 2018 2:18 下)
optimise七月 22, 2018 6:31 下午
For terrain system, when updated Terrain shipped I hope it’s highly optimized for mobile platform too. If there are some terrain features that’s heavy for mobile platform, it will have the option to remove it.
optimise七月 22, 2018 6:24 下午
One more thing I want to mention is although it’s really nice that Unity put a lot of effort into Machine Learning but I really hope at least there is Behavior Tree AI tool for game development will happen.
Bob Jones七月 20, 2018 9:38 上午
My goodness please tell me we are getting GPU Lightmapper in 2018.3. It’s been showcased in videos ever since 2017. It was supposedly supposed to be in 2018.2, and still no news.
hippocoder七月 18, 2018 6:20 下午
Nice stuff! The roadmap is like that little notice you see in corner shops “please don’t ask for credit as refusal often offends”, or the writing on the wall :)
Stops people trying to molest Unity staff over random comments in videos (usually dates or whatever).
Steve Watkins七月 19, 2018 1:42 下午
Some people do have strange attitudes towards the inevitable development timescale slippages, as if anything on this front can really be guaranteed until the feature is really ready. In theory the roadmap already has features that enable the realities of such things to be clearly presented (ie the colour coding). I only go on about such things because it would be a terrible shame if Unity were too afraid to provide timely and accurate roadmap information, with features that were more at risk of slippage, because of a vocal minority and their unrealistic expectations.
Will Goldstone七月 20, 2018 1:43 下午
Hey Steve, you make a great point but we don’t worry about not being transparent – its more important that disappointing people because everyone in development on our side and your side lives in the real world, we’re doing our best and we will have a better way to represent this on the website soon as we can, cheers for the comment.
Lief七月 17, 2018 9:45 上午
Do I need to rewrite my code for Textmesh Pro or can I just let Unity update my code when textmesh pro will replace UI text and UI Dropdown? Will they replace those component? I tried 5 minutes to replace UI text with Textmesh Pro it was easy enough but I don’t need the new features of Textmesh Pro and it’s a pain to replace every code for Textmesh Pro.
Mobile->New Input system (touch)…. What is this? Will it require changes to my current code? I still use the old Input Manager for both PC and Mobile build and I get my x and y coordinates from a virtual joystick for mobile movements. Do I need to change anything?
Feedback: I don’t know if I like the new Editor design. I think the current editor design is really easy to use and intuitive, I think it’s one of the main reason that I started with Unity3d instead of others game engines. Just remember to keep it simple and intuitive.
Will Goldstone七月 17, 2018 11:30 上午
Hey Lief, afaik there’s no need to replace any code for TextMesh Pro – we’ve simply migrated it to being directly integrated, you may have a script updater feature later in the release cycle once you no longer need a namespace but that should be it. If you have any issues, ping me on twitter @willgoldstone.
Lief七月 18, 2018 10:50 上午
Good thank you.
If you know something about the New Input system (touch) in the roadmap for 2018.3 it would be great
optimise七月 17, 2018 9:25 上午
I really hope Unity can look into iOS and Android able to update game code dynamically instead of just art asset. This problem still remain until now and I still haven’t hear any official answer from Unity.
Will Goldstone七月 17, 2018 11:49 上午
This is something we are actively working on – streaming assets etc – take a look at the talk about the Addressables system from Unite Berlin here – – we didn’t have time to fit everything into the roadmap talk but we should have had more on this so apologies for that.
P7七月 17, 2018 2:15 上午
The only thing I’m disappointing in is the style of that new GUI layout… like where the hell are the gradients….’revolutionary design’? you what? flat color background, with text dumped ontop is about as revolutionary as the winblows 10’s garbage interface with it’s flat color square border fat padding idiocracy looking ‘basic’ kindergarten color design.. for noobs without taste.
Anyway seriously add some gradients, I know some subtle beveling around borders is way too much to ask, but having tabs without any soft of gradient color background, and every other panel option without any gradient graphics in the background to seperate different sections really helps… right now it’s all just text, it’s about as crap as the modded theme you can for Unity.. it’s all just awful looking and why the default Apple styled light/dark gui graphics just looks much better…. though in need of an update.. instead you’ve thrown out the graphics, depth etc for this current trend of devolutionary lazy millennial garbage design.
Mykhaylo七月 17, 2018 8:23 上午
I really like the style that Windows has adopted since Windows 8. I did not like the 10th style for quite some time until I had to revert my Windows back to Windows 8 and then I realized that 10th design was actually better than 8th and I don’t think it’s a “used to” reason. So far I quite enjoy what I see in their UI design but I can understand that different people view the world differently and there are no two people sharing the same taste.
Will Goldstone七月 17, 2018 11:29 上午
Thanks for your comment, not sure we used the term revolutionary – we’re just out to modernise things here and make them as tactile and useful for you as possible. The current approach and thinking in software design (yes, i’m not using the term ‘trend’ here deliberately) is to de-clutter and remove cognitive load as you navigate interfaces, and that is what we’re hoping to do with the work expressed here. Naturally I too nostalgically look back at the days of wooden veneers, gradients and Winamp skin packs, but sometimes you just have to try new things. We haven’t tried new things in terms of interface design in a long time – that’s our bad, so please bear with us whilst we do what we can to rectify that!
Kharil七月 18, 2018 5:27 下午
I’m personally more worried about an absolute lack of readability, I mean if everything is flat, I can’t tell a text background from a button or an input field. Which is like antithesis to design. The “ugly cluttered” design had at least the benefit of having “affordances” their form followed the function, removing clutter should come at this expense. Also it’s not modern nor degenerate millennial stuff, flat design is one century old and is a call back to the Bauhaus revolution.
Bring back clear affordances
Arthur Brussee七月 16, 2018 11:25 下午
I really love these roadmap sessions. Similarly, the roadmap site is a great initiative: . But what I don’t understand, is why huge items from the roadmap sessions are not on the roadmap website. Large important releases are sometimes not on there even just before release.
Is there a plan to introduce a good way to stay up to date with the unity roadmap? It still requires scouring the unity forum, and keeping an eye on unites at the moment.
Steve Watkins七月 17, 2018 8:33 下午
Yeah I dont undersatnd the obvious, large omissions from the roadmap compared to what is said at Roadmap talks either. I’ve tried asking on the forums and on the youtube comments and I never get a response. Some people tell me that I should read something into these omissions, eg treat stuff in the roadmap talks as being less certain than stuff that actually makes it onto the official roadmap, but I dont like that approach or assumptions. Especially as some things missing from the roadmap page have already been delivered, such as the preview build that has the new prefab system in it.
Steve Watkins七月 17, 2018 8:52 下午
Oops, correction to what I said there. I found the Improved Prefabs stuff in the Development section, although I’m not sure why it isnt in the Feedback build section instead! And I’m not sure why Terrain stuff isnt listed at the moment, given what is said about that elsewhere in the comments to this blog post! New VFX system another obvious omission from the Roadmap compared to the Roadmap talks.
Will Goldstone七月 18, 2018 3:54 下午
Hey Arthur and Steve, honestly, we just have to get better and keeping on top of things, we’re in the midst of a mix of manual and automated processes that result in the roadmap page you see – we’re reviewing it at the moment though, and seeing what needs to change. Bear with!
Steve Watkins七月 19, 2018 1:36 下午
Thanks very much for the reply! Its great to know you are working on this. I only made a bit of a big deal about it because some on the forums were suggesting that we should read between the lines when it comes to such roadmap omissions (eg assume that stuff not mentioned was a sign that such features were more at risk of delays), and I had no intention of doing that. I have a small obsession with quality technical information communication, but I know it isnt always easy to get this stuff just right.
Trilo Byte七月 16, 2018 6:29 下午
Please tell me you’re not going to make us have to wait until 2018.3 (or later?) to get the terrain changes needed so we can get Speedtree 8 working? IMO your terrain team needs to work more proactively with Speedtree, version 8 has been available for 6ish months on Unreal Engine and more than a year for Lumberyard.
Arisa Scott七月 16, 2018 11:17 下午
Hi Trilo, Speedtree 8 integration will be coming with 2018.3. Thanks for your feedback. It is our desire to get support out as quickly as we can. Happily the terrain team has grown over the last 6 months which will aid faster turnaround.
Thall七月 17, 2018 4:11 上午
Can we PLEASE have this?
Will Goldstone七月 17, 2018 11:32 上午
Hey Thall, that’s awesome – I definitely wanna see if we can make some new Standard Terrain Assets to ship with the new features. This is pretty much just shader merging trickery anyhow, so we should be able to build something like that to share with you. I’ll look into it and see what’s possible. Thanks for the suggestion!!
Ionut Tudor (RO)七月 23, 2018 8:59 下午
Hey unity staff, could you please buy Gaia and integrate into Unity’s new terrain system? i have not made any game yet and its very hard to afford basic components like a full terrain system. | https://blogs.unity3d.com/cn/2018/07/16/stay-up-to-date-with-the-unity-roadmap/ | CC-MAIN-2019-35 | refinedweb | 2,389 | 66.67 |
Originally posted by Michael Imhof:
I thought, a labelled break is working like a "goto". So after calling
"break lab" it breaks the loop and returns to the label.
Originally posted by anindam bhattacharaya:
G'day
I have a problem getting to understand this code..
Originally posted by JayaSiji Gopal:
public class Test {
static int total = 10;
public static void main (String args []) {
new Test();
}
public Test () {
System.out.println("In test");
System.out.println(this);
int temp = this.total;
if (temp > 5) {
System.out.println(temp);
}}}
The compiler reports an error at line 2
The class will not compile
The value 10 is one of the elements printed to the standard output
The compiler reports an error at line 9
The class compiles but generates a runtime error
i answered the 4th option,but the correct answer is 3.
i answered 4th, bcos static variables cannot have a this reference.
plz correct me, wht is wrong?
Originally posted by siva kumar:
What are the differences bw RequestProcessor and ActionServlet.
The advantages of RequestProcessor over ActionServlet.
Originally posted by manish ahuja:
What I intended to ask from my post was Cant we have caching without resorting to Singleton
Say I use the caching part of the code mentioned in the original post in Scenario1 & force it on scenario2.
Wont I be able to still use caching
In short do we have to have singleton to enable caching or I can have caching even without being a Singleton class
Originally posted by manish ahuja:
Hi All
I was going through Sun BluePrints where they show 2 types of service locators
quoting from the blue prints
***************************************
The Java Pet Store sample application, v1.3.1 has two service locators: a Web-tier class ServiceLocator , and an Enterprise JavaBeansTM (EJB) tier class, also called ServiceLocator . Both classes manage lookup and caching of enterprise bean home interfaces, JMS and database connection factories, and environment entries within their respective tiers. The only difference between them is that the Web-tier class is a singleton, and it caches the objects it looks up. The EJB-tier class is not a singleton, and does not cache.
****************************************
Here are the links to the code piece
1) the 1 that looks up as well as caches
This is synchronized. My question is does it have to be that way. In the above code for caching was Singleton necessary
2) the 2nd one looks up but does not cache and is neither a Singleton
Do post your viewpoints on the same
Rgrds
Manish | https://coderanch.com/u/24885/Aneesha-Singh | CC-MAIN-2020-40 | refinedweb | 423 | 60.35 |
Introduction: Illuminated Christmas Tree Ornament [WiFi Controlled]
In this Instructable i'll describe how to build a illuminated Christmas tree ornament, which can be controlled over WiFi. Use your favorite browser (computer or smartphone) to connect to your Christmas tree ornament. And select the colors, speed and pattern.
The Christmas tree ornament has it's own web server. And all code runs on a build-in Wemos/ESP8266 board. Everything else it requires is a 5 Volt (USB) power source and a WiFi connection.
This Instructable contains diverse steps. It starts with three code examples. The first example is a simple Arduino sketch, in Autodesk Circuits, using a NeoPixel ring. This example is the base of this build. Next step is a simple webserver using a Wemos board. The third code example explains how to execute functions at specific time intervals.
After these coding examples, it's time to create the design. This is based on a regular icosahedron. This is a completely symmetrical geometry with 20 sides. The design was created in Fusion 360, and then printed using a 3D printer.
After the assembly follows the final code. This is a combination of the three examples from the beginning of the Instructable.
This Instructable is about creating a Christmas Tree ornament. But the web interface is not limited to Christmas ornaments. It can be used for many other projects. In fact, Anything that can be controlled by an Arduino can be controlled over WiFi.
Step 1: Required Materials
Required materials:
- Wemos D1 Mini Pro ($5) or Wemos D1 Mini ($3)
- WS2812b LED strip 30/meter IP30 ($3 for 1 meter with 30 Leds)
- Micro USB cable (local store, about $2)
- Breadboard wires
- Transparent glue (hobby store)
- Glitter dust powder (hobby store)
- USB power supply (e.g. Ikea Koppla) or other 5 Volt power supply.
Total material costs are about $10 for a single Christmas ornament.
Use a decent USB power supply. The leds use maximum 60 milliAmpere each. 20 LEDs at full power require 1.2 Ampere (6 Watt). I'm using an Ikea Koppla USB power supply. It has 3 ports and can deliver 3.2 Ampere at 5 Volt.
Step 2: Autodesk Circuit: NeoPixel Ring Example
Building something with an Arduino and WS2812 LEDs is really simple. It might look intimidating, if you've never worked with an Arduino before. Some programming and/or electronics experience makes it more easy. But it isn't really that hard.
And it's not necessary to purchase an Arduino if you want to try this out. There are websites where you can simulate an Arduino. One of them is Autodesk Circuits. I've made an Arduino example using a NeoPixel ring. This pixel ring example, is the base of this Christmas ornament.
The code looks simple. But it shows many of the possibilities of coding an Arduino:
It uses an external library (Adafruit NeoPixel). So I don't have to worry about changing the LEDs colors. All I have to do is use the library functions.
The code defines the RGB values of 12 colors in 3 arrays. This are the 12 colors, used by the web interface for controlling the led strip.
There is also a self-defined function. The setColor function can be called from anywhere within the program.
#include <Adafruit_NeoPixel.h> #define NUM_PIXELS 16 int D2 = 8; Adafruit_NeoPixel pixels(NUM_PIXELS, D2, NEO_GRB | NEO_KHZ800);}; void setColor(int R, int G, int B) { for (int i = 0; i < NUM_PIXELS; i++) { pixels.setPixelColor (i, R, G, B); } pixels.show(); } void setup() { pixels.begin(); pixels.show(); } void loop() { for (int j = 0; j < numColors; j++) { setColor (R[j], G[j], B[j]); delay (1000); } }
This code contains one array with 12 colors (numbered from 0 to 11). I've chosen 12 colors, because the final code contains one button for each color:)
You can change the colors if you like, by altering the RGB values. More colors codes can be found at Wikipedia.
_______________________________________
For anyone who has never worked with an Arduino, I can recommend the Instructable Arduino Class:
"This class will introduce you to the Arduino world. You'll learn the basics, build your first project, and so much more. Each lesson builds on your skills, infusing new knowledge and techniques along the way.
And most of these classes can be made with Autodesk Circuits.
Step 3: Hello World
After programming an arduino with ws2812 LEDs, it's time to create a simple web server. This requires a Wemos (with an ESP8266) board, containing a WiFi adapter. The Wemos can be connected to your Computer using an USB cable. There is no need for additional USB to serial adapters. This is the advantage of a Wemos above an ESP8266-12.
The Wemos can be programmed using the Arduino software. But it requires adding additional boards with the Boards Manager. This is described in the Wemos documentation.
After these steps it's possible to select a Wemos board in the Arduino programming environment. Select the Wemos board (+ corresponding com-port) and copy the following code:
#include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266WebServer.h> #include <ESP8266mDNS.h> MDNSResponder mdns; // network credentials const char* ssid = "ssid"; const char* password = "password"; String webPage = "<h1>Hello World</h1>"; ESP8266WebServer server(80); void setup() { Serial.begin(115200); delay(500); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.println("."); } Serial.print("IP address: "); Serial.println(WiFi.localIP()); server.on ("/", [](){server.send(200, "text/html", webPage);}); server.begin(); Serial.println("HTTP server started"); } void loop() { server.handleClient(); }
Alter the network credentials before compiling and uploading the code.
This is a very simple web server. The Wemos will connect to the WiFi network and start a web server with only one page. Use the serial monitor to obtain the IP address of your webserver.
Step 4: Wiring
This instructable requires some soldering. But this is minimized by using a WS2812b led strip.
Solder the male headers on the Wemos board. Only the D2, +5 Volt and ground pins are used. This Means that the headers only have to be soldered on one side of the board.
Solder 3 breadboard wires on the led strip (Ground, signal and +5 Volt).
Remove the plastic from the USB connector. There is no room for such a connector. Add 2 wires to the usb cable: one to the +5 and one to the ground wire. These are used for directly powering the Leds. Don't forget to insulate these wires.
Connect the +5 Volt wires from the USB cable and led strip. The same for the 2 round wires. Connect the signal wire, from the Led strip, onto the D2 pin on the Wemos board. Finally connect the usb connector to the Wemos board.
There is no ground wire connected to the header on the Wemos board. This ground pin is directly connected to the usb connector. Which is connected to the additional ground wire.
Step 5: Timing Example
In my first Arduino neopixel code example (NeoPixel ring), color changes are made within the main loop. This requires a delay in the main loop, or the change of color will go too fast. During this delay the Wemos board just waits, and doesn't execute any other code. Except for background processes, e.g. handle the WiFi network connection.
The final product will run a webserver to give control to the LEDs. Because of this there should be no waits inside the code, because this will give a non-responsive web-interface.
In this example the LEDs are controlled by an internal timer. This osTimer is defined by the os_timer_setfn function, and then armed with the os_timer_arm function. The used value of 1000 is in milliseconds. By using this value, the Wemos timer will execute the timerCallback procedure every second. This procedure increases the color value, and changes the colors of the Leds. And all these actions are done outside the main loop.
Beware that the code inside the osTimer must be very short. The code must be completed before the next timer is fired.
#include <Adafruit_NeoPixel.h> #include <user_interface.h> #define NUM_PIXELS 20 Adafruit_NeoPixel pixels(NUM_PIXELS, D2, NEO_GRB | NEO_KHZ800); os_timer_t osTimer;}; int vColor = 0; // start with color 0 void setColor(int R, int G, int B) { for (int i = 0; i < NUM_PIXELS; i++) { pixels.setPixelColor (i, R, G, B); } pixels.show(); } void timerCallback(void *pArg) // interrupt os-timer<br>{ vColor++; if (vColor>=numColors){vColor=0;} setColor (R[vColor], G[vColor], B[vColor]); } void setup() { pixels.begin(); pixels.setBrightness (16); // reduce power usage pixels.show(); os_timer_setfn (&osTimer, timerCallback, NULL); os_timer_arm (&osTimer, 1000, true); } void loop() { delay (1000); // nothing to do }
This code also introduces a function called setColor. This function accepts 3 values, these are used to change the color of all the the LEDs.
Step 6: Regular Icosahedron
There are Christmas tree ornaments in many different shapes. While I was looking for a design, i came across some geometric forms. And one type of geometry caught my attention: A regular polyhedron. They are completely symmetrical. This makes it perfect for a Christmas ornament. There are only five known types:
- Triangular pyramid (4 sides)
- Cube (6 sides)
- Octahedron (8 sides)
- Dodecahedron (12 sides)
- Icosahedron (20 sides)
I've choosen for the icosahedron. It has the highest number of sides. There will be one WS2812 LED on each side, with 20 LEDs in total.
The use of WS2812 LED strips limits the size of the geometry. The distance between the LEDs is 1.3 inch (30 LEDs per meter). This equals the upper limit for the sides of each equilateral triangle. After creating a paper prototype, I came up with a size of about 3 inch (75 mm). This gives just enough room for the Wemos controller and 20 LEDs.
Step 7: Autodesk Fusion 360
Drawing a regular icosahedron starts with 3 rectangles on each axis. These must be golden rectangles. A golden rectangle is a rectangle whose side lengths are in the golden ratio (approximately 1.618). We can calculate the sides for a golden rectangle with a diagonal of 75 mm (3 inch). Making use of the Pythagoras's theorem, gives 65 x 40 millimeter for the sides.
Every single corner of the rectangles is a corner of 5 triangles.
Next step is to create 20 triangles (using a plane through 3 points). And extrude them to the inside. Create a new fourth body with these 20 triangles. Each triangle is adjusted, so that the LEDs can be placed behind.
All Fusion 360 files are available for download on my autodesk drive: Icosahedron, Part 1 and Part 2.
Step 8: Printing Parts
I've printed the design 3 times. Two times with the original Up filament (white), and one time with non regular filament (blue).
Remove all support material. And make sure the LEDs fit in the holes. Use a sharp knife and sand paper to remove all irregularities. It is intended to cover the entire Christmas ornament with glitter. Therefore any irregularities will be visible in the end product.
Step 9: Assembly
Before gluing the LEDS, draw a single line for the path of the LED strip. This line may not cross itself.
Start with gluing the LEDs, inside the large 3D printed part. Begin with the final LED at the end of the strip. I've used a hot melt glue gun. Carefully bend the LED strip while processing.
I used two LED strips in my first version. One with 5 LEDs and one with 15 LEDs. But it is quite possible to use a single LED strip of 20 LEDs. This saves some soldering.
Connect the +5 and ground wires from the LED strip to the USB cable. The signal cable is connected to the D2 pin on the Wemos board. The ground is internally connected. Don't forget to check the LEDs before closing the Christmas ornament.
Put some glue on the connectors, so they don't get loose. Place the Wemos board inside the Large 3D printed part. Make some room for the USB cable throughput, and glue everything together.
Step 10: Webserver
This Arduino sketch file contains all code for a web server with a Wemos board. Alter the "ssid" and the "password" variables before uploading the code.
About the code
Some parts of the code require some explanation:
#include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266WebServer.h> #include <ESP8266mDNS.h> #include <Adafruit_NeoPixel.h> #include <user_interface.h>
All libraries used in this Arduino sketch.
#define NUM_PIXELS 20 Adafruit_NeoPixel pixels(NUM_PIXELS, D2, NEO_GRB | NEO_KHZ800);
There are 20 LEDs. And these LEDs are connected to pin D2 on the Wemos board.
int R[13] = {255,255,227,255,255,128,075,000,127,000,127,255,000}; int G[13] = {194,165,066,000,000,000,000,000,255,255,255,255,000}; int B[13] = {000,000,052,000,255,128,130,255,212,000,000,000,000};
These are the 12 colors defined (color 0 to 11), these are used for the LEDS. And the corresponding HEX values are used for the buttons. There are 13 values in this array. The last value in the array turns the LED off (#000000 = black). You can change these colors if you want.
String buttonColor [2] = {"white", "black"}; boolean ColorState [13] = {1,1,1,1,1,1,1,1,1,1,1,1,1}; // initial colors
All 12 buttons have a "State". When a button has the value "True", then the corresponding color is displayed by the LEDs. By pressing a button, the state of this button changes. This also changes the text color of this button (e.g. from black [on] to white [off]).
int waitTimes [16]= {50, 100, 150, 200, 250, 500, 750, 1000, 1500, 2000, ... int waitTime = 5; // default values
There are two buttons to change the timer value ("faster" and "slower"). The default waitTime value is 5. This value gives a timer interval of 500 milliseconds.
int nextColor (int lastColor) { foundColor = numColors; // nothing found return value countColors = 0; // count number of searches inside the loop do { currentColor += 1; countColors += 1; if (currentColor>numColors) {currentColor=0;} if (ColorState[currentColor]) {foundColor=currentColor;} } while (currentColor != lastColor && foundColor == numColors && countColors < numColors+1); return (foundColor); }
This function finds the next color to display using the colorState array. It starts at the array position with the number lastColor. And returns the next index-value in the colorState array with the value 1.
An example: The following array has color 2-7 turned off (white text). Executing this function with the value 0 returns 1. Using this function with the value 1 returns 8. This is the next color which has colorState "True".)
The colors are always displayed in a fixed order. When all 12 colors are off, all LEDs are turned off (value 000000).
// interrupt os-timer void timerCallback(void *pArg) if (!buttonSparkle) { // Sparkle Off = Blink } else { // Sparkle }
There are 2 modes of operation: Sparkle and Blink. And they each have a different code path inside the OS-timer.
The blink mode has the easiest code. It gets the next color by calling the nextColor function. Then all LED colors are changed to this color.
The sparkle mode differs a lot. It always starts with the first available color in the ColorState array. And then the nextColor function is called for each LED. Increasing the starting LED value, gives a sparkling effect.
void showPage() { webPage += "<p><a href=\"socketAmb\"><button style=\"background:#FFC200;... webPage += " <a href=\"socketOra\"><button style=\"background:#FFA500;... webPage += " <a href=\"socketVer\"><button style=\"background:#E34234;...
This function displays/refreshes the web page. There is only one web page in this sketch. The button colors are hard-coded. And these colors match the R-G-B-arrays.
void setup(void){ server.on ("/",[](){showPage(); }); server.on ("/socketAmb",[](){ColorState [0] = !ColorState [0]; showPage();}); server.on ("/socketOra",[](){ColorState [1] = !ColorState [1]; showPage();}); server.on ("/socketVer",[](){ColorState [2] = !ColorState [2]; showPage();});
The setup part contains the first executed code, after starting the Wemos. It initializes the neopixels, WiFi connection, OS timer and the web server.
Pressing a button on this page results in executing some code. For example: The first button on the web page (amber) has a reference (href) to "socketAmb". Pressing this button executes the code in the server.on part for "socketAmb). This piece of code alters the colorstate in the array for the first color (which is amber).
The LED colors are changed by a timed function. The colors don't change immediate.
void loop(void) { server.handleClient(); }
The only thing in the main loop is to take care of the web server. All other processing is done by the timer function.
Step 11: No WiFi Version
The following Wemos code can be used as an example for a Christmas ornament without WiFi.
This code makes it possible to use an arduino, instead of a Wemos (ESP8266). The arduino code is available at circuits.io (WS2812 Matrix Example). The main difference in the code is the port-name (port 8 instead of D2).
#include <Adafruit_NeoPixel.h> #define NUM_PIXELS 20 Adafruit_NeoPixel pixels(NUM_PIXELS, D2, NEO_GRB | NEO_KHZ800); int R[14] = {255,255,227,255,255,128,075,000,127,000,127,255,000,255}; int G[14] = {194,165,066,000,000,000,000,000,255,255,255,255,000,255}; int B[14] = {000,000,052,000,255,128,130,255,212,000,000,000,000,255}; int NUM_ROWS = 20; // led 01 02 03 04 05 06 07 08 09 10 11 14 13 14 15 16 17 18 19 20 int ColorMatrix [20][20] = {}}; int brightValue = 10; int brightMax = 16; // brightness (1..16) void setup(void) { pixels.begin(); } void loop(void) { for (int j = 0; j < NUM_ROWS; j++) { for (int i = 0; i < NUM_PIXELS; i++) { pixels.setPixelColor (i, R[ColorMatrix [j][i]]*brightValue/brightMax, G[ColorMatrix [j][i]]*brightValue/brightMax, B[ColorMatrix [j][i]]*brightValue/brightMax); } pixels.show(); delay (50); } }
The order of the LEDs is dependent on the order of gluing. My ornament has the following order:
- Upper 5 LEDs: 4, 5, 6, 7 , 8 (counterclockwise).
- Lower 5 LEDs: 11, 12, 13, 14, 15 (counterclockwise)
- Middle 10 LEDs: 1, 2, 3, 10, 9, 16, 17, 18, 19, 20 (clockwise)
The number in the ColorMatrix corresponds to a R/G/B-color (see the first example for the colors). There are 20 rows with 20 LED colors. The main loop starts with the first row (this is row number zero in the code). And writes the 20 values to the LED strip.The show-function changes the colors.
Then the code waits 50 milliseconds, before to continue with the next row in the matrix. There is no timer in this example. This makes it possible to execute this code with an arduino.
Step 12: Decoration
The last step is decorating the Christmas ornament. First remove any excess glue, and all other irregularities.
It is intended to cover the entire Christmas ornament with glitter. Also, the LEDs. These provide enough light to remain visible.
Cover the 3D printed part entirely with glue. Use transparent glue of good quality. Sprinkle the glitter dust over the whole ornament. Use a box to collect the excessive glitter. This glitter can be reused. Continue until the entire ornament is covered with glitter.
Step 13: Merry Christmas
In this final step, I wish everyone a merry Christmas.
GosseAdema
After some headscratching I got this working. Being tired and and fiddling is not the best. xD Anyway, only problem I have now with testing on a breadboard is that it blinks for a few seconds and then just stops for 20-30 seconds and then starts to blink again. Some of the buttons also doesn't seem to be doing very much...? I wonder if I made a mistake, because some of the libraries you mention had multiple choices when installing via Arduino SDK app.
another question... I ordered the WS2812b LED strip 30/meter IP30 per your list. you said you used 20 LED's. Does that mean you just cut the last 10 off the strip?
Yes, or you change code for 30 leds and make a Christmas Ornament with 30 leds
This is great, but i am missing the program for android or am i looking over it.
All code runs inside the Christmas Ornament. There is a webserver running on the Wemos board. You can use any recent browser to select your colors.
How are you controlling multiple ornaments, such as in your first video?
The blue one (on the left) contains the code without WiFi. The other 2 have WiFi enabled. Only one is controlled by WiFi in the video. The other one (on the right) uses an infinite loop, but has WiFi enabled.
I know that these have wifi on them and a USB cable that you use to hang it in the tree.... can it be programmed over wifi?
Yes it works, and now i know every bal has his own ip ofcource.
Great to see that you've made this with individual ws2812 Leds. I still have 25 of these, but I used a led strip for this Instructable. I thought nobody would solder 60 wires for a Christmas tree ornament.
I'm having trouble finding the difference between a Wemos mini D1Pro and the non-pro... any insight would help.
Looking to build a few of these this year as presents for next year.
You can use the D1 mini or the D1 mini pro. The main difference is the amount of memory.
Great job!
Love it for its multiple ideas. I've voted for it in all three contests!
Kudos!
This looks awesome. Brings many ideas to mind. Thanks for sharing!
Great....last I was at a concert and we had a bracelet that changed: color and I did not know how it worked but now I know it .. :-) I'm going to try this to...
Excellent project with great detail of the mechanical, electronics and sketch.
There is a problem with the links to the Fusion 360 "Icosahedron, Part 1 and Part 2" links. "Icosahedron"is good. "Part 1" also points to "Icosahedron" and "Part 2" actually points to "Part 1". There is no link to "Part 2".
You got my votes
Thanks, I changed the links.
Will try this for next year maybe is close to Christmas now but looks like a nice project
Awesome project! Exactly what I was looking for!
Great project. Impressive!
Great instructions and Merry Christmas to you! Big thumbs up!
Great Project
Very nice! You have my vote too! :)
This is awesome!! Definitely going to make it one of these days!
And Voted for the contests. | http://www.instructables.com/id/Illuminated-Christmas-Tree-Ornament-WiFi-Controlle/ | CC-MAIN-2017-30 | refinedweb | 3,783 | 68.87 |
This is the sixth tutorial on how to use Voice APIs with ASP.NET series. In the previous tutorial, we learnt how to forward a call via voice proxy with ASP.NET Core. In today's tutorial, we will learn how to set up a conference call so multiple people can join the same call.
Learning objectives
In this tutorial, we will:
- Create an ASP.NET Core app.
- Use NancyFX with ASP.NET Core.
- Create a Vonage voice application.
- Create and return NCCOs.
- Run and test the code using Ngrok.
Prerequisites
- Visual Studio 2017 or higher.
- A project that was created configuration is created successfully, we can move on to setting up a conference call.
Building a Conference Call
When a user calls the Vonage number, the Vonage Voice API will make a request to the application to figure out how to respond using a Vonage Call Control Object (NCCO).
The user will be greeted then will join the conference call. create a route to
/webhook/answer which will respond with the
ncco returned by
GetConferenceCallNCCO()
using Nancy; using Vonage.Voice.Nccos; namespace NexmoDotnetCodeSnippets.Modules { public class ConferenceCallModule : NancyModule { public ConferenceCallModule() { Get("/webhook/answer/", x => { var response = GetConferenceCallNCCO(); response.ContentType = "application/json"; return response; }); Post("/webhook/event", x => Request.Query["status"]); } private Response GetConferenceCallNCCO() { var ncco = new Ncco(); ncco.Actions.Add(new TalkAction { Text = "Hello. You will now be added to the conference call.", Language = "en-US", Style = 2 }); ncco.Actions.Add(new ConversationAction { Name = "conference-call" }); return Response.AsJson(ncco); } } }
The above code will do the following:
When a call is received, the user will hear "Hello. You will now be added to the conference call." then they will be added to the conference call.
Multiple callers can be added to the conference until they all have disconnected.
We are done! To test this sample app, some more configuration steps are required.
Linking Your App to Vonage
If you've been following along by using the Vonage CLI:
vonage numbers. Run the app and give it a go by calling the
- How to forward a call via voice proxy with ASP.NET Core
- Getting Started with Nexmo Number Insight APIs and ASP.NET. | https://developer.vonage.com/blog/2019/05/16/build-a-conference-call-with-nexmo-voice-api-and-csharp-dr | CC-MAIN-2022-27 | refinedweb | 364 | 52.05 |
What I am trying to do is take a user input for as many rows as they wish, and make it into an array. After that i want to find where the highest number is in the array, an (x,y) coordinate of the number type of thing. I have created the initial array in different way but for example I have:
import numpy as np
m = []
rows = eval(input("How many rows in the list:"))
for row in range(rows):
m.append([])
value = eval(input("Enter a row:"))
m[row].append(value)
m = np.array(m)
print(m)
M = np.amax(m)
print(M)
index = np.where(M)
print(index)
Enter the number of rows in the list:3
Enter a row: 1,5,6
Enter a row: 2,6,7
Enter a row: 5,26,12
The location of the largest element is at (1, 2)
This is an implementation without using numpy. It is not that efficient, but works fine.
rows = eval(input("How many rows in the list:")) m = [] for row in range(rows): value = eval(input("Enter a row:")) m.append(value) large = m[0][0] x = 0 y = 0 for i in range(0, rows): for j in range(0, len(m[i])): if(large < m[i][j]): large = m[i][j] y = i x = j print(x, y, large) | https://codedump.io/share/FMcHib24GQMg/1/find-element-in-two-dimensional-python-array | CC-MAIN-2017-39 | refinedweb | 226 | 80.11 |
21 September 2012 21:48 [Source: ICIS news]
HOUSTON (ICIS)--US September contract prices for methyl methacrylate (MMA) were assessed 2.2% lower on Friday, tracking seasonal factors that are reducing demand.
US September MMA contracts were assessed by ICIS at $1.075-1.125/lb ($2,370-2,480/tonne, €1,825-1,910/tonne) FD railcar (free delivered via railcar).
September prices were 2.5 cents/lb lower than the August settlement of $1.10-1.15/lb FD railcar.
“Demand has been weak,” a buyer said. “Painting season has been down and manufacturing is declining.”
Although the US Department of Commerce said new ?xml:namespace>
“It’s the time of year when MMA ramps down for seasonal reasons,” a producer said.
The slight softening in demand is not expected to exert much downward pressure on prices, sources said.
Two major producers said they rolled over their September pricing from August levels, but most buyers said they were able to shed 1-3 cents/lb in September.
Buyers pointed to improved supply and stable feedstock costs as other reasons for prices to stay steady or dip slightly.
The main feedstock for
Additionally,
Major US MMA producers include | http://www.icis.com/Articles/2012/09/21/9597815/us-september-mma-contracts-fall-on-weaker-seasonal-demand.html | CC-MAIN-2014-42 | refinedweb | 199 | 68.16 |
This blog will show you the basics of XI, XSLT and the Graphical mapping tool. This should give the XI beginner a very basic idea of how to use the SLD, Repository, namespaces, data types and mappings. If you are like me you are probably just itching to get your hands dirty. So first up let’s assume you have a XI userid – note that probably at first logon you will need to first logon to XI via SAPGUI to reset the password. You’ll also need Java version 1.4+ and Java webstart installed on your PC – get this from Sun website ()That is very easy to do if you have a reasonable idea of how XSLT works. It will help you, even using the XI Graphic mapping, to understand the concepts – tree navigation, nodes, context etc. I would recommend you go and buy XSLT for Dummies or one of the many teach yourself XSLT sites and study further on this subject see () If you don’t have one then get an XSLT editor. E.g. Download this free tool – () You can use Cooktop to quickly check any XSLT you prepare before diving into XI.*And an associated DTD to describe the resulting XML*. Tip : If you don’t have one but you have the XML you can use a convertor. You can use a online tool to import and create a DTD () *
*
*Save it.* Then on the left hand navigation pane it will appear.* * h3. External Definition Create an external definition to hold the *DTD for the Source XML file*. With that created select the DTD category and in the Messages choose the First Element. Import the DTD file and Save it.
Create another *External Definition for the Target* XML file. Remember to choose Category DTD and Messages from First Element
h3. Message Interface Now we’ll need to describe the message interfaces for both the Source and Target files. Again within your SWC Interface Objects, right click on Message Interface – create a new one for the source file. This is the source’s outbound interface – so the category is Outbound. Choose the corresponding DTD.
We create another for the Target file. This is the target’s inbound interface – so the category is Inbound. Choose the corresponding DTD. Leave the fault message type empty.
h3. Interface Mapping Create a interface mapping for the Source to the Target via the XSL. In the left hand navigation pane, Open the Mapping Objects, right click on Interface Mappings and create. You can drag and drop or select the Source Interface And for the Target Interface Now choose the mapping program as XSL using the one you imported from the zip file you previously set up.
Select the Test Tab and click the xmlbutton to import the source XML file (via the XMLimport icon
) or cut and paste the XML (via the src icon
) Press the Test button
– Hopefully you will have a transformed document.
*
Many thanks for this great blog.
Only some hints which very very helpful for me.
For the source DTD I cut and past the line “” to the first row because than the messages structure is shown in the right structure (coffees is the root element in this structure). If you do this it is necessary to update the Message Interfaces and Interface Mapping because XI will not do this by its own.
Additionally I pad in the trap and named the mapping file with an extension xslt. As I tried to add this to the Interface Mapping I got the error “… has no program”. As I reread your blog I found my mistake and renamed the mapping file to xsl and archived it once again and then everything was fine.
For the target Message Interface is the wrong picture shown, as you mentioned it is a Inbound Interface.
Many thanks once again for this I was very helpful to me.
Josef | https://blogs.sap.com/2008/05/12/xi-for-beginners-simple-xslt-part-1/ | CC-MAIN-2018-13 | refinedweb | 654 | 71.65 |
Answered by:
VS 2008 & Plugin registration - multiple plugins
Question
- Since I'm relatively new to both VS 2008 and the CRM, I may be missing something obvious.
I have a project CRM.Plugins with a TaskRoute.cs class. I have followed the instructions in the SDK and Programming with CRM 4 book, and have successfully registered the plugin. However, if I add an additional class to the CRM.Plugins, the solution builds fine but loading the dll in the Plugin Registration Tool only shows up the TaskRoute plugin. The other class also inherits from IPlugin, but I can't seem to get the Registration Tool to see it. Are there additional steps I need to take? Something possibly obvious I missed?Wednesday, July 22, 2009 12:20 PM
Answers
- Hi,
Could it be public keyword being missed?
public class Class2: IPlugin
Regards,
Nishant Rana, July 22, 2009 12:37 PM
All replies
- Hi,
Could it be public keyword being missed?
public class Class2: IPlugin
Regards,
Nishant Rana, July 22, 2009 12:37 PM
The plug-in signature is captured when you register the assembly . You need to re-register the plug-in in order to see the new classes. Another option is to adopt a single entry point plug-in and manage the messages execution path with a switch construct. E.g.
switch( context.MessageName )
{
case MessageName.Create:
break;
case MessageName.Update:
break;
}
The advantage of using such approach is that it does not require you to re-register the plug-in and is a good development practice if you’re thinking ahead e.g. future updates / ms rollups / new version / new requirements etc.
Blog: * Website:, July 22, 2009 12:55 PM
- Yes, it was this silly mistake! Thanks for pointing it out...
(Also, thanks Adi for the information, but I am already using switch (context.MessageName); It's just that I have several different kind of plugins so I need to separate out the logic a little more)Monday, July 27, 2009 6:46 AM | https://social.microsoft.com/Forums/en-US/ec7bb1e1-3394-41f1-aeba-28b2689285ae/vs-2008-amp-plugin-registration-multiple-plugins?forum=crmdevelopment | CC-MAIN-2021-43 | refinedweb | 336 | 65.62 |
Dear all,
I am a seasonal programmer, and just got back to learn how to program in C again. I need a hand for showing my mistake, any help will be much appreciated.
thnks
Nico :)
I have to work around on the problem, but I got this warning after compiling this program:
Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
exercise.c:
Error E2379 exercise.c 14: Statement missing ; in function main
*** 1 errors in Compile ***
-----------------------------------------------------------------------------------
/* Calculate and display the average used of gasoline */
#include <stdio.h>
int main()
{
/* data type */
float average, gallons, totave;
int counter, miles;
/* initializing phase */
counter = 0
/* processing phase */
printf( "Enter the gallons used (-1 to end): " );
scanf( "%d", &gallons );
if ( gallons != -1 ) {
printf( "Enter the miles driven: " );
scanf( "%d", &miles );
average = gallons / miles;
counter = counter + 1;
printf( "The miles/gallon for this tank was %f", average );
totave = average / counter;
}
else
printf( "The overall miles/gallons was %f", totave );
return 0;
} | https://cboard.cprogramming.com/cplusplus-programming/54339-statement-missing-problem-printable-thread.html | CC-MAIN-2017-09 | refinedweb | 160 | 69.01 |
Search the Community
Showing results for tags 'csv'.
Found 18 results
import csv in mysql db using ajax and php
zetastreak posted a topic in PHP Coding Helpi was working on a mini project that imports csv file to the database through ajax and it's working fine <?php if(!empty($_FILES["marks_file"]["name"])) { $connect = mysqli_connect("localhost", "root", "", "dbname"); $output = ''; $allowed_ext = array("csv"); $extension = end(explode(".", $_FILES["marks_file"]["name"])); if(in_array($extension, $allowed_ext)) { $file_data = fopen($_FILES["marks_file"]["tmp_name"], 'r'); fgetcsv($file_data); while($row = fgetcsv($file_data)) { ); } $ <tr> <th width="25%" >name</th> <th width="15%" >Physics</th> <th width="15%" >Maths</th> <th width="15%" >Chemistry</th> <th width="15%" >Biology</th> <th width="15%" >SST</th> </tr> '; while($row = mysqli_fetch_array($result)) { $output .= ' <tr> <td>'.$row["name"].'</td> <td>'.$row["Physics"].'</td> <td>'.$row["Maths"].'</td> <td>'.$row["Chemistry"].'</td> <td>'.$row["Biology"].'</td> <td>'.$row["SST"].'</td> </tr> '; } $output .= '</table>'; echo $output; } else { echo 'errorx'; } } else { echo "errory"; } ?> however the imported csv files inserts null values in the tables because the format of all csv files assigned to me are in the exact same format: ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,Fields,Physics~75,Maths~50,Chemistry~65,Bio~85,SST~100 ,,,Name1,10,25,35,42,62 ,,,Name2,80,45,45,45,25 ,,,Name3,63,25,63,36,36 ,,,Name4,82,36,75,48,42 ,,,Name5,45,45,78,25,24 ,,,Name6,36,36,15,75,36 ,,,Name7,99,45,24,24,45 ,,,Name8,45,85,85,85,96 i changed my code a bit modified the functions to espace blank spaces and not return null values in the data tables while (($row = fgetcsv($file_data, 1000, ",")) !== FALSE) { if ((string) $row[0] != '0' and empty($row[0])) { continue; } ); } But it doesn't work with the specified csv files i think the ajax call breaks and that's why nothing happens.However it works fine with csv files without blank spaces
How to read csv data in PHP from a direct Java App upload
FreakingOUT posted a topic in PHP Coding HelpAfter searching postings on multiple forums, I am officially now "Freaking OUT" trying to understand something that is probably very simple, but cannot seem to grasp. I simply want to read basic .csv data that is sent/uploaded directly to a PHP page, and to then append each record that shows up to a single .csv file on the server. The incoming data is supposed incoming via $_POST['csv'] ... at least that's what I was told. Each.csv record line being sent/uploaded is very simple (either single or multiple records in one small file): text1,text2,text3,text4,text5 For additional processing I know about 'explode', etc., but right now I am stuck even trying to do an 'echo' to display the simple incoming data "as is". One option I tried was: $postdata = file_get_contents("php://input"); echo $postdata; In the Java App monitoring I get the following after 3 records are sent/uploaded to the PHP URL: Server response status line: HTTP/1.1 200 OK I find this strange since I did not include... http_response_code(200); ... in the page code. Obviously, I do NOT know what I am doing here {SIGH}. Any assistance or guidance is appreciated. Thank you ! - FreakingOUT
store csv data coming from api to put in a csv file to later save in db
natturefrk posted a topic in PHP Coding Help0 What is the best way to store this data coming from the api into a csv file to later put into the db. Output: rank, level, xp, rank, level, xp, etc. This api produces about 60 rows of data per name ran and x that by about roughly 300 names that equals a lot of data. Pretty much with my current code I am pretty much creating a endless loop almost that would take a long time to execute so updating said data would be a nightmare i would think. Is there a way to accomplish the same thing without the loop or I am not sure how to go about this. My current code is a mess that much I know I am gonna be told. This code works, just not efficiently. I am thinking there may be a better way to do this. $query = $conn->prepare("SELECT name FROM users LIMIT 1"); $query->execute(); while($row = $query->fetch(PDO::FETCH_ASSOC)){ $name = $row['name']; $url = ''. $name . '';//api that the csv data is coming from $highscores = file_get_contents($url); $fields = array("Name", "Rank", "Level", "Xp");//this is to add the headers // for the csv files $implode1 = implode($fields, ",");//turn into csv format, not sure this is //even needed $implode1 .= "\n";/*this is to add a line break so that the explode below will properly put it into its own element*/ //otherwise data starts joining togather $extra_data = array("$name");/*This is to add the name that the data pertains too*/ $implode2 = implode($extra_data, ",");//turn into csv format $highscores = $implode1 . $implode2 . $highscores;//join as one array $highscores = explode("\n", $highscores);//turn each csv into an element of //its own element a bunch of unsets to remove unwanted data. Omitted them to condense the code $i = 1; header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="name.csv"'); $data = $highscores; $fp = fopen('highscores/' . $name . '.csv', 'wb'); foreach ( $data as $line ) { $val = explode(",", $line); fputcsv($fp, $val); } fclose($fp); The pdo part I was gonna include but the way I have it setup now wouldn't work. I was thinking that I would use mysql's LOAD DATA INFILE to insert the csv data to database. The end goal here is to be able to search for player stats and to use said data to keep track of xp earned during a xp competition. I PRAY that i have included enough info... I would really appreciate any feedback if possible.
uploading a csv file into mysql database
xclusivzik posted a topic in PHP Coding Helpwhen i input this code it only uploads a single column into my database <html> <head> <title>MySQL file upload example</title> <meta http- </head> <body> <form action="try2.php" method="post" enctype="multipart/form-data"> <input type="file" name="uploaded_file"><br> <input type="submit" name="submit"value="Upload file"> </form> <p> <a href="list_files.php">See all files</a> </p> </body> <?php $con=mysqli_connect("localhost","root","","book"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } if(isset($_POST['submit'])) { $fname = $_FILES['uploaded_file']['name']; $chk_ext = explode(".",$fname); if(strtolower($chk_ext[1]) == "csv") { $filename = $_FILES['uploaded_file']['tmp_name']; $handle = fopen($filename, "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $sql = "INSERT into data(name,Groups,phone_number) values('$data[0]','$data[1]','$data[2]')"; $result=mysqli_query($con,$sql) or die(mysql_error()); } fclose($handle); echo "Successfully Imported"; } else { echo "Invalid File"; } } ?> </html>
Inserting long form data to database table
thenorman138 posted a topic in PHP Coding HelpI have a form that is populated by a CSV file, always 229 fields but anywhere up to 10 or 12 rows. The form populates correctly, but I'm having issues saving it all. The loop seems like it's missing something or maybe something is mismatched. Here is the form code: **page-confirm.php** $connect = mysqli_connect($server, $user, $pw, $db); if ($connect->connect_error) { die("Connection failed: " . $conn->connect_error); }else{ //echo'success!'; } if(isset($_POST['preview'])) { ini_set('auto_detect_line_endings', true); $file = $_FILES["file"]["tmp_name"]; $handle = fopen($file, "r"); $maxPreviewRows = PHP_INT_MAX; // this will be ~2 billion on 32-bit system, or ~9 quintillion on 64-bit system $hasHeaderRow = true; echo "<form method='post' action='/form-submit' >"; echo '<table>'; if ($hasHeaderRow) { $headerRow = fgetcsv($handle); echo '<thead><tr>'; foreach($headerRow as $value) { echo "<th>$value</th>"; } echo '</tr></thead>'; } echo '<tbody>'; $rowCount = 0; while ($row = fgetcsv($handle)) { $colCount = 0; echo '<tr>'; foreach($row as $value) { echo "<td><input name='row[".$rowCount."][".$colCount."]' type='text' value='$value' /></td>"; $colCount++; } echo '</tr>'; if (++$rowCount > $maxPreviewRows) { break; } } echo '</tbody></table>'; echo "<input type='submit' name='confirm' value='confirm'>"; echo '</form>'; } ?> Here's the code for the submission page with the insert loop: **page-formsubmit.php** $connect = mysqli_connect($server, $user, $pw, $db); if ($connect->connect_error) { die("Connection failed: " . $connect->connect_error); }else{ echo'success!'; } //var_dump($_POST); $sql = $inserts = $binds = []; foreach ($_POST['row'] as $rowValue){ if(is_array($rowValue) && count($rowValue) > 0 ){ foreach($rowValue as $rowData){ /*** * Stupidly, I had missed that row contains arrays * rather than values, so you need a foreach, inside the * foreach as so: ***/ foreach ($rowData as $columnKey => $columnValue){ //$columnValue will now equal $value //$columnKey will be the column number (1...229) /*** * This is the area you can construct your SQL query values. * db_connection is assumed to be setup. ***/ $sql[] = "`column_name_".$columnKey."`"; $binder = "value".$columnKey; $inserts[] = ":".$binder; $binds[$binder] = $columnValue; unset($binder); } unset($columnKey,$columnValue); } unset($rowData); /*** * This is the area the SQL query is set on a per row basis ***/ $sqlFull = "INSERT INTO staging (".implode(",",$sql).") VALUES(".implode(",",$inserts).")"; $connect->prepare($sqlFull); /*** * EDIT: bind param MUST come after the prepare call ***/ foreach($binds as $bindKey=>$bindRow){ $connect->bind_param(":".$bindKey, $bindRow); } unset($bindKey,$bindRow); var_dump($binds); $sql = $inserts = $binds = []; //reset arrays for next row iteration. /*** * db_connection then executes the statement constructed above ***/ $connect->execute(); } //close if. } unset($rowValue); ?> You can see in the submission page where I comment out the var_dump for post data. When it's active, it prints out this for the array: success!array(1) { ["row"]=> array(5) { [0]=> array(229) and continues printing the 229 elements for all 7 rows. There is something that's not quite working in this loop because even a debug statement within the loop to print the query won't work. I just need to make sure it iterates all 229 fields of every row to the end of the form and puts them into my staging table. My staging table, which is temporary, has 229 named fields in the exact order as the CSV, so I shouldn't have to declare each field I don't believe.
CSV hinderance
ajoo posted a topic in Javascript HelpHi all ! i have been trying to implement the CSV policy in my files. I have a bit of code that I am not sure how I can change it to suit the policy. Here's the code snippet : if(isset($_SESSION['msg'])) { // The script below shows the sliding panel on page load $script = ' <script type="text/javascript"> $(function(){ $("div#panel").show(); $("#toggle a").toggle(); }); </script>'; } As can be seen the script is loaded conditionally here. So how can I remove javascript embedded from this code so that this may be compatible with the CSV policy. NOTE: the javascript functions are in a separate js file loaded in the header. Thanks all !
import a csv file into mysql database
xclusivzik posted a topic in PHP Coding Help<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns=""> <head> <meta http- <title>Import a CSV File with PHP & MySQL</title> </head> <body> <form action="" method="post" enctype="multipart/form-data" name="csv" id="csv"> Choose your file: <br /> <input name="csv" type="file" id="csv" /> <input type="submit" name="Submit" value="Submit" /> </form> </body> but i keep having this error Notice: Undefined index: csv in C:\wamp\www\youngsoul\upload\file.php on line 7
Looking to export 4 tables as a CSV where the timestamps match across all tables
MasterACE14 posted a topic in MySQL HelpHi All, I have 4 tables each with only 2 columns (except for one that has 3) and they all have in common a date/time field. I am trying to export all 4 tables together as one CSV file and to have the records matched together where they have the same date/time. My tables are structured like so (which originally came from 4 individual CSV files): So as an exported CSV I would want the matching records (based on the date/time) to be part of the same record like so: Time, heartrateValue, Intensity, minutesleepValue, minutesleepLogId, steps 3/01/2018 0:01, 45, 0, 1, 17396451215, 0 3/01/2018 0:02, 45, 0, 1, 17396451215, 0 etc. A secondary issue is changing the date format to D/MM/YYYY from M/DD/YYYY. However, if I can get this CSV file export I can probably just loop through it in PHP and fix up the date format. Thank you kindly for your assistance
PHP script, add rows to total data for a CSV
thenorman138 posted a topic in PHP Coding HelpI have a php script which runs a sql query and writes it to a CSV, which works perfectly. However, I created a second modified version of the script because I want to write the same CSV, but with an additional row beneath each group of data for totals. Currently, the results are ordered by User Extension (CSRs and phone numbers). So for extension 7200 I want, let's say, all 10 of their calls and then another row to total the calls and the individual columns. I currently have the query returning an 'x' for indicators. So one user might have 10 calls and 4 'x's in the 'inbound' column. I would want that to say 4. Anyway, I started the second version of the script to use an array to do this. The first problem is it's telling my fputcsv() expects parameter 1 to be resource. It looks like this could be an error for the type of array I'm using, but I'm not sure. I feel like I'm on the right track but I'm not familiar with using arrays and CSV files together like this. Any help is much appreciated. ```$result = mysqli_query($conn2, "SELECT DISTINCT firstn , lastn , extension , Recieved , RecievedKnown , Outbound , outboundKnown , Missed , MissedKnown , CallingNumber , CalledNumber , starttime , endtime , duration , HOLDTIMESECS , TERMINATIONREASONCODE FROM ( SELECT u.firstn , u.lastn , c.extension , CASE WHEN LEGTYPE1 = 2 AND ANSWERED = 1 THEN 'x' ELSE '' END AS Recieved , CASE WHEN LEGTYPE1 = 2 AND answered = 1 AND CALLINGPARTYNO = k.phone_number THEN 'x' ELSE '' END AS RecievedKnown , CASE WHEN ANSWERED = 1 AND LEGTYPE1 = 1 THEN 'x' ELSE '' END AS Outbound , CASE WHEN LEGTYPE1 = 1 AND FINALLYCALLEDPARTYNO = k.phone_number THEN 'x' ELSE '' END AS outboundKnown , CASE WHEN Answered = 0 THEN 'x' ELSE '' END AS Missed , CASE WHEN ANSWERED = 0 AND CALLINGPARTYNO = k.phone_number THEN 'x' ELSE '' END AS MissedKnown , a.CALLINGPARTYNO AS CallingNumber , a.FINALLYCALLEDPARTYNO AS CalledNumber , b.starttime AS starttime , b.endtime AS endtime , b.duration , a.holdtimesecs , a.terminationreasoncode FROM ambition.session a INNER JOIN ambition.callsummary b ON a.NOTABLECALLID = b.NOTABLECALLID INNER JOIN ambition.mxuser c ON a.RESPONSIBLEUSEREXTENSIONID = c.EXTENSIONID INNER JOIN jackson_id.users u ON c.extension = u.extension LEFT JOIN ambition.known_numbers k ON a.callingpartyno = k.phone_number WHERE date(b.ts) >= curdate() AND LEGTYPE1 <> 12 -- This keeps the report from having blank spaces due to the 12 legtype. AND c.extension IN (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312) ) x ORDER BY lastn") or die(mysqli_error( $conn2)); $userDetails = array(); while ($row = mysqli_fetch_assoc($result)){ $userDetails[] = $row; $extension = $row['extension']; if(!isset($userDetails[$extension])){ $userDetails[$extension]['missedCallCounts'] = 1; /* First time count */ }else{ $userDetails[$extension]['missedCallCounts'] += 1; /* Sum up the count */ } } echo $userDetails; $fp = fopen('TESTCSV.csv', 'w'); foreach($userDetails as $userDetail){ /* In the following line dump the respective userdetails to csv which will show summary */ fputcsv($fp, array_values($userDetails)); }```
php Script used to search multiple websites at once.
dolke022 posted a topic in PHP Coding HelpHi guys, What I'm trying to accomplish sounds like fairly easy task but due to my poor knowledge of php this turned to be quite a challenge. What I'm trying to do is to make a php script that will search the keywords on the multiple websites. Websites that I will search are all web shops, selling spare part for home appliances and keywords used are usually original spare part codes. When searching, script is searching these websites using their own search functions and not Google or other search engines. Input for this script should be a CSV file containing list of keywords and URLs of the web shops that needs to be search for all these keywords. Here is the example: Script should perform like this: It picks up the 1st keyword, browse to the URL1, uses its search, searches for the product, if it finds it, copy its price and write it back to original input CSV. If it doesn't find match (search results appear empty) it should write "no match found" and continue to URL2, URL3 and so on... When all URLs from the list are checked for the 1st keyword, scripts picks up 2nd keyword and continues on through all these keywords are not checked. This would be a resulting CSV file after the 1st keyword is checked: After all data from the input CSV file are processed, script should prompt a msg and create a download link for that CSV file to be downloaded. If there are multiple matches, in other words if for one keyword some of the website searches find 2 or more products, something like "More then one match" should be written in the file. Example: Please note that non of the website is using SSL and non of them requires login in order to display the prizes. This fact should make this script easier to build. Its not important for this script to run fast (its better I think to run it with some timeouts because of the server glitches and bottlenecks). What is more important is to make it automatic so one can start it over the night, over the weekends. Number of the URLs would be around 10, and list of keywords from few tens, to a few hundred. If I can provide some additional clarification and info I'm available. Of course I would be willing to pay someone to help me accomplish this task. Cheers Dean
PHP create csv, insert into db, send email with attachment to a bcc address
barkly posted a topic in PHP Coding HelpI'm trying to after submission 1. create a csv 2. insert record into db 3. send email that's created in form submission - $msg. 4. send email with attachment to only the email I specify (if possible) if not attach it to the email that's created at submission. I've search and search and found different methods but doesn't work with my code. I kept 3 lines at the top but can't get them to work ... either I don't get an email after submission or don't get an attachement. Can some one help? <?php $random_hash = md5(date('r', time())); $csvString = "..."; // your entire csv as a string $attachment = chunk_split(base64_encode($csvString)); $to = "email@email.com"; if(isset($_POST['submit'])) { // VALIDATION if(empty($_POST['firstName'])) { "First Name Required"; } if(empty($_POST['lastName'])) { "Last Name Required"; } if(empty($error)) { $to = "$to"; $ <tr><td> <table width='100%' cellspacing='0' border='0' cellpadding='0'> <tr><td>This is the email sent.</td></tr> </table> </body> </html>"; include('con.php'); $con = mysqli_connect($host,$user,$pass,$dbName); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } mysqli_select_db($con,"thetable"); $firstName = mysqli_real_escape_string($con, $_POST['firstName']); $lastName = mysqli_real_escape_string($con, $_POST['lastName']); $sql = "SELECT * FROM thetable WHERE `firstName` = '{$firstName}' OR `lastName` = '{$lastName}'"; $result = mysqli_query($con,$sql); if(($result->num_rows)>= 1) { $theerror = "You exist"; } else { $sql="INSERT INTO thetable(firstName, lastName) VALUES ('$_POST[firstName]','$_POST[lastName]'"; $success = "Sent ... Insert it!!!"; if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); } $result = @mail($to, $subject, $msg, $headers); } mysqli_close($con); { } } } ?>
getting info from csv file
cobusbo posted a topic in PHP Coding HelpHi Ive currently developed a script that connects via an API to send a message, and tested it with one user and it works perfectly. But now im bit stuck to send it to multiple users. All my visitors unique IDs are being stored into a file called unique.csv all in 1 column under each other. But what im currently trying to do is to recall the info from the csv and make a contact list to broadcast the message to. The csv file looks like: Here is my current script <?php $f_pointer=fopen("unique.csv","r"); // file pointer while(! feof($f_pointer)){ $ar=fgetcsv($f_pointer); } require_once ('MxitAPI.php'); /* Instantiate the Mxit API */ $key = '****'; $secret = '*****'; $visitor = '****'; $api = new MxitAPI($key, $secret); $api->get_app_token('message/send'); $api->send_message('guniverse', '$ar[0]', '*test message*', 'true'); echo 'Success'; ?>
PHP Form Validation Against CSV with Wordpress
JessicaBBG posted a topic in PHP Coding HelpHi all, PHP newbie here. I've been trying to integrate Gravity Forms with Gravity View's Import Entries from CSV plugin. Unfortunately, it needs a bit of tweaking to get everything connected properly. I used a code snippet from David at Gravity Whiz, (HERE) that gets integrated into my Wordpress site's functions.php file, and have been trying to customize to to suit my needs. From what I understand in looking at the code, the only bit I need to tweak (I think) is the bottom portion: # Configuration new GW_Value_Exists_Validation( array( 'target_form_id' => 1, 'target_field_id' => 3, 'source_form_id' => '/RSVPcodes.csv', 'source_field_id' => 'rsvp', 'validation_message' => 'Hey! Don\'t be a villain! Provide a legit RSVP code to reserve your spot at the Smackdown.' ) ); My main question here: how to get the validation code to see the database that I've uploaded via the Import Entries plugin? I know ignorance is making me miss something that should be pretty simple. Right now, I've got it to validate a test word that I know is not in my database, and also a code that I know is in the database. It's coming back with both items as not valid. The end result will be a RSVP form that will be used to accept RSVPs only from people who have an RSVP code from their invitation, a lot like a license key validation system. The live site (and form I'm trying to tweak) is HERE. Thanks in advance for any help.
explod csv file
kimjessen posted a topic in PHP Coding HelpHello yes so I let myself be carried away, and then came a new small challenge. In the graph code is the csv file opened and soteret with a "explod" function. and it work fine as long as I only have one column with y data and one with x data. but when I start to get more column's it does not work. I've created a short example below. <?php define("LOG_FILE", "./data/test111/test111-2015-01-17.csv"); $times = array(); $values = array(); $values_test1 = array(); $file_lines = file(LOG_FILE , FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES); foreach($file_lines as $line_num => $line_value) { $line_elements = explode(",", $line_value); $times[] = date($line_elements[0]); $values[] = $line_elements[1]; $values_test1[] = $line_elements[2]; } echo $values[2]; ?> the control echo I make "echo $values[2];" works fine, there is be the expected value. but if I try to "echo $values_test1[2];" so there is nothing. the CSV file looks like this. Date,temp1,temp2 2015-01-23-12-00,54,59 2015-01-23-12-01,54,59 2015-01-23-12-02,54,59 2015-01-23-12-03,54,58 2015-01-23-12-04,54,58 2015-01-23-12-05,54,58 2015-01-23-12-06,54,58 2015-01-23-12-07,54,58 2015-01-23-12-08,54,58 2015-01-23-12-09,54,58 2015-01-23-12-10,54,58 2015-01-23-12-11,53,58 2015-01-23-12-12,53,58 2015-01-23-12-13,53,58 2015-01-23-12-14,53,58 why can I not get the temp2 values into $ values_test1 [] thank you very much
Parsing CSV file + appending data to another file by unique ID key
slim_swan posted a topic in PHP Coding HelpI have multiple CSV files (example file.csv) that need to be read, and the data needs to be compared to the data in another csv file (data.csv) by an ID key which is in the first column of the file There are multiple rows and columns with data. First rows of the file is header column info so the first row needs to be skipped the data which is in the selected row of the file (file.csv) needs to be compared to data in data.csv by the ID key when the same ID key is found in a row, the data needs to be appended to the end of the row of that same ID key row in data.csv (everything except the ID key is copied to file.csv) CSV files are delimited by ; data is UTF-8 - Croatian I've made a script to parse through a file (data.csv) and print it but ain't that good with working multiple files and arrays to make it check the data from file.csv and append it...help? <?php $row = 1; if (($xxa = fopen("data.csv", "r")) !== FALSE) { echo "<meta charset=\"UTF-8\">"; while (($data = fgetcsv($xxa, 1000, ";")) !== FALSE) { if ($row==1) { $row++; continue; } $num = count($data); echo "<p>$row. <i>red: <br /></p>\n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] . "</br>\n"; } } fclose($xxa); } ?> ----- I've googled and found this other script online (other.php) which is awesome because it puts all the data in arrays but I have no idea how to select that first cell with an ID key in one file, and copy that row and append it to another csv file at the end of that ID key row :/ <?php /** *; } /** * Example */ print_r(csv_to_array('example.csv')); ?>
how to insert into a new table everytime the query is implemented
xclusivzik posted a topic in PHP Coding Helpi want a situation where, when i upload something into my database, it creates a new table, everytime, i saw this $forum = "CREATE TABLE IF NOT EXISTS for_".$id." ( `id` int(11) NOT NULL AUTO_INCREMENT, `stud` int(11) DEFAULT NULL, `course` int(11) DEFAULT NULL, `message` varchar(1000) DEFAULT NULL, PRIMARY KEY (`id`) ) "; but don't know how to implement it into this query $sql = "INSERT into data(name,Groups,phone_number) values('$data[0]','$data[1]','$data[2]')";
Importing CSV data into application database
Ty44ler posted a topic in Application DesignBackground: I work on an application that tracks server information. The data comes from 10 tables in a database that are exact replicas of 10 CSV files that insert daily into their specific tables. The database is nowhere near normalized and is a straight dump from the CSV to the db tables. (CSV headers match the table fields) Problem: I need to figure out a way to get the data from the CSV data into a normalized database for the application to read instead of a straight dump of the CSV data to the table. I have little control over the CSV's, but do have control over what happens with them afterwards. What would be the best way to get logical data into a normalized database from a set of CSV's? Thanks!
Add Column and Value existing CSV
eugenevz posted a topic in PHP Coding HelpHi I have a script which picks up CSV files and inserts into a table (mysql). I am a beginner and finding it difficult to get the script to add an additional column to existing CSV, and add value to column, for each row... Here is the script.... How can I manipulate $csv and add a column (including separator) and value ($filedate) for each row? Help much appreciated. for example: CSV contains: Number, Name, LastName 1, John, Thomas 2, Jeffrey, James I need to add: Number, Name, LastName, Date 1, John, Thomas, 2014-10-31 2, Jeffrey, James, 2014-10-31 <?php #! /usr/bin/env php $databasehost = "localhost"; $databasename = "****"; $databasetable = "****"; $databaseusername="****"; $databasepassword = "****"; $fieldseparator = ","; $lineseparator = "\n"; $files = glob("*ETF_*.csv"); $filedate = "2014-10-31"; if (empty($files)) { die("No records were loaded."); } else foreach($files as $csv) $etf_array = array( PDO::MYSQL_ATTR_LOCAL_INFILE => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION); { try { $pdo = new PDO("mysql:host=$databasehost;dbname=$databasename", $databaseusername, $databasepassword, $etf_array ); } catch (PDOException $e) { die("database connection failed: ".$e->getMessage()); } $affectedRows = $pdo->exec(" LOAD DATA LOCAL INFILE ".$pdo->quote($csv)." INTO TABLE `$databasetable` FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)." LINES TERMINATED BY ".$pdo->quote($lineseparator)." IGNORE 1 LINES"); echo "Daily - Loaded a total of $affectedRows records from $csv.\n"; } ?> | https://forums.phpfreaks.com/tags/csv/ | CC-MAIN-2019-26 | refinedweb | 4,714 | 61.97 |
Design Guidelines, Managed code and the .NET Framework
I just noticed that Vance Morrison posted the source code to his latest project (Hyperaddin for Visual Studio) on CodePlex.
I have long thought that source code comments were not enough to explain what is really going on... often you need to refer the read to other methods or areas of the code. Well, luckily for me, Vance and gang saw the same problem and went out to solve it.
Here are a few simple examples:
// In this comment I wanted to talk about the code:MethodTable::Unbox method.
// By Adding a code: hyperlink, readers can quickly navigate to it. Any name
// that can be found using the Edit.FindSymbol (Alt-F12) can be used. If you
// need to refer to an overloaded method, it is best to use an anchor (see below).
// #mytopic
//
// ...
// Somewhere else in the file you can refer to code:#mytopic. Now readers
// can quickly navigate to the #mytopic anchor.
// I need to refer to #mytopic but it is not in the current file. But I
// know that this anchor is related to the class 'MethodTable' and thus will
// be in the same file as that class definition by using code:MethodTable#mytopic
// I can refer to #mytopic anywhere in any code within the solution.
Check it out:
primitive. really primitive. honestly? I think MS missed a huge and I do mean huge opportunity when it introduced C# to not have the source actually be code markup that was readered into source code. something like xml or html for source code
you could have embedded images/diagrams in the markup - no more tab damaged ascii art. xslt to control formatting of code. comments with bold, paramters appearing in blue, italics or whatever style you chose. refactoring would be dog simple since things like <forloop></forloop> would have controlled code constructs etc.
sigh.
code visualization would be cool. just render symbols based on the elemnts. branch/condition/loops. Visual Studio could have been so much more.
Nice thought, but the way is wrong: C# already supports structured commenting through XML comments: The <see> tag actually links to other types and members. One should utilize this already given feature instead of doing something totally new and different.
ReSharper, e.g., supports this through its "Quick Documentation" (Ctrl+Q) where it displays a type's/member's XML docs in a formatted and hyperlinked tooltip window.
See:
Le titre pourrait laisser penser que je ne connais pas la doc xml déjà proposée par C# , qui permet,
The ultimate would have the text formatting power of Donald Knuth's literate programming tools but integrated live into Visual Studio and for languages used in production.
That's beautiful! I love to see developers trying to standardize their tools so as to help the community.
As for the above comment about C# should be XML... that's nasty and bizarre. Besides, if someone was so impressed with XSLT, why not build a tool that will do the transformations yourself?
C# is perfect :)
sounds very cool, thanks for sharing.
um, I don't get it.
/// <summary>blah blah blah<see cref="SomeOtherMethod"> </summary>
Why are you reinventing the wheel on this? The XML documentation in C# (along with Sandcastle) covers these bases quite well (see "see", etc). It irritates me greatly when I download source code from somebody who rolls their own documentation scheme rather than uses the built-in documentation functionality. If we really want to find the referenced bits while coding, we can right-click and choose Go To Definition or Find All References. Outside of the editor, we have Reflector and Sandcastle. I'm not sure what more you need, but rolling yet another mechanism doesn't help anyone.
But I may be missing something. I tend to be critical of things that I find curiously interesting. I'll check it out.
It is only working for the same class methods which resides in the same source file. Am I missing something?
Following is the coding I used...
In Class2.cs
public class Class2
{
public Class2()
{
//
// TODO: Add constructor logic here
}
public void comments()
{
}
}
In Class1
public class Class1
/// <summary>
/// code:Class2::comments blah blah
/// </summary>
public Class1()
But above link is not navigating to the Class2 method
I think C# as XML would have been REALLY neat too. It would have made all kinds of things much easier.
Code as xml....sounds a bit like XAML, no?
XAML is more of serialization format than a procedural language. XML's good for representing the the state of something and defining general workflows, but the general C syntax isn't going away any time soon. On the other hand, I tend to think that XML would make a good replacement for, say, Verilog in that you want to represent a static object (a chip) in a self-describing format with tons of parsers, transforms, and "compilation" in the form of deserialization.
But on the topic of the hyperlinked code, I'm in the camp of "doesn't C# already have XML documentation for this?" | http://blogs.msdn.com/brada/archive/2007/09/04/hyperlink-your-source-code.aspx | crawl-002 | refinedweb | 851 | 64.3 |
Difference between revisions of "XSD Smoke Test Scenarios"
Latest revision as of 12:11, 10 October 2008
- Preferences
- XSD preferences are under XML->XML Schema Files
- Check the Qualify XSD constructs preference. Ensure that the prefix is used by the new schema wizard.
- Modify the default target namespace. Ensure that the new value is used by the new schema wizard.
- Modify the Honour all schema locations. Test a schema that imports two other schemas with the same namespace and different locations.
- Modify full schema conformance. TODO Needs a test schema that would expose the difference
- Unused Imports (New to 3.0.1).Test that unused imports and includes are removed | http://wiki.eclipse.org/index.php?title=XSD_Smoke_Test_Scenarios&diff=122911&oldid=94434 | CC-MAIN-2015-11 | refinedweb | 110 | 59.6 |
Technical Articles
Create a Welcome Popup for Fiori Launchpad and Freestyle Portal Sites
Moderator’s note:
Note that our public GitHub repository, providing code samples for Cloud Portal on the Neo environment, is not available anymore. If you have further questions, contact us under sapportal@sap.com.
Fiori and Portal developers can extend the functionality of Fiori Launchpad and Portal custom sites using Fiori Shell plugins. The concept of plugins allows portal implementers to hook into the Fiori Shell and add new elements to the User Experience – add menu items, create a custom footer, extend the header and more.
Fiori Shell plugins are SAPUI5 component apps that are loaded and initialized automatically when the site is started. This means that in addition to hooking into the Shell UX, plugins can be used to initiate and run site related actions in the background. Enabling Google Analytics (GA) tracking in your Portal site is a great example – here the shell plugin app is used to load the GA library and register for tracking events. For more information – Google Analytics for Fiori Launchpad.
In this post I’d like to show how to easily add a Welcome Popup to your Cloud Portal Fiori Launchpad and freestyle sites using a Fiori Shell plugin.
Prerequisites
To develop and use the Fiori Shell plugin we will be using the SAP Web IDE for Full-Stack Development.
Before you start make sure you have the following in place:
- Register for a free SAP Cloud Platform Trial account
- Enable the SAP Cloud Platform Portal service in your account
- Enable the SAP Web IDE Full-Stack service in your account
Create a Fiori Shell Plugin
To create a shell plugin please follow the instructions here:
SAP Fiori Launchpad Extensibility: Creating SAP Fiori Launchpad Plugins in SAP Web IDE
When generating the Shell plugin project enter the project name – welcomepopup.
Notice that the wizard allows you to generate sample code for hooking your custom UX controls into the Fiori shell – the Header, Footer and Me Area. For our scenario, you can leave those unchecked – as we will be creating a popover dialog.
Add the custom code
Now that the project has been generated let’s add the code for launching a popup welcome window.
- Under the welcomepopup root folder, create a new folder
- Name the folder – fragment
- Under the new fragment folder – create a new file
- Name the file – fragment.xml
- Paste the following code into the Popup.fragment.xml file:
<Dialog contentHeight="400px" contentWidth="400px" title="Welcome" xmlns="sap.m" xmlns: <buttons> <Button id="cancelBtn" text="Close"></Button> </buttons> <!-- This is the popup content, you can replace it with your own HTML and / or SAPUI5 code --> <VBox> <html:div <html:h1 Whats New</html:h1> <html:p Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </html:p> </html:div> </VBox> </Dialog>
Your code should look like this:
Now lets add the code that launches the dialog box
- Double click to open the Component.js file
- Add the following code at the end on the init() method:
if (!this.dialogFragment) { this.dialogFragment = sap.ui.xmlfragment("welcomepopup.fragment.Popup", this); sap.ui.getCore().byId("cancelBtn").attachPress(function(){ this.dialogFragment.close(); }.bind(this)); } this.dialogFragment.attachAfterClose(function() { this.destroy(); // view is destroyed as a video plays inside }); this.dialogFragment.open();
your code should look like this:
Preview the Shell plugin
To preview the plugin in Web IDE follow the instructions here: Running SAP Fiori Launchpad Plugins in the Sandbox.
The Fiori Launchpad sandbox is opened in the preview tab, notice the popup welcome dialog is opened when the site as initially loaded.
Deploy the Plugin to SAP Cloud Platform
After developing and testing the plugin, deploy it to your SAP Cloud Platform account to make it available for Portal Admins to use in their portal sites. Follow the instructions here: Deploying SAP Fiori Launchpad Plugins to SAP Cloud Platform
Configure the Shell Plugin in your Fiori Launchpad Portal Site
If you already have a Fiori Launchpad portal site, you can add the welcome popup plugin to it. Otherwise, create a new Fiori Launchpad site by:
- Launching the Portal service from your trial account
- Once the Portal admin space is opened
- Navigate to the Site Directory
- Click on the + icon to open the Create Site wizard
- Select the SAP Fiori Launchpad template
- Enter the site name and click Create
- Once the site is created it’s admin environment (Fiori Configuration Cockpit) is opened in a new browser tab.
- To add the shell plugin
- Click on Apps to configure new and existing apps in your Launchpad site
- Click on + to add a new app
- In the App Resource list select the welcomepopup application you just developed and deployed
- Under App Type select Shell Plugin
- Click on Catalogs and add the Sample Catalog or Everyone catalog or any other catalog you defined that contains the business roles you wish to assign the popup to.
- Click Save to apply your changes
Publish and View the Fiori Launchpad Site
To make the latest changes available for your end users
- Click on the publish button in the top menu
- Confirm and click on Publish and Open
The Fiori Launchpad site is opened in a new browser tab. Notice the Welcome popup is opened once the site is loaded.
You can repeat those steps and add the popup window shell plugin to any freestyle portal site as well:
Hi Ido,
Thank You for valuable blog its help me to creating the notifications in Fiori Launchpad,
But in webide its working fine for me . And deployed the applications in SAPUI5 ABAP REPOSITORY . when we are configuring in portal plugins we are getting an backend system not available . attached the error image . please guide us how to resolve the issue.
Thanks.
Hi Sangamesh,
I believe you were able to follow the instructions to create a popup on your Fiori Launchpad. I am not clear as to why you are selecting "Backend System". Are you trying to deploy the application from WebIDE to your ABAP Frontend server (which hosts the Fiori Launchpad) ? The "Backend Systems" button will try to fetch all the systems defined in the SCP destinations with a particular property. I have documented its usage here. If you still have questions related to this, please raise a new question in the forum.
Hi Ido,
Thanks for this blog!
Let's say I want to deploy this plugin project to a Enteprise Portal where a Fiori Launchpad is already in place. Would it be possible to use this Web IDE plugin project in with EP? Note that by exporting/importing project from Web IDE Full stack to usual Web IDE I was able to deploy to our Enterprise Portal system)
We know it is possible to extend a Launchpad on EP (as stated here) but procedure seems to be quite different
Thanks again!
Pablo
HI Pablo,
You can follow the steps to register a shell plugin on EP as described in this blog:
How to make use of the Fiori Framework Page Extensions
Regards, Ido
Thanks for your answer Ido,
Exactly, that's the blog we were following to make custom changes on EP, but as you can see it is just a plain js file instead of this fancy new brand Fiori template that you talk in this blog.
Then I assume answer is no, we can't integrate this Fiori Launchpad Plugin template on EP
Thanks!
Pablo
Hi Ido,
Thanks for such a great blog.
I have a requirment in sap Fiori launch onpremise to develop broadcast message tool. In your Case it is hardcoded message. How can we make one admin and user screen. User screen is in your example covered. Admin should have one app in that he can update message for certain time period.
We have achieved samething in enterprice portal.How can we do the same in case of Fiori?
Please suggest if you have any ide?
BR,
RK
Hi Ram,
You can have the admin create the message in an HTML format (with whatever tool youre using) and save in a location that would be accessible to the plugin to request as an HTML markup response.
Im not familiar with the Fiori Configuration environment on premise but perhaps the message HTML file location can be configure as a Fiori property.
In Cloud Portal you could implement this by reading the html file from the Portal's Asset Repository. The portal provides an API for the plugin to use for getting the file markup. Each time the admin will want to change the displayed message he will upload a new version of the file to the Portal's Asset repository.
Hi Ram,
I have a similar requirement have you achieved this if so please share the details.
Kind Regards
VK
Hi Venkata,
You should have two things ready in case of on premise.
That is how , you have to achieve this requirement.
Thank you!
I have added ICON in Header of fiori launchpad .When first time launchpad get display i am able to view it and can perform required functionality. But when i open any App and return back to Home Page of Launchpad .The icon is getting invisible on launchpad .
Below is my code
rendererPromise.then(function (oRenderer) {
oRenderer.addHeaderItem({
icon: “sap-icon://customer”,
tooltip: “Select Customer”,
press: function () {
if (!this.dialogFragment) {
this.dialogFragment = sap.ui.xmlfragment(“com.mycompany.flp.flpplugiacc.fragment.Popup”, this);
}
var oModel = this.getModel();
oModel.setHeaders({
“X-AUTHENTICATED-USER”: “tom@xyz.com”
});
this.dialogFragment.setModel(this.getModel());
this.dialogFragment.open();
}.bind(this)
}, true, true);
}.bind(this));
Thanks
Surekha
Hi Surekha,
Take a look at the documentation here:
Notice that if you mark bCurrentState=false and dont provide any aStates
Regards, Ido
Thanks Ido ,
It's worked .
hi Ido,
Is there a way to disable the plugin when i don't have anything to broadcast? i just want the pop-up to be seen when there's a system broadcast.
Not sure what a System broadcast is – but you can change the code to display the popup conditionally (if there is some REST API that you call to check the condition).
You can also add a property to the portal’s site settings (in the admin environment) to indicate if the popup should be displayed or not – and add that condition to the popup code.The advantage here, is that an admin can control the popup appearance from the portal admin screens.
You can user the SIteService JavaScript API for that:
Regards, Ido
Hi Ido ,
Nice blog 🙂
Regards
Ranjit V
Hey all,
excellent blog!
I have a on-premise Launchpad running.
I tried the steps provided by you in the SCP Web IDE.
I do not know how to proceed with the steps Deployment, Launchpad Cofiguration of the "tile" and Publishing.
Is there some one who set up a welcome page for on-premise Launchpad or knows a blog which discusses the configuration?
Greetings
Benjamin
Hi Benjamin,
For an on-premise launchpad deployment take a look at this blog to learn how to add a shell-plugin:
Regards, Ido
Hey Ido,
thank you very much!
This blog looks very good, i try to get this thing running and will give you a note once that worked.
Regards, Benjamin
Hi Ido,
I tried this, but I am getting an invalid xml error for the fragment. What could be the issue?
Regards,
Karan
I also get an xml error after creating the popup fragment file and after adding the code. Does it have anything to with defining the fragment like regular SAPui5 apps? Were you able to resolve this?
Thanks!
Mary
Hi Mary,
Can you try and run it; it runs properly even if it shows an error? I am also getting the error but on running the app it is running fine.
Regards,
Karan
WebIDE's complaining because it cannot find the namespace definition. You can either add the namespace or just ignore the message.
Cool, thank you very much! Would you have any template to add a "Do not display again" feature?
Hello Ido,
How do we handle this in Production?
Is it like every new message has to be written in Development System Launchpad(webide) and then Transport to Production Launchpad?
How to control these messages in Production?
Regards,
Sujoy
We recently upgraded our portal to 7.5 and we want to have a Pop-up for displaying a warning message and it should have OK button and once clicked OK, it should take to the Portal.
We are trying to do this in AFP in Standards mode using UI Theme Designer.
I found UR Control Previews "PopupWindow" but when we build and save, it doesn't show up after login.
I am a BASIS guy with very little knowledge on portal development.
Any form of guidance is really helpful.
Thanks and Regards,
Satish Dhanalakoti
Thanks for the nice blog.
I have one question. Can someone please suggest on how to block the popup once appeared. I have deployed the function on onpremise 1709 and when i access any legecy app tile it will appear again.
Good blog.
How can i use the destinations in this way? im trying to use it like always from the neoapp.json and it works in the WebIDE but when i deploy in the portal is like it doesnt recognize the neoapp.json file, is there another way to achieve this?
Hi,
could you solve that issue? I have the same problem. Destinations are not resolved in the launchpad. Testing the plugin in WebIDE (same subaccount) everything works fine.
Any hint is welcome.
Thanks.
Hi,
Yes, i dont have the source right now, so i dont know if im right.
But in the controller of your app, you have to call the destination this way:
/sap / fiori / "name of your app" / "path you define in neo-app"
Regards.
Hi Shemesh,
Thanks for wonderful blog on Plugins. I have developed similar plugins in FLP, but loading of plugins takes time during initial loading of FLP. Only after FLP loaded completely, plugins are loaded. Is there a way to load plugins first and then load launch page of FLP.
Hi,
I appreciate all the information on your blog. I've tried and worked perfectly.
As a new guy on Fiori/UI5 development I am trying to add language options for button, text or title to that plugin.
Somehow I've tried to set i18n.Model the dialog fragment but I couldn't get success on that. Dynamic field such as {i18n>title} seems empty or when I set to the dialog fragment it shows only title text not the value.
Could anyone help me how can I update i18n.properties on that plugin?
Wesley
Hello Ido,
Thanks for the blog.
Question - Can we add this plugin to development gateway system?
In-order to access this feature in production launchpad, I think firstly we need to add this plugin in development gateway.
Please provide your input.
Thanks, | https://blogs.sap.com/2017/10/12/create-a-welcome-popup-for-portal-fiori-launchpad-and-freestyle-sites/ | CC-MAIN-2022-27 | refinedweb | 2,511 | 62.38 |
Single page apps demand the front-end developers to become better software engineers. CSS and HTML are not the biggest concern anymore, in fact, there is no longer just a single concern. The front-end developer needs to handle XHRs, application logic (models, views, controllers), performance, animations, styles, structure, SEO, and integration with external services. The result which emerges from all those combined is the User Experience (UX) which should always be prioritized.
AngularJS is a very powerful framework. It is the third most starred repository on GitHub. It is not difficult to start using, but the goals that it is intended to accomplish demand comprehension. No longer can AngularJS developers ignore memory consumption, because it will not reset on navigation anymore. This is the vanguard of web development. Let’s embrace it!
Common Mistake #1: Accessing The Scope Through The DOM
There are a few optimization tweaks recommended for production. One of them is disabling debug info.
DebugInfoEnabled is a setting which defaults to true, and allows for scope access through DOM nodes. If you want to try that through the JavaScript console, select a DOM element and access its scope with:
angular.element(document.body).scope()
It can be useful even when not using jQuery with its CSS, but should not be used outside of the console. The reason being that when
$compileProvider.debugInfoEnabled is set to false, calling
.scope() on a DOM node will return
undefined.
That is one of the few recommended options for production.
Please note that you can still access the scope through the console, even when on production. Call
angular.reloadWithDebugInfo() from the console and the app will do just that.
Common Mistake #2: Not Having a Dot In There
You probably have read that if you were not having a dot in your ng-model, you were doing it wrong. When it regards inheritance, that statement is often true. Scopes have a prototypal model of inheritance, typical to JavaScript, and nested scopes are common to AngularJS. Many directives create child scopes such as
ngRepeat,
ngIf, and
ngController. When resolving a model, the lookup starts on the current scope and goes through every parent scope, all the way to
$rootScope.
But, when setting a new value, what happens depends on what kind of model (variable) we want to change. If the model is a primitive, the child scope will just create a new model. But if the change is to a property of a model object, the lookup on parent scopes will find the referenced object and change its actual property. A new model would not be set on the current scope, so no masking would occur:
function MainController($scope) { $scope.foo = 1; $scope.bar = {innerProperty: 2}; } angular.module(‘myApp’, []) .controller('MainController', MainController);
<div ng-controller=“MainController"> <p>OUTER SCOPE:</p> <p>{{ foo }}</p> <p>{{ bar.innerProperty }}</p> <div ng-if=“foo”> <!— ng-if creates a new scope —> <p>INNER SCOPE</p> <p>{{ foo }}</p> <p>{{ bar.innerProperty }}</p> <button ng-click="foo = 2”>Set primitive</button> <button ng-click=“bar.innerProperty = 3”>Mutate object</button> </div> </div>
Clicking the button labelled “Set primitive” will set foo in the inner scope to 2, but will not change foo in the outer scope.
Clicking the button labelled “Change object” will change the bar property from the parent scope. Since there is no variable on the inner scope, no shadowing will happen, and the visible value for bar will be 3 in both scopes.
Another way to do this is to leverage the fact that the parent scopes and the root Scope are referenced from every scope. The
$parent and
$root objects can be used to access the parent scope and
$rootScope, respectively, directly from the view. It may be a powerful way, but I am not a fan of it due to the problem with targeting a particular scope up the stream. There is another way to set and access properties specific to a scope - using the
controllerAs syntax.
Common Mistake #3: Not Using controllerAs Syntax
The alternative and most efficient way to assign models to use a controller object instead of the injected $scope. Instead of injecting scope, we can define models like this:
function MainController($scope) { this.foo = 1; var that = this; var setBar = function () { // that.bar = {someProperty: 2}; this.bar = {someProperty: 2}; }; setBar.call(this); // there are other conventions: // var MC = this; // setBar.call(this); when using 'this' inside setBar() }
<div> <p>OUTER SCOPE:</p> <p>{{ MC.foo }}</p> <p>{{ MC.bar.someProperty }}</p> <div ng- <p>INNER SCOPE</p> <p>{{ MC.foo }}</p> <p>{{ MC.bar.someProperty }}</p> <button ng-Change MC.foo</button> <button ng-Change MC.bar.someProperty</button> </div> </div>
This is much less confusing. Especially when there are many nested scopes, as can be the case with nested states.
There is more to the controllerAs syntax.
Common Mistake #4: Not Fully Utilising The controllerAs Syntax
There are a few caveats with how the controller object is exposed. It is basically an object set on the controller’s scope, just like a normal model.
If you need to watch a property of the controller object, you can watch a function but you are not required to. Here is an example:
function MainController($scope) { this.title = 'Some title'; $scope.$watch(angular.bind(this, function () { return this.title; }), function (newVal, oldVal) { // handle changes }); }
It is easier to just do:
function MainController($scope) { this.title = 'Some title'; $scope.$watch(‘MC.title’, function (newVal, oldVal) { // handle changes }); }
Meaning that also down the scope chain, you could access MC from a child controller:
function NestedController($scope) { if ($scope.MC && $scope.MC.title === ‘Some title’) { $scope.MC.title = ‘New title’; } }
However, to be able to do that you need to be consistent with the acronym you use for controllerAs. There are at least three ways to set it. You already saw the first one:
<div ng-controller=“MainController as MC”> … </div>
However, if you use
ui-router, specifying a controller that way is prone to error. For states, controllers should be specified in the state configuration:
angular.module(‘myApp’, []) .config(function ($stateProvider) { $stateProvider .state('main', { url: ‘/', controller: ‘MainController as MC', templateUrl: ‘/path/to/template.html' }) }). controller(‘MainController’, function () { … });
There is another way to annotate:
(…) .state('main', { url: ‘/', controller: ‘MainController’, controllerAs: ‘MC’, templateUrl: ‘/path/to/template.html' })
You can do the same in directives:
function AnotherController() { this.text = 'abc'; } function testForToptal() { return { controller: ‘AnotherController as AC', template: '<p>{{ AC.text }}</p>' }; } angular.module(‘myApp', []) .controller('AnotherController', AnotherController) .directive('testForToptal', testForToptal);
The other way to annotate is valid too, although less concise:
function testForToptal() { return { controller: 'AnotherController', controllerAs: 'AC', template: '<p>{{ AC.text }}</p>' }; }
Common Mistake #5: Not Using Named Views With UI-ROUTER For Power”
The de facto routing solution for AngularJS has been, until now, the
ui-router.
Removed from core sometime ago, ngRoute module, was too basic for more sophisticated routing.
There is a new
NgRouter on it’s way, but the authors still consider it too early for production. When I am writing this, the stable Angular is 1.3.15, and
ui-router rocks.
The main reasons:
- awesome state nesting
- route abstraction
- optional and required parameters
Here I will cover state nesting to avoid AngularJS errors.
Think of this as a complex yet standard use case. There is an app, which has a homepage view and a product view. The product view has three separate sections: the intro, the widget, and the content. We want the widget to persist and not reload when switching between state. But the content should reload.
Consider the following HTML product index page structure:
<body> <header> <!-- SOME STATIC HEADER CONTENT --> </header> <section class="main"> <div class="page-content"> <div class="row"> <div class="col-xs-12"> <section class="intro"> <h2>SOME PRODUCT SPECIFIC INTRO</h2> </section> </div> </div> <div class="row"> <div class="col-xs-3"> <section class="widget"> <!-- some widget, which should never reload --> </section> </div> <div class="col-xs-9"> <section class="content"> <div class="product-content"> <h2>Product title</h2> <span>Context-specific content</span> </div> </section> </div> </div> </div> </section> <footer> <!-- SOME STATIC HEADER CONTENT --> </footer> </body>
This is something we could get from the HTML coder, and now need to separate it into files and states. I generally go with the convention that there is an abstract MAIN state, which keeps the global data if needed. Use that instead of $rootScope. The Main state will also keep static HTML that is required on every page. I keep index.html clean.
<!— index.html —> <body> <div ui-view></div> </body>
<!— main.html —> <header> <!-- SOME STATIC HEADER CONTENT --> </header> <section class="main"> <div ui-view></div> </section> <footer> <!-- SOME STATIC HEADER CONTENT --> </footer>
Then let’s see the product index page:
<div class="page-content"> <div class="row"> <div class="col-xs-12"> <section class="intro"> <div ui-</div> </section> </div> </div> <div class="row"> <div class="col-xs-3"> <section class="widget"> <div ui-</div> </section> </div> <div class="col-xs-9"> <section class="content"> <div ui-</div> </section> </div> </div> </div>
As you can see, the product index page has three named views. One for the intro, one for the widget, and one for the product. We meet the specs! So now let’s set up routing:
function config($stateProvider) { $stateProvider // MAIN ABSTRACT STATE, ALWAYS ON .state('main', { abstract: true, url: '/', controller: 'MainController as MC', templateUrl: '/routing-demo/main.html' }) // A SIMPLE HOMEPAGE .state('main.homepage', { url: '', controller: 'HomepageController as HC', templateUrl: '/routing-demo/homepage.html' }) // THE ABOVE IS ALL GOOD, HERE IS TROUBLE // A COMPLEX PRODUCT PAGE .state('main.product', { abstract: true, url: ':id', controller: 'ProductController as PC', templateUrl: '/routing-demo/product.html', }) // PRODUCT DEFAULT SUBSTATE .state('main.product.index', { url: '', views: { 'widget': { controller: 'WidgetController as PWC', templateUrl: '/routing-demo/widget.html' }, 'intro': { controller: 'IntroController as PIC', templateUrl: '/routing-demo/intro.html' }, 'content': { controller: 'ContentController as PCC', templateUrl: '/routing-demo/content.html' } } }) // PRODUCT DETAILS SUBSTATE .state('main.product.details', { url: '/details', views: { 'widget': { controller: 'WidgetController as PWC', templateUrl: '/routing-demo/widget.html' }, 'content': { controller: 'ContentController as PCC', templateUrl: '/routing-demo/content.html' } } }); } angular.module('articleApp', [ 'ui.router' ]) .config(config);
That would be the first approach. Now, what happens when switching between
main.product.index and
main.product.details? The content and widget get reloaded, but we only want to reload the content. This was problematic, and developers actually created routers that would support just that functionality. One of the names for this was sticky views. Fortunately,
ui-router supports that out of the box with absolute named view targeting.
// A COMPLEX PRODUCT PAGE // WITH NO MORE TROUBLE .state('main.product', { abstract: true, url: ':id', views: { // TARGETING THE UNNAMED VIEW IN MAIN.HTML '@main': { controller: 'ProductController as PC', templateUrl: '/routing-demo/product.html' }, // TARGETING THE WIDGET VIEW IN PRODUCT.HTML // BY DEFINING A CHILD VIEW ALREADY HERE, WE ENSURE IT DOES NOT RELOAD ON CHILD STATE CHANGE 'widget@main.product': { controller: 'WidgetController as PWC', templateUrl: '/routing-demo/widget.html' } } }) // PRODUCT DEFAULT SUBSTATE .state('main.product.index', { url: '', views: { 'intro': { controller: 'IntroController as PIC', templateUrl: '/routing-demo/intro.html' }, 'content': { controller: 'ContentController as PCC', templateUrl: '/routing-demo/content.html' } } }) // PRODUCT DETAILS SUBSTATE .state('main.product.details', { url: '/details', views: { 'content': { controller: 'ContentController as PCC', templateUrl: '/routing-demo/content.html' } } });
By moving the state definition to the parent view, which also is abstract, we can preserve the child view from reloading when switching urls which normally affects that child’s siblings. Of course, the widget could be a simple directive. But the point is, it could also be another complex nested state.
There is another way to do this through the use of
$urlRouterProvider.deferIntercept(), but I think that using state configuration is actually better. If you are interested in intercepting routes, I wrote a small tutorial on StackOverflow.
Common Mistake #6: Declaring Everything In The Angular World Using Anonymous Functions
This mistake is of a lighter calibre, and is more a question of style than avoiding AngularJS error messages. You may have previously noticed that I seldom pass anonymous functions to angular internal’s declarations. I usually just define a function first and then pass it in.
This regards more than just functions. I got this approach from reading style guides, especially Airbnb’s and Todd Motto’s. I believe there are several advantages and almost no drawbacks to it.
First of all, you can manipulate and mutate your functions and objects much easier if they are assigned to a variable. Secondly, the code is cleaner and can be easily split into files. That means maintainability. If you don’t want to pollute the global namespace, wrap every file in IIFEs. The third reason is testability. Consider this example:
'use strict'; function yoda() { var privateMethod = function () { // this function is not exposed }; var publicMethod1 = function () { // this function is exposed, but it's internals are not exposed // some logic... }; var publicMethod2 = function (arg) { // THE BELOW CALL CANNOT BE SPIED ON WITH JASMINE publicMethod1('someArgument'); }; // IF THE LITERAL IS RETURNED THIS WAY, IT CAN'T BE REFERRED TO FROM INSIDE return { publicMethod1: function () { return publicMethod1(); }, publicMethod2: function (arg) { return publicMethod2(arg); } }; } angular.module('app', []) .factory('yoda', yoda);
So now we could mock the
publicMethod1, but why should we do that since it is exposed? Wouldn’t it be easier just to spy on the existing method? However, the method is actually another function - a thin wrapper. Take a look at this approach:
function yoda() { var privateMethod = function () { // this function is not exposed }; var publicMethod1 = function () { // this function is exposed, but it's internals are not exposed // some logic... }; var publicMethod2 = function (arg) { // the below call cannot be spied on publicMethod1('someArgument'); // BUT THIS ONE CAN! hostObject.publicMethod1('aBetterArgument'); }; var hostObject = { publicMethod1: function () { return publicMethod1(); }, publicMethod2: function (arg) { return publicMethod2(arg); } }; return hostObject; }
This is not only about style, since in effect the code is more reusable and idiomatic. The developer gets more expressive power. Splitting all code into self-contained blocks just makes it easier.
Common Mistake #7: Doing Heavy Processing In Angular AKA Using Workers
In some scenarios, it may be required to process a large array of complex objects by passing them through a set of filters, decorators, and finally a sorting algorithm. One use case is when the app should work offline or where the performance of displaying data is key. And since JavaScript is single-threaded, it is relatively easy to freeze the browser.
It is also easy to avoid it with web workers. There don’t seem to be any popular libraries that handle that specifically for AngularJS. It might be for the best though, since the implementation is easy.
First, let’s setup the service:
function scoringService($q) { var scoreItems = function (items, weights) { var deferred = $q.defer(); var worker = new Worker('/worker-demo/scoring.worker.js'); var orders = { items: items, weights: weights }; worker.postMessage(orders); worker.onmessage = function (e) { if (e.data && e.data.ready) { deferred.resolve(e.data.items); } }; return deferred.promise; }; var hostObject = { scoreItems: function (items, weights) { return scoreItems(items, weights); } }; return hostObject; } angular.module('app.worker') .factory('scoringService', scoringService);
Now, the worker:
'use strict'; function scoringFunction(items, weights) { var itemsArray = []; for (var i = 0; i < items.length; i++) { // some heavy processing // itemsArray is populated, etc. } itemsArray.sort(function (a, b) { if (a.sum > b.sum) { return -1; } else if (a.sum < b.sum) { return 1; } else { return 0; } }); return itemsArray; } self.addEventListener('message', function (e) { var reply = { ready: true }; if (e.data && e.data.items && e.data.items.length) { reply.items = scoringFunction(e.data.items, e.data.weights); } self.postMessage(reply); }, false);
Now, inject the service as usual and treat
scoringService.scoreItems() as you would any service method that returns a promise. The heavy processing will be carried out on a separate thread, and no harm will be done to the UX.
What to look out for:
there does not seem to be a general rule for how many workers to spawn. Some developers claim that 8 is a good number, but use an online calculator and suit yourself
check compatibility with older browsers
I run into an issue when passing the number 0 from the service to the worker. I applied .toString() on the passed property, and it worked correctly.
Common Mistake #8: Overusing And Misunderstanding Resolves
Resolves add extra time to the loading of the view. I believe that high performance of the front-end app is our primary goal. It should not be a problem to render some parts of the view while the app waits for the data from the API.
Consider this setup:
function resolve(index, timeout) { return { data: function($q, $timeout) { var deferred = $q.defer(); $timeout(function () { deferred.resolve(console.log('Data resolve called ' + index)); }, timeout); return deferred.promise; } }; } function configResolves($stateProvide) { $stateProvider // MAIN ABSTRACT STATE, ALWAYS ON .state('main', { url: '/', controller: 'MainController as MC', templateUrl: '/routing-demo/main.html', resolve: resolve(1, 1597) }) // A COMPLEX PRODUCT PAGE .state('main.product', { url: ':id', controller: 'ProductController as PC', templateUrl: '/routing-demo/product.html', resolve: resolve(2, 2584) }) // PRODUCT DEFAULT SUBSTATE .state('main.product.index', { url: '', views: { 'intro': { controller: 'IntroController as PIC', templateUrl: '/routing-demo/intro.html' }, 'content': { controller: 'ContentController as PCC', templateUrl: '/routing-demo/content.html' } }, resolve: resolve(3, 987) }); }
The console output will be:
Data resolve called 3 Data resolve called 1 Data resolve called 2 Main Controller executed Product Controller executed Intro Controller executed
Which basically means that:
— The resolves are executed asynchronously
— We can’t rely on an order of execution (or at least need to flex quite a bit)
— All the states are blocked until all resolves do their thing, even if they are not abstract.
This means that before the user sees any output, he/she must wait for all the dependencies. We need to have that data, sure, okay. If it absolutely necessary to have it before the view, put it in a
.run() block. Otherwise, just make the call to the service from the controller and handle the half-loaded state gracefully. Seeing work in progress - and the controller is already executed, so it actually is progress - is better than having the app stall.
Common Mistake #9: Not Optimizing The App - Three Examples
a) Causing too many digest loops, such as attaching sliders to models
This is a general problem that can result in AngularJS errors, but I will discuss it at the example of sliders. I was using this slider library, angular range slider, because I needed the extended functionality. That directive has this syntax in the minimal version:
<body ng-controller=“MainController as MC”> <div range-slider min="0” max=“MC.maxPrice” pin-handle="min” model-max=“MC.price” > </div> </body>
Consider the following code in the controller:
this.maxPrice = '100'; this.price = '55’; $scope.$watch('MC.price', function (newVal) { if (newVal || newVal === 0) { for (var i = 0; i < 987; i++) { console.log('ALL YOUR BASE ARE BELONG TO US'); } } });
So that works slow. The casual solution would be to set a timeout on the input. But that is not always handy, and sometimes we don’t really want to delay the actual model change in all cases.
So we will add a temporary model bound to change the working model on timeout:
<body ng-controller=“MainController as MC”> <div range-slider min="0” max=“MC.maxPrice” pin-handle="min” model-max=“MC.priceTemporary” > </div> </body>
and in the controller:
this.maxPrice = '100'; this.price = '55’; this.priceTemporary = '55'; $scope.$watch('MC.price', function (newVal) { if (!isNaN(newVal)) { for (var i = 0; i < 987; i++) { console.log('ALL YOUR BASE ARE BELONG TO US'); } } }); var timeoutInstance; $scope.$watch('MC.priceTemporary', function (newVal) { if (!isNaN(newVal)) { if (timeoutInstance) { $timeout.cancel(timeoutInstance); } timeoutInstance = $timeout(function () { $scope.MC.price = newVal; }, 144); } });
b) Not using $applyAsync
AngularJS does not have a polling mechanism to call $digest(). It is only executed because we use the directives (e.g. ng-click, input), services ($timeout, $http), and methods ($watch) which evaluate our code and call a digest afterwards.
What
.$applyAsync() does is it delays the resolution of expressions until the next $digest() cycle, which is triggered after a 0 timeout, which actually is ~10ms.
There are two ways to use applyAsync now. An automated way for $http requests, and a manual way for the rest.
To make all http requests that return in around the same time resolve in one digest, do:
mymodule.config(function ($httpProvider) { $httpProvider.useApplyAsync(true); });
The manual way shows how it actually works. Consider some function that runs on the callback to a vanilla JS event listener or a jQuery
.click(), or some other external library. After it executes and changes models, if you didn’t already wrap it in an
$apply() you need to call
$scope.$root.$digest() (
$rootScope.$digest()), or at least
$scope.$digest(). Otherwise, you will see no change.
If you do that multiple times in one flow, it might start running slow. Consider calling
$scope.$applyAsync() on the expressions instead. It will set only call one digest cycle for all of them.
c) Doing heavy processing of images
If you experience bad performance, you can investigate the reason by using the Timeline from Chrome Developer Tools. I will write more about this tool in mistake #17. If your timeline graph is dominated with the color green after recording, your performance issues may be related to processing of images. This is not strictly related to AngularJS, but may happen on top of AngularJS performance issues (which would be mostly yellow on the graph). As front-end engineers, we need to think about the complete end project.
Take a moment to assess:
Do you use parallax?
Do you have several layers of content overlapping one another?
Do you move your images around?
Do you scale images (e.g. with background-size)?
Do you resize images in loops, and perhaps cause digest loops on resize?
If you answered “yes” to at least three of the above, consider easing it. Perhaps you can serve various image sizes and not resize at all. Maybe you could add the “transform: translateZ(0)” force GPU processing hack. Or use requestAnimationFrame for handlers.
Common Mistake #10: jQuerying It - Detached DOM Tree
Many times you probably hear that it’s not recommended to use jQuery with AngularJS, and that it should be avoided. It is imperative to understand the reason behind these statements. There are at least three reasons, as far as I can see, but none of them are actual blockers.
Reason 1: When you execute jQuery code, you need to call
$digest() yourself. For many cases, there is an AngularJS solution which is tailored for AngularJS and can be of better use inside Angular than jQuery (e.g. ng-click or the event system).
Reason 2: The method of thought about building the app. If you have been adding JavaScript to websites, which reload when navigating, you did not have to worry about memory consumption too much. With single-page apps, you do have to worry. If you don’t clean up, users who spend more than a few minutes on your app may experience growing performance issues.
Reason 3: Cleaning up is not actually the easiest thing to do and analyze. There is no way to call a garbage collector from the script (in the browser). You may end up with detached DOM trees. I created an example (jQuery is loaded in index.html):
<section> <test-for-toptal></test-for-toptal> <button ng-remove directive</button> </section>
function MainController($rootScope, $scope) { this.removeDirective = function () { $rootScope.$emit('destroyDirective'); }; } function testForToptal($rootScope, $timeout) { return { link: function (scope, element, attributes) { var destroyListener = $rootScope.$on('destroyDirective', function () { scope.$destroy(); }); // adding a timeout for the DOM to get ready $timeout(function () { scope.toBeDetached = element.find('p'); }); scope.$on('$destroy', function () { destroyListener(); element.remove(); }); }, template: '<div><p>I AM DIRECTIVE</p></div>' }; } angular.module('app', []) .controller('MainController', MainController) .directive('testForToptal', testForToptal);
This is a simple directive that outputs some text. There is a button below it, which will just destroy the directive manually.
So when the directive is removed, there remains a reference to the DOM tree in scope.toBeDetached. In chrome dev tools, if you access the tab “profiles” and then “take heap snapshot”, you will see in the output:
You can live with a few, but it is bad if you have a ton. Especially if for some reason, like in the example, you store it on the scope. The whole DOM will be evaluated on every digest. The problematic detached DOM tree is the one with 4 nodes. So how can this be solved?
scope.$on('$destroy', function () { // setting this model to null // will solve the problem. scope.toBeDetached = null; destroyListener(); element.remove(); });
The detached DOM tree with 4 entries is removed!
In this example, the directive uses the same scope, and stores the DOM element on the scope. It was easier for me to demonstrate it that way. It does not always get that bad, as you could store it in a variable. However, it would still take up memory if any closure that had referenced that variable or any other from the same function scope lived on.
Common Mistake #11: Overusing Isolated Scope
Whenever you need a directive that you know will be used in a single place, or which you don’t expect to conflict with whatever environment it is used in, there is no need to use isolated scope. Lately, there is a trend to create reusable components, but did you know that core angular directives don’t use isolated scope at all?
There are two main reasons: you can’t apply two isolated scope directives to an element, and you may encounter issues with nesting / inheritance / event processing. Especially regarding transclusion - the effects may not be what you expect.
So this would fail:
<p isolated-scope-directive another-isolated-scope-directive ng-if="MC.quux" ng-repeat="q in MC.quux”></p>
And even if you use just one directive, you will notice that neither the isolated scope models nor events broadcasted in isolatedScopeDirective will not be available to AnotherController. That being sad, you can flex and use transclusion magic to make it work - but for most use cases, there is no need to isolate.
<p isolated-scope-directive <div ng- … the isolated scope is not available here, look: {{ isolatedModel }} </div> </p>
So, two questions now:
How can you process parent scope models in a same-scope directive?
How can you instantiate new model values?
There are two ways, in both of them you pass values to attributes. Consider this MainController:
function MainController($interval) { this.foo = { bar: 1 }; this.baz = 1; var that = this; $interval(function () { that.foo.bar++; }, 144); $interval(function () { that.baz++; }, 144); this.quux = [1,2,3]; }
That controls this view:
<body ng- <div class="cyan-surface"> <h1 style="font-size: 21px;">Attributes test</h1> <test-directive</test-directive> </div> </body>
Notice that “watch-attribute” is not interpolated. It all works, due to JS magic. Here is the directive definition:
function testDirective() { var postLink = function (scope, element, attrs) { scope.$watch(attrs.watchAttribute, function (newVal) { if (newVal) { // take a look in the console // we can't use the attribute directly console.log(attrs.watchAttribute); // the newVal is evaluated, and it can be used scope.modifiedFooBar = newVal.bar * 10; } }, true); attrs.$observe('observeAttribute', function (newVal) { scope.observed = newVal; }); }; return { link: postLink, templateUrl: '/attributes-demo/test-directive.html' }; }
Notice that
attrs.watchAttribute is passed into
scope.$watch() without the quotation marks! That means what was actually passed to $watch was the string
MC.foo! It does work, however, because any string passed into
$watch() gets evaluated against the scope and
MC.foo is available on the scope. That is also the most common way that attributes are watched in AngularJS core directives.
See the code on github for the template, and look into
$parse and
$eval for even more awesomeness.
Common Mistake #12: Not Cleaning Up After Yourself - Watchers, Intervals, Timeouts And Variables
AngularJS does some work on your behalf, but not all. The following need to be manually cleaned up:
Any watchers that are not bound to the current scope (e.g. bound to $rootScope)
Intervals
Timeouts
Variables referencing DOM in directives
Dodgy jQuery plugins, e.g. those that don’t have handlers reacting to the JavaScript
$destroyevent
If you don’t do that manually, you will encounter unexpected behaviour and memory leaks. Even worse - these will not be instantly visible, but they will creep up eventually. Murphy’s law.
Amazingly, AngularJS provides handy ways to deal with all of those:
function cleanMeUp($interval, $rootScope, $timeout) { var postLink = function (scope, element, attrs) { var rootModelListener = $rootScope.$watch('someModel', function () { // do something }); var myInterval = $interval(function () { // do something in intervals }, 2584); var myTimeout = $timeout(function () { // defer some action here }, 1597); scope.domElement = element; $timeout(function () { // calling $destroy manually for testing purposes scope.$destroy(); }, 987); // here is where the cleanup happens scope.$on('$destroy', function () { // disable the listener rootModelListener(); // cancel the interval and timeout $interval.cancel(myInterval); $timeout.cancel(myTimeout); // nullify the DOM-bound model scope.domElement = null; }); element.on('$destroy', function () { // this is a jQuery event // clean up all vanilla JavaScript / jQuery artifacts here // respectful jQuery plugins have $destroy handlers, // that is the reason why this event is emitted... // follow the standards. }); };
Notice the jQuery
$destroy event. It is called like the AngularJS one, but it is handled separately. Scope $watchers will not react to the jQuery event.
Common Mistake #13: Keeping Too Many Watchers
This should be quite simple now. There is one thing to understand here:
$digest(). For every binding
{{ model }}, AngularJS creates a watcher. On every digest phase, each such binding is evaluated and compared against the previous value. That is called dirty-checking, and that’s what $digest does. If the value changed since the last check, the watcher callback is fired. If that watcher callback modifies a model ($scope variable), a new $digest cycle is fired (up to a maximum of 10) when an exception is thrown.
Browsers don’t have problems even with thousands of bindings, unless the expressions are complex. The common answer for “how many watchers are ok to have” is 2000.
So, how can we limit the number of watchers? By not watching scope models when we don’t expect them to change. It is fairly easy onwards from AngularJS 1.3, since one-time bindings are in core now.
<li ng-repeat=“item in ::vastArray”>{{ ::item.velocity }}</li>
After
vastArray and
item.velocity are evaluated once, they will never change again. You can still apply filters to the array, they will work just fine. It is just that the array itself will not be evaluated. In many cases, that is a win.
Common Mistake #14: Misunderstanding The Digest
This AngularJS error was already partly covered in mistakes 9.b and in 13. This is a more thorough explanation.
AngularJS updates DOM as a result of callback functions to watchers. Every binding, that is the directive
{{ someModel }} sets up watchers, but watchers are also set for many other directives like
ng-if and
ng-repeat. Just take a look at the source code, it is very readable. Watchers can also be set manually, and you have probably done that at least a few times yourself.
$watch()
’ers are bound to scopes. $Watchers can take strings, which are evaluated against the scope that the $watch() was bound to. They can also evaluate functions. And they also take callbacks. So, when $rootScope.$digest()` is called, all the registered models (that is $scope variables) are evaluated and compared against their previous values. If the values don’t match, the callback to the $watch() is executed.
It is important to understand that even though a model’s value was changed, the callback does not fire until the next digest phase. It is called a “phase” for a reason - it can consist of several digest cycles. If only a watcher changes a scope model, another digest cycle is executed.
But $digest() is not polled for. It is called from core directives, services, methods, etc. If you change a model from a custom function that does not call
.$apply,
.$applyAsync,
.$evalAsync, or anything else that eventually calls
$digest(), the bindings will not be updated.
By the way, the source code for
$digest() is actually quite complex. It is nevertheless worth reading, as the hilarious warnings make up for it.
Common Mistake #15: Not Relying On Automation, Or Relying On It Too Much
If you follow the trends within front end development and are a bit lazy - like me - then you probably try to not do everything by hand. Keeping track of all your dependencies, processing sets of files in different ways, reloading the browser after every file save - there is a lot more to developing than just coding.
So you may be using bower, and maybe npm depending on how you serve your app. There is a chance that you may be using grunt, gulp, or brunch. Or bash, which also is cool. In fact, you may have started your latest project with some Yeoman generator!
This leads to the question: do you understand the whole process of what your infrastructure really does? Do you need what you have, especially if you just spent hours trying to fix your connect webserver livereload functionality?
Take a second to assess what you need. All those tools are only here to aid you, there is no other reward for using them. The more experienced developers I talk to tend to simplify things.
Common Mistake #16: Not Running The Unit Tests In TDD Mode
Tests will not make your code free of AngularJS error messages. What they will do is assure that your team doesn’t run into regression issues all the time.
I am writing specifically about unit tests here, not because I feel they are more important than e2e tests, but because they execute much faster. I must admit that the process I am about to describe is a very pleasurable one.
Test Driven Development as an implementation for e.g. gulp-karma runner, basically runs all your unit tests on every file save. My favorite way to write tests is, I just write empty assurances first:
describe(‘some module’, function () { it(‘should call the name-it service…’, function () { // leave this empty for now }); ... });
After that, I write or refactor the actual code, then I come back to the tests and fill in the assurances with actual test code.
Having a TDD task running in a terminal speeds up the process by about 100%. Unit tests execute in a matter of a few seconds, even if you have a lot of them. Just save the test file and the runner will pick it up, evaluate your tests, and provide feedback instantly.
With e2e tests, the process is much slower. My advice - split e2e tests up into test suites and just run one at a time. Protractor has support for them, and below is the code I use for my test tasks (I like gulp).
'use strict'; var gulp = require('gulp'); var args = require('yargs').argv; var browserSync = require('browser-sync'); var karma = require('gulp-karma'); var protractor = require('gulp-protractor').protractor; var webdriverUpdate = require('gulp-protractor').webdriver_update; function test() { // Be sure to return the stream // NOTE: Using the fake './foobar' so as to run the files // listed in karma.conf.js INSTEAD of what was passed to // gulp.src ! return gulp.src('./foobar') .pipe(karma({ configFile: 'test/karma.conf.js', action: 'run' })) .on('error', function(err) { // Make sure failed tests cause gulp to exit non-zero // console.log(err); this.emit('end'); //instead of erroring the stream, end it }); } function tdd() { return gulp.src('./foobar') .pipe(karma({ configFile: 'test/karma.conf.js', action: 'start' })) .on('error', function(err) { // Make sure failed tests cause gulp to exit non-zero // console.log(err); // this.emit('end'); // not ending the stream here }); } function runProtractor () { var argument = args.suite || 'all'; // NOTE: Using the fake './foobar' so as to run the files // listed in protractor.conf.js, instead of what was passed to // gulp.src return gulp.src('./foobar') .pipe(protractor({ configFile: 'test/protractor.conf.js', args: ['--suite', argument] })) .on('error', function (err) { // Make sure failed tests cause gulp to exit non-zero throw err; }) .on('end', function () { // Close browser sync server browserSync.exit(); }); } gulp.task('tdd', tdd); gulp.task('test', test); gulp.task('test-e2e', ['webdriver-update'], runProtractor); gulp.task('webdriver-update', webdriverUpdate);
Common Mistake #17: Not Using The Available Tools
A - chrome breakpoints
Chrome dev tools allow you to point at a specific place in any of the files loaded into the browser, pause code execution at that point, and let you interact with all the variables available from that point. That is a lot! That functionality does not require you to add any code at all, everything happens in the dev tools.
Not only you get access to all the variables, you also see the call stack, print stack traces, and more. You can even configure it to work with minified files. Read about it here.
There are other ways you can get similar run-time access, e.g. by adding
console.log() calls. But breakpoints are more sophisticated.
AngularJS also allows you to access scope through DOM elements (as long as debugInfo is enabled), and inject available services through the console. Consider the following in the console:
$(document.body).scope().$root
or point at an element in the inspector, and then:
$($0).scope()
Even if debugInfo is not enabled, you can do:
angular.reloadWithDebugInfo()
And have it available after reload:
To inject and interact with a service from the console, try:
var injector = $(document.body).injector(); var someService = injector.get(‘someService’);
B - chrome timeline
Another great tool that comes with dev tools is the timeline. That will allow you to record and analyse your app’s live performance as you are using it. The output shows, among others, memory usage, frame rate, and the dissection of the different processes that occupy the CPU: loading, scripting, rendering, and painting.
If you experience that your app’s performance degrades, you will most likely be able to find the cause for that through the timeline tab. Just record your actions which led to performance issues and see what happens. Too many watchers? You will see yellow bars taking a lot of space. Memory leaks? You can see how much memory was consumed over time on a graph.
A detailed description:
C - inspecting apps remotely on iOS and Android
If you are developing a hybrid app or a responsive web app, you can access your device’s console, DOM tree, and all other tools available either through Chrome or Safari dev tools. That includes the WebView and UIWebView.
First, start your web server on host 0.0.0.0 so that it is accessible from your local network. Enable web inspector in settings. Then connect your device to your desktop and access your local development page, using your machine’s ip instead of the regular “localhost”. That is all it takes, your device should now be available to you from your desktop’s browser.
Here are the detailed instructions for Android And for iOS, unofficial guides are to be found easily through google.
I recently had some cool experience with browserSync. It works in a similar way to livereload, but it also actually syncs all browsers that are viewing the same page through browserSync. That includes user interaction such as scrolling, clicking on buttons, etc. I was looking at the iOS app’s log output while controlling the page on the iPad from my desktop. It worked nicely!
Common Mistake #18: Not Reading The Source Code On The NG-INIT Example
Ng-init, from the sound of it, should be similar to
ng-if and
ng-repeat, right? Did you ever wonder why there is a comment in the docs that it should not be used? IMHO that was surprising! I would expect the directive to initialize a model. That’s also what it does, but… it is implemented in a different way, that is, it does not watch the attribute value. You don’t need to browse through AngularJS source code - let me bring it to you:
var ngInitDirective = ngDirective({ priority: 450, compile: function() { return { pre: function(scope, element, attrs) { scope.$eval(attrs.ngInit); } }; } });
Less than you would expect? Quite readable, besides the awkward directive syntax, isn’t it? The sixth line is what it is all about.
Compare it to ng-show:
var ngShowDirective = ['$animate', function($animate) { return { restrict: 'A', multiElement: true, link: function(scope, element, attr) { scope.$watch(attr.ngShow, function ngShowWatchAction(value) { // we're adding a temporary, animation-specific class for ng-hide since this way // we can control when the element is actually displayed on screen without having // to have a global/greedy CSS selector that breaks when other animations are run. // Read: $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, { tempClasses: NG_HIDE_IN_PROGRESS_CLASS }); }); } }; }];
Again, the sixth line. There is a
$watch there, that’s what makes this directive dynamic.
In the AngularJS source code, a big part of all the code are comments that describe code that was mostly readable from the beginning. I believe it is a great way to learn about AngularJS.
Conclusion
This guide covering most common AngularJS mistakes is almost twice as long as the other guides. It turned out that way naturally. The demand for high quality JavaScript front end engineers is very high. AngularJS is so hot right now, and it has been holding a stable position among the most popular development tools for a few years. With AngularJS 2.0 on the way, it will probably dominate for years to come.
What is great about front-end development is that it is very rewarding. Our work is visible instantly, and people interact directly with the products we deliver. The time spent learning JavaScript, and I believe we should focus on the JavaScript language, is a very good investment. It is the language of the Internet. The competition is super strong! There is one focus for us - user experience. To be successful, we need to cover everything.
Source code used in these examples can be downloaded from GitHub. Feel free to download it and make it your own.
I wanted to give credits to four publishing developers that inspired me the most:
I also wanted to thank all the great people on FreeNode #angularjs and #javascript channels for many excellent conversations, and continuous support.
And finally, always remember:
// when in doubt, comment it out! :) | https://www.toptal.com/angular-js/top-18-most-common-angularjs-developer-mistakes | CC-MAIN-2017-09 | refinedweb | 7,093 | 58.58 |
Nicolae - please consider this a higher priority than the higher-order function work; if you could work on it in the next couple of weeks that would be great. We really want this in 2.7, whereas the higher-order function features are on the bubble.
Advertising
** Changed in: zorba Milestone: None => 2.7 -- You received this bug notification because you are a member of Zorba Coders, which is the registrant for Zorba. Title: xml:parse unable to parse content containing a DOCTYPE Status in Zorba - The XQuery Processor: New Bug description: The xml:parse function is unable to parse an XML document/fragment if it starts with a doctype definition. For example, import module namespace </opt:options>) return $i with tmp.xml containing <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" ""> <a><b/></a> raises [err:FODC0006]: invalid content passed to parse-xml:parse(): loader parsing error: internal error; To manage notifications about this bug go to: -- Mailing list: Post to : zorba-coders@lists.launchpad.net Unsubscribe : More help : | https://www.mail-archive.com/zorba-coders@lists.launchpad.net/msg11078.html | CC-MAIN-2016-50 | refinedweb | 171 | 56.25 |
Registering Extensions with Entry Points¶
Often, third party packages will have a user-facing API as well as define
extensions to the Numba compiler. In those situations, the new types and
overloads can registered with Numba when the package is imported by the user.
However, there are situations where a Numba extension would not normally be
imported directly by the user, but must still be registered with the Numba
compiler. An example of this is the numba-scipy package, which adds support for some
SciPy functions to Numba. The end user does not need to
import
numba_scipy to enable compiler support for SciPy, the extension only needs
to be installed in the Python environment.
Numba discovers extensions using the entry points
feature of
setuptools. This allows a Python package to register an
initializer function that will be called before
numba compiles for the
first time. The delay ensures that the cost of importing extensions is
deferred until it is necessary.
Adding Support for the “Init” Entry Point¶
A package can register an initialization function with Numba by adding the
entry_points argument to the
setup() function call in
setup.py:
setup( ..., entry_points={ "numba_extensions": [ "init = numba_scipy:_init_extension", ], }, ... )
Numba currently only looks for the
init entry point in the
numba_extensions group. The entry point should be a function (any name,
as long as it matches what is listed in
setup.py) that takes no arguments,
and the return value is ignored. This function should register types,
overloads, or call other Numba extension APIs. The order of initialization of
extensions is undefined.
Testing your Entry Point¶
Numba loads all entry points when the first function is compiled. To test your
entry point, it is not sufficient to just
import numba; you have to define
and run a small function, like this:
import numba; numba.njit(lambda x: x + 1)(123)
It is not necessary to import your module: entry points are identified by the
entry_points.txt file in your library’s
*.egg-info directory.
The
setup.py build command does not create eggs, but
setup.py sdist
(for testing in a local directory) and
setup.py install do. All entry points
registered in eggs that are on the Python path are loaded. Be sure to check for
stale
entry_points.txt when debugging. | https://numba.readthedocs.io/en/stable/extending/entrypoints.html | CC-MAIN-2021-10 | refinedweb | 378 | 56.76 |
Components and supplies
Apps and online services
About this project
Note: Pulse width modulation(PWM) is an important component of servo operation. Please read this article if you're unfamiliar with PWM before proceeding.
Introduction to Servos
The term servo originates from servomechanism, which refers to any system that uses negative feedback to correct its position or speed. A negative feedback system feeds its output into the input in order to provide error correction or speed limitation. The first example of a mechanical negative feedback system was an 18th-century steam engine governor, which used the engine speed as an input in a mechanical system to cap the engine speed at a safe rate. A cruise control system is a modern example of a servomechanism because the speed of the car influences the throttle position, which is adjusted to maintain the desired speed.
Servomotors are a subcategory of servomechanisms, and are usually what people are referring to when they say servo. Servomotors use digital encoders or potentiometers to determine the position of the drive shaft. They are used in a wide array of industrial and personal applications such as valve control, robotic parts, and actuators for hobby projects.
This write-up will be focused on electronic servos used in remote control applications, since these are most commonly used in hobbyist projects. R/C servo operational principles will be discussed, followed by a demonstration of how to characterize a servo using an OpenScope device.
Feedback System
R/C servos, like their industrial counterparts, have a feedback system that allows for precise position control. If something tries to move the DC motor from a particular position, say a rudder encountering air resistance on an R/C airplane, the servo will apply additional force to recover and maintain the position.
The error correction system is comprised of a potentiometer, which is attached to the motor's output shaft, and an error amplifier. The error amplifier has two input signals that it is comparing: the current position of the motor, provided by the potentiometer, and the desired position of the motor, provided by the controller signal. When the signals don't match, the output from the amplifier drives the motor to make the inputs match.
In order to change the position of the servo, the error amplifier needs to have a variable analog voltage applied to the controller pin. Generating a precise analog voltage requires integrated circuits that can be quite expensive, so many microcontrollers don't have this ability, and instead rely on PWM to simulate analog voltages.
As the article about PWM (linked above) discusses, a capacitor receiving a PWM signal will tend to average out the signal voltage. For example, a 50% duty cycle with a 5V peak will cause the capacitor to hold a voltage equal to approximately half the signal's max, or 2.5V. By varying the amount of time the PWM signal is high, the capacitor charge can be varied, thus creating an analog voltage. The screenshots below demonstrate this concept with a PWM signal being fed into a resistor-capacitor circuit.
Servos use a similar concept to set the position of the motor. As the charge on the capacitor varies with the amount of time it receives a high signal, the servo's error amplifier will see a difference between the potentiometer and the capacitor. The output will then cause the motor to move to a position that will match the potentiometer's voltage to the capacitor's voltage. Of course, a lot more hardware goes into making the servo operate correctly, but these are the basic concepts.
Most servos have a range of motion limited to 180°, but some are designed for a smaller or larger range, or are able to rotate continuously (in which case the speed, not the position, is controlled by the pulse width).
R/C servos vary by design, but a pulse width of 1.5ms will cause the servo to move to the neutral position, halfway through its range of motion, or stop in the case of continuously rotating units. The pulse widths needed to move the servo to the two extremes (or the maximum forward/backward speed) depend on the servo itself, but all R/C servos have the same neutral position pulse width (1.5ms).
Arduino Servo Library
Arduino comes with a library designed for operating servos. While controlling a servo directly via PWM is entirely possible, it's much easier to use the Servo library. Including "Servo.h" at the beginning of the code is all that's needed to start using the library.
It might be necessary to change the control signal pulse width limits to use the servo's full range of motion. By default, these limits are set to 544ms and 2, 400ms. The servo used in this demonstration required the limits to be set to 550ms and 2, 650ms to achieve 180° of motion.
Servo Characterization with OpenScope
OpenScope along with WaveForms Live can be used to characterize the servo and find its pulse width limits.
A potentiometer is used to select the servo position in this demonstration, as seen in the schematic below. Use the code attached at the end to operate the servo.
From the OpenScope, attach the orange oscilloscope cable to PWM pin 9, and the blue oscilloscope cable to the analog input pin A0. The first cable will monitor the signals being sent to the servo, and the second cable will monitor the voltage level in the potentiometer used to set the servo position. Ensure that the two oscilloscope ground cables are attached to the Arduino's ground.
Initially, move the potentiometer from one extreme to the other to see if the servo is able to achieve its full range of motion. If it isn't, the limits are too tight and need to be expanded. Even if the servo is able to achieve its full range of motion it is necessary to check that the limits are not set too far, which would cause a dead zone in the input (something that might be undesirable if the servo is being used as a gauge, for example).
Connect the OpenScope to WaveForms Live and perform the following steps to configure the display to show information relevant to the characterization:
- At the top of the screen, in the Time option type "1ms".
- Under the Trigger section click the RisingEdgeTrigger button (hover the mouse over each button to see its name). For Source select "Osc Ch 1" and leave Level at "500mV".
- Under both the OscCh1 and the OscCh2 sections, change Volts to "2V". Leave all the other settings at their defaults.
- At the bottom of the WaveForms Live screen is a button labeled CURSORS. Press it and in the dialog select the following: under Type select "Time", under Cursor1Channel select "Osc 1", and under Cursor2Channel select "Osc 2". An orange and blue cursor should appear on the display. Use the arrows at the top of the cursors to drag them around. Place the blue cursor on the left side of the green line, and leave the yellow one alone for now.
On line11 in the code, the attach() function is used to set pin 9 as the servo control pin, while the second and third values are used to set the pulse width in microseconds. The time values will need to be changed if the default ones do not allow full range of motion or are causing dead zones. For now, leave the values as they are (544 and 2400) and upload the code to the Arduino Uno.
Press the Run button in WaveForms Live, and set the potentiometer back to one of its extremes. At this point the orange line (oscilloscope Channel 1) in WaveForms Live should be showing up as a square pulse, and the blue line (Channel 2) should either be at a constant 0V or 5V, depending on which direction the potentiometer was connected. The value of Channel 2 can be seen at the bottom of the screen, after the "2:...". If the value is near zero (or a few hundred uV), set the potentiometer to the other extreme so that the value is near 5V. At this point, the WaveForms Live screen should look similar to the one below.
If the full range of motion is not available, it's likely a result of the larger pulse width value being too small. The shorter pulse width is probably within an acceptable range, as making the pulse width much shorter caused the demonstration servo to behave erratically instead of extending the rotation range. Set the third value in the attach() function to something large, like 2800, and after uploading the code, check to see if the full range is being used. Otherwise, try increasing the value again.
Once the full range of motion has been established, it's necessary to trim down the pulse width to remove any dead zone that might exist at the extreme positions of the potentiometer. To detect the dead zone, place the potentiometer in the position that causes Channel 2 to show 5V and keep WaveForms Live in Run mode. Hold the servo between two fingers, and slowly turn the knob back on the potentiometer. As soon as vibrations from the servo are felt, stop turning the knob. This is the DC motor in the servo engaging, which means it is responding to changes in the pulse width. Ensure that the servo is right on the cusp of engaging by turning the knob slightly up and down to find the exact spot (this doesn't have to be perfect, but closer is better).
Alternately, it's possible to detect servo engagement by watching the Channel 2 signal for a dip immediately following the signal pulse end on Channel 1. This is caused by the DC motor drawing current and slightly pulling down the 5V supply voltage. See the image below to see the dip.
In WaveForms Live, press Stop and drag the Channel 1 cursor so that it intersects with the orange line right at the point where the pulse drops to 0. Then look at the value at the bottom of the screen, after the "1:...". The voltage should be in the milli- or micro-volt range. The blue line should be slightly down from 5V, unless the servo responded immediately to the knob rotation, in which case the pulse width is correct. See the image below for clarification.
In the cursor measurements at the bottom of the screen, the time value expressed in milliseconds is the maximum pulse width the servo will respond to. Use this time in the attach() function as the third value. Note that the attach() function accepts pulse width values in microseconds, while the value in WaveForms Live will be in milliseconds, so the value will need to be multiplied by 1000 before placing it in the code.
To check that the pulse width is correct, upload the code with the updated value, and see if the servo responds immediately to the knob being moved. Also ensure the servo still has its full range of motion.
The servo code is now ready to be integrated into a larger project, and will allow the full range of the servo to be utilized without any dead zones.
Code
Servo CharacterizationArduino
#include <Servo.h> // create a servo object Servo servo; //analog input from the potentiometer int potPos = A0; void setup() { // link the servo to pin 9, and set the pulse width limits (544ms and 2400ms in this case) servo.attach(9, 544,2400); //set the analog pin as an input pinMode(potPos, INPUT); } void loop() { //store the potentiometer position as a float float level = analogRead(potPos); //calculate analog data as a voltage float voltage = 5*level/1024; //make sure the voltage isn't outside the acceptable range if(voltage < 0){ voltage = 0; } if(voltage > 5){ voltage = 5; } //scale voltage to 180 degrees servo.write(36 * voltage); //give the servo time to move to new position delay(15); }
Team members
Boris Leonov
- 9 projects
- 12 followers
Sam Kristoff
- 9 projects
- 25 followers
Arthur Brown
- 9 projects
- 11 followers
Published onJuly 12, 2018
Members who respect this project
you might like | https://create.arduino.cc/projecthub/104085/servo-signals-and-characterization-dad271 | CC-MAIN-2019-13 | refinedweb | 2,041 | 57.71 |
The QSqlDriverPlugin class provides an abstract base for custom QSqlDriver plugins. More...
#include <qsqldriverplugin.h>
List of all member functions.
The.
See also Plugins.
You never have to call this explicitly. Qt destroys a plugin automatically when it is no longer used.
Creates and returns a QSqlDriver object for the driver key key. The driver key is usually the class name of the required driver.
See also keys().
Returns the list of drivers (keys) this plugin supports.
These keys are usually the class names of the custom drivers that are implemented in the plugin.
See also create().
This file is part of the Qt toolkit. Copyright © 1995-2003 Trolltech. All Rights Reserved. | http://vision.lbl.gov/People/qyang/qt_doc/qsqldriverplugin.html | CC-MAIN-2014-41 | refinedweb | 112 | 71.92 |
From: Glen Fernandes (glen.fernandes_at_[hidden])
Date: 2019-06-27 04:59:30
On Thu, Jun 27, 2019 at 12:23 AM Gavin Lambert wrote:
>
>"...
Right. ADL was just one suggestion of many by Andrey. Another
suggestion was trait specialization. Nobody is against specialization,
or opening namespaces. ADL can be avoided too. But there is value in
not having to re-implement out_ptr_t by a full specialization of it.
At that point the author of LibX doesn't care about LibZ::out_ptr and
LibZ::out_ptr_t at all: they would just be implementing LibX::out_ptr
and LibX::detail::out_ptr_t.
> >.
It's not a good idea. I believe the author when he says that there are
users who refuse to use the version without UB because they need the
performance; he has that data. But that doesn't justify the UB in
Boost.
> And "UB-based optimization" does not inspire confidence.
Glen
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2019/06/246439.php | CC-MAIN-2022-40 | refinedweb | 172 | 70.5 |
Things I learned about Pyspark the hard way
Why Spark?
Lately I have been working on a project that requires cleaning and analyzing a large volume of event-level data.
Originally, I did some exploratory data analysis on small samples of data (up to 15 million rows) using pandas, my usual data visualization tools, and multiprocessing. But then it was time to scale up.
Why Spark is good for this
Distributed processing means it’s very fast at very large scale, and we can scale it up with minimal adjustments (the same code still works, we just need a bigger cluster).
It’s very readable, re-usable and unit-testable. That means it’s very maintainable, which makes it easier to hand off than some older map reduce tools (my team has traditionally used Pig).
The output can be dataframes, or tables in various formats.
It also incorporates SQL, which can be used for filtering, joining, grouping, and aggregations.
Finally, it has functionality for machine learning, which means we could build the next parts of this project in the same place using the same tools, which also makes it easier to maintain.
What my python script was doing
- Read in files
- Filter for the types of rows we care about
- Parse out some fields
- Run some helper functions to make some things more human-readable
- Deal with missing values
- Convert some fields to boolean flags
- Optional steps to join to other tables, group, aggregate, etc.
- Write out a pandas dataframe and/or CSV files, with or without compression
My first question: why is making dataframes in spark so hard?
First, there are too many ways to do it. Most of the ways I found on Teh Internet don’t work because the syntax is changing so rapidly, and there are a lot of unwritten rules. Also, it’s a lot dumber than pandas. Pandas is really good at two things that make your life easy, and if you’re just starting out with pyspark you will miss these things dearly:
(1) automatic type inference (2) dealing with missing values, so you don’t have to
What I ended up doing:
Parse lines into RDDs, zipWithIndex, and use a lambda function to swap (val, index) to get (index, val)
Make sure every item has a key (I chose to use dicts). These will become the column names (see more below).
My items now each look like this:
one = lines.take(1) assert (one == (1, {'first_column': 100}))
Fill any missing values with ‘None’ (because
Noneleads to weird behavior with join, I found it was better to use strings) to square everything up, because otherwise it’s impossible to convert to dataframe.
Join RDDs on the index
Drop the index with a lambda function, because we don’t want it in the dataframe, and we won’t use it for ordering or lookups
Flatten everything (with a flatMap lambda function)
Write a helper function to make Row objects
#this method is from StackOverflow, but it really should be built-in (!) from collections import OrderedDict from pyspark.sql import Row def convert_to_row(inputdict): ''' For creating a pyspark DataFrame from Row objects, have to convert to Row objects first Note: python3 sorts the input dict by default :param: inputdict (dict) of {colname : value} :returns: pyspark Row object ''' return Row(**OrderedDict(inputdict)) #Note that only the kwargs version of ** dictionary expansion is supported in python 3.4
Use the helper function to convert big RDD to Row objects, and then to dataframe
df = deindexed.map(ph.convert_to_row).toDF()
Rename any columns that aren’t compatible with the ultimate destination, e.g. in my case I had to convert things like “req.id” and “device-type” to “req_id” and “device_type” because Redshift and Athena will not tolerate period symbols or dashes in column names.
1) create the list of df.columns, just like you would in pandas
2) create a new dataframe with the new columns like this:
renamed = df.toDF(*df_columns) #note that the asterisk splat operator is supported even in python3.4, even though the ** dictionary expansion is not supported until later versions
Write out with coalesce to avoid getting a ton of tiny files
The actual parsing ended up being a series of regular expressions, wrapped in a helper to catch exceptions (which is basically just a try:except that says it’s ok if there’s no match, just fill with ‘None’ instead of freaking out). I also had to write a helper to flatten, because I was doing this on AWS, and the latest version of python they support is 3.4, which does not include the compact double-asterisk syntax for flattening dictionaries).
My next question: How do I deploy this thing to run on AWS?
I had trouble finding step-by-step instructions on this part, so here’s what I ended up doing:
- Write a script to load code to s3 (I used boto3)
- Write a script to copy code from s3 to hadoop home on the EMR cluster (I did this with bash)
- Write a script (and/or in my case, an Airflow plugin) to spin up and configure the EMR cluster
- Write steps to bootstrap pyspark with the code, install dependencies, and run with python3
- Create an EC2 key pair using ssh keygen, if you don’t have one already. You need this to spin up the cluster, but more importantly, to be able to log into it for debugging (you want this)
- setMaster(“yarn-client”)
- addPyFile to SparkContext() so it can find your helper scripts
- Make sure you know if auto-terminate should be on or off, depending on where you are in the development cycle (can’t log into debug on a cluster that auto-terminated already!) and whether your job will be running continuously or not.
I used a YAML file for my configuration, which includes things like the region_name, number of instances, which ec2 key pairs to use, the path to where the logs should go on s3, etc. This is really easy to import in python:
with open("config.yml", 'r') as f: config = yaml.load(f) config_emr = config.get("emr") cluster_name = config_emr.get('cluster_name')
Other things that were non-obvious:
When I went to scale up the job to run on more data, I did run into some problems I hadn’t had before.
I had to do some funky things to get the spark unit tests to work correctly. If you want to have anything that uses the spark context object, e.g. using
sc.textFile to read in a local file, you’ll have to do this first, even if your tests don’t require any other setUp:
from sparktestingbase.testcase import SparkTestingBaseTestCase class TestFileParsing(SparkTestingBaseTestCase): def setUp(self): super().setUp()
At the beginning, it wasn’t obvious to me that zipWithIndex appends the index in the ‘value’ or second position in the (key, value) tuple. So you have to use a lambda function to swap it to the front, because joins only work on the ‘key’. This seems like a strange design choice to me, although I can understand that append is always easier and there are probably (?) some use cases where you want an index but aren’t using it for joins (I just can’t think what those would be?).
After my initial script was working, I ended up refactoring to remove some joins, because they involve shuffle steps, which you want to avoid in spark because they’re slow and memory-intensive. This was actually pretty easy to fix because I had plenty of tests.
I also ended up having to explicitly
repartition and
persist() my original big RDD and then explicitly
unpersist() at the end, because although pyspark is supposed to be smart about handling this kind of stuff for you, it wasn’t quite smart enough to do it when I was running my methods on chunks of files iteratively.
I also ran into some serious irritations with AWS configurations, because we have data stored in different regions, and some regions (like eu-central-1 in Frankfurt) require a little extra information for security reasons. It’s also confusing that
zone can have an extra specification, e.g for zone it has to be “us-east-1a” but
region has to be “us-east-1”, or you’ll get ‘cluster id is None’ errors.
The special trick for Europe is that you have to specify the s3 host yourself and include that in your
s3_additional_kwargs (this took a bit of googling to find out, so I’m putting it here for safekeeping):
if region == 'eu-central-1': host = 's3.eu-central-1.amazonaws.com'
Other irritations include having to set up separate EC2 keys in each region; having to deal with multiple profiles for cross-account access (because the log data are owned by one AWS account and the s3 buckets and spark cluster are owned by another); having to deal with setting s3 bucket policies… So maybe all of that could be its own post, but ugh so boring (!).
Finally, I did end up having to adjust the driver-memory to 10G, executory-memory to 8G, executor-cores to 5, and num-executors to 17. This took some fiddling and it may not be the final configuration, given that we are currently using r3.2xlarge to avoid having to deal with additional configuration requirements for some of the newer instance types, but there are a limited number of instances of this type available in some regions.
I also added a bunch of handling using
except Py4JavaError to deal with things like missing, empty, and corrupt files on s3. | https://szeitlin.github.io/posts/engineering/things-i-learned-about-pyspark-the-hard-way/ | CC-MAIN-2022-27 | refinedweb | 1,616 | 55.07 |
AWS Open Source Blog
Migrating from self-managed Apache Airflow to Amazon Managed Workflows for Apache Airflow (MWAA)
This post was written by Tomas Christ, Solution Architect at eprimo GmbH.
eprimo GmbH is a wholly owned subsidiary of E.ON SE, situated near Frankfurt, Germany. It represents the largest purely green-energy supplier in Germany with some 1.7 million customers. Currently, eprimo has a staff of approximately 160 people. We have been using Amazon Web Services (AWS) since 2016 and run multiple production workloads in more than 40 AWS Control Tower-managed AWS Accounts.
In this blog post, I will describe how we migrated from self-managed Apache Airflow to Amazon Managed Workflows for Apache Airflow (MWAA). Then I will explain how we upgraded to Apache Airflow 2.x. This should provide a guideline with the necessary steps to accomplish the migration.
Overview
With only 2 of 160 employees taking care of the entire DevOps and data engineering environment at eprimo, automation has always been key. This was a strong driver into looking for a powerful workflow management platform, going with Apache Airflow, which we deployed using a self-managed approach back in 2019.
Apache Airflow is an open source workflow management platform that enables us to develop, manage, schedule, and monitor workflows based on directed acyclic graphs (DAGs) that are based on Python source files. An Airflow DAG defines a workflow; at eprimo, this includes mostly data pipelines and can consist of several steps that are called Tasks in Apache Airflow.
Because the availability of workflow orchestration and management platforms is critical, we had to take the necessary steps to ensure the availability of Airflow (for example, by configuring Amazon EC2 Auto Scaling groups). With that in mind, learning that Amazon Managed Workflows for Apache Airflow (MWAA) was announced in late 2020 sounded like great news to us.
The following diagram shows the Apache Airflow environment before migrating to Amazon MWAA. While the classical Apache Airflow on Amazon Elastic Compute Cloud (Amazon EC2) used the Apache Airflow version 1.15, Amazon MWAA uses v1.10.12. Nonetheless, we did not experience any compatibility issues between the different versions.
After we began experimenting with Amazon Managed Workflows for Apache Airflow, the following benefits convinced us to deploy Amazon MWAA:
- Compatibility: Amazon MWAA is the same open source Apache Airflow that one can download. DAGs developed for self-managed Apache Airflow also run on Amazon MWAA.
- Setup, patching, and upgrades: Creating an Apache Airflow environment is simpler. Specify the information that the managed service needs to set up the environment (for example, with an AWS CloudFormation template) and AWS takes care of the rest. With AWS managing the environment, MWAA also significantly simplifies the complexity of patching and upgrading Apache Airflow.
- Availability: Amazon MWAA monitors the workers in its environment, and as demand increases or decreases, Amazon MWAA adds additional worker containers or removes those that are free, respectively.
- Security: With self-managed Apache Airflow, administrators must manage the SSH private keys that allow access to the Amazon EC2 instances where Apache Airflow is installed. Amazon MWAA is integrated with AWS Identity and Access Management (IAM), including role-based authentication and authorization for access to the Airflow user interface. Because our AWS organization is linked to our Azure Active Directory (Azure AD) thanks to AWS Single Sign-On (AWS SSO), we can centrally manage the access to Amazon MWAA and its Amazon CloudWatch dashboards by adding users to Azure AD groups whose structure and policies are actively monitored.
- Monitoring: Before migrating to Amazon MWAA, we monitored our environment using Grafana for the Airflow logs in addition to Amazon CloudWatch for the metrics of the Amazon EC2 instances. With MWAA’s integration with Amazon CloudWatch, we were able to free up resources, unify monitoring, and monitor DAG failure and successes in CloudWatch dashboards.
Migrating to MWAA
eprimos’ approach to create a new MWAA environment
The following deployment guide lists the steps that we at eprimo took to create the new Amazon MWAA environment. The goal was to replace our three different Apache Airflow environments: one for DAG development/testing, one for DAG production, and one optional environment for testing new Apache Airflow features.
At eprimo, whenever infrastructure with more than one environment is supposed to be set up, we have a policy of using infrastructure as code (IaC) methods. Whenever multiple executions of a step cannot be ruled out, we also strive to implement it programmatically. Thus, the resources were created using CloudFormation stacks. The actual migration process, including testing dozens of productive Airflow DAGs, took about a week for two employees.
All steps, including the CloudFormation templates, also can be found on GitHub.
Step 1. Create all necessary resources for Amazon MWAA
First, we needed to create all necessary resources for the MWAA environment. At eprimo, that included the following:
- An Amazon Simple Storage Service (Amazon S3) bucket that contains the Airflow DAGs, hooks, and sensors
- A, AWS CodePipeline that pulls files from an AWS CodeCommit git repository and uploads them to Amazon S3
- An AWS Lambda function that zips the custom hooks and sensors and uploads them to Amazon S3
- IAM roles for MWAA, AWS CodePipeline, and Lambda
- A security group for the MWAA resources
The CloudFormation YAML file for this step is on GitHub.
Step 2. Adjust the KMS key policy
Disks of MWAA resources were supposed to be encrypted at-rest with AWS Key Management Service (AWS KMS). This KMS key had to be identical to the key that is used to encrypt data stored in the Amazon S3 bucket mentioned in step 1 to allow encrypted CloudWatch Logs. To achieve this, the KMS key policy had to be changed accordingly:
AWS_REGION and
AWS_ACCOUNT_ID must be replaced with the concrete values of an environment.
Step 3. Create the actual MWAA environment
Finally, we created the MWAA environment with Apache Airflow version 1.10.12. Resources creation took about 20 minutes.
The CloudFormation YAML file to this step is on GitHub.
Update the MWAA environment
Update DAGs and insert new DAGs
Both updating DAGs and inserting new DAGs is done automatically. After the Python source file that represents an Airflow DAG is pushed to a specific git repository hosted on AWS CodeCommit, the CodePipeline will pull the newly pushed file and store it on a specific path on an Amazon S3 bucket, like s3://mybucketname/dags/dagname.py. Amazon MWAA automatically synchronizes the content of the path to its own directory every 30 seconds.
Update hooks
To update or add custom plugins (for example, hooks, or sensors, or requirements to the MWAA environment), a manual update of the environment is necessary. This can be done by initiating the following steps:
- The new hooks must be pushed to the specific repository. Because changes at hooks can involve several files, we have learned that, when taking new plugins to production, copying the entire plugins folder can make sense if the development git repository differs from the production git repository and a
git mergeis not possible.
- The
git pushstarts the AWS CodePipeline that calls a Lambda function, which generates a ZIP file of the plugins folder and saves it to the Amazon S3 location that contains the DAG plugins. Once this is done successfully, you can begin to update the MWAA environment.
- In the AWS Management Console, select the right MWAA environment and choose Edit.
- The corresponding version can be selected at Plugins file. By default, MWAA always uses the previously deployed version when updating, so the latest version must be selected here manually. Paying attention to the timestamp of the file is recommended. Because it may take a moment for the pushed code to end up in the Amazon S3 bucket, make sure that the latest version possible in MWAA is the latest version that you just pushed. If the timestamp doesn’t match, you must wait a couple of minutes and refresh the Edit page. In Figure 4, the field with the to-be-adjusted timestamp is outlined in blue.
- For updating the requirements version, repeat the preceding steps.
- You can skip the following settings and choose Save to have the MWAA environment updated. This can take up to 15 minutes.
Migrating to Apache Airflow 2.x
Once Amazon Managed Workflows for Apache Airflow supported Apache Airflow 2.0, we were eager to upgrade because it includes new features that both enhance operability, such as task groups and the new UI, and allow high availability of the Apache Airflow Scheduler.
Apart from migrating to an Apache Airflow 2.0 environment, hooks and DAGs also must be changed for a successful migration. Now let’s walk through changes implemented in hooks and DAGs to migrate successfully to Apache Airflow 2.0.
Step 1. Create necessary resources for Amazon MWAA v2
Directly upgrading MWAA from version 1.10.12 to version 2.0 is not possible. Therefore, a new MWAA environment must be created with all the necessary resources. Review the previous steps to achieve that.
Step 2. Adjust the hooks
Adjust folder structure and importing the hooks
Loading hooks as Apache Airflow plugins is deprecated from version 2.0. The hooks can now be imported directly from the corresponding Airflow plugins folder. Furthermore, the distinction between hook and sensor locations is no longer made in Airflow 2.0. Inserting a custom hook into an Airflow plugin also is not necessary. The new, simplified folder structure compared to the old folder structure looks like the following:
- Old folder structure:
plugins,
hooks,
awshooks,
v03,
customhooks.py
- New folder structure:
plugins,
awshooks_v03,
customhooks.py
Hooks can now be imported with the following statement:
Adjust the hook import statements
Importing custom hooks has changed. Instead of
from hooks.awshooks.v02.biccSSM import custom_hook_name at Apache Airflow version 1.10.12, the import statement has changed to
from awshooks_v03.biccSSM import custom_hook_name at Apache Airflow version 2.0.2.
Adjust the DAG import statements
A long list of import statements is available in the Apache Airflow versions on Amazon Managed Workflows for Apache Airflow (MWAA) documentation.
Imports in version 1.10.12:
Imports in version 2.0.2:
Conclusion
Following are highlights from what we learned and recommendations based on our migration to Amazon MWAA in February 2021 and our upgrade to Apache Airflow 2.0.2 on MWAA in June 2021.
- Migrating the DAGs is trivial. The automatic synchronization pushes the DAGs to the MWAA environment and quickly makes the DAGs available in the user interface.
- Migrating custom hooks and sensors was more difficult as the former hooks and sensors could not be loaded simply in the same way from a specific directory to the Amazon MWAA environment. Instead, the files had to be saved as ZIP file, which means an additional step for us run by a Lambda function.
- Debugging the environment, in addition to hooks and sensors, can take time due to the up to 15 minutes that the Amazon MWAA is blocked when updating. Moreover, introducing new hooks and sensors can result in an error in all custom modules failing to load. Thus, testing custom sensors and hooks in a development environment is essential.
- Installing Python modules is intuitive. Store a
requirements.txtfile with the desired modules on Amazon S3 and select this file when updating Amazon MWAA.
- When encrypting Amazon MWAA, if CloudWatch is supposed to be enabled for the Amazon MWAA environment, ensure that the key policy is expanded to include CloudWatch Logs.
- Managing the authentication process has become simpler because once you are logged to the right AWS account, logging into the Airflow user interface does not require additional credentials. If your IT security approves, we recommend deploying the WebserverAccessMode PUBLIC_ONLY, as accessing the UI from outside the network will be easier, especially since port forwarding to the Amazon MWAA UI with SSO is not possible.
In this blog post, I explained why we migrated to Amazon Managed Workflows for Apache Airflow (MWAA), steps we took as part of that migration, and lessons we learned along the way. Resources covered in this article are available in our GitHub repository.
The content and opinions in this post are those of the third-party author and AWS is not responsible for the content or accuracy of this post. | https://aws.amazon.com/blogs/opensource/migrating-from-self-managed-apache-airflow-to-amazon-managed-workflows-for-apache-airflow-mwaa/ | CC-MAIN-2021-49 | refinedweb | 2,048 | 52.6 |
hey guys ! i have been given an assignment . the question is stated below :
1. Create a struct Product with fields id (int), name (char*), price (double), and isAvailable (bool).
2. Write a function which returns a pointer to a dynamically allocated Product filled with the provided data.
Product * getNewProduct(int id, char * name, int nameLength, double price, bool isAvailable);
3. Write a function to read data of products from a file and fill it in a dynamically allocated array of Products and return it. Here is the format of the file.
The first line contains an integer the number of products, on each of the following lines there is data for each product in following format
<id><name><price><isAvailable>
The name will not contain any spaces.
4. Write a function that takes a Product * (which points to the array of products) and an integer id. The function searches the product with that id in the array and returns a pointer to that Product if found. The function returns NULL otherwise.
5. Write a function that takes a Product * and a char * name. The function searches the product with that name in the array and returns a pointer to that Product if found. The function returns NULL otherwise.
so far i have done the first three parts of this question but i have some problem . my code is pasted below :
Code:#include <iostream> #include <string> #include <fstream> using namespace std ; struct Product { int id ; char *name ; double price ; bool isAvailable ; }; Product* getNewProduct(int id, char* name , double price , bool isAvailable ); bool* ReadData (ifstream &inFile, Product P[] ); int main () { system("pause"); return 0 ; } Product* getNewProduct(int id, char* name , double price , bool isAvailable ) { Product *P = new Product ; (*P).id = id ; (*P).isAvailable = isAvailable ; (*P).name = name ; (*P).price = price ; return P ; } bool* ReadData (ifstream &inFile , Product P[] ) { ifstream inFile ; int size ; string line ; bool isAvailable ; inFile.open("file.txt"); if (!inFile.is_open()) { cout << " opening of file failed " << endl; exit(1); } while (!inFile.eof()) { inFile >> size ; Product *arr = new Product [size]; for (int i = 0 ; i<size ; i++ ) { getline (inFile,line,' ' ); P[i].id = atoi(line); // gives error (underlines line stating that no suitable conversion from std::string to const char* exists ) P[i].name = getline(inFile,line,' ' ); // gives error underlining "getline" getline (inFile,line,' ' ); P[i].price = atof(line); // gives error (underlines line stating that no suitable conversion from std::string to const char* exists ) P[i].isAvailable = inFile >> isAvailable ; } } } | http://cboard.cprogramming.com/cplusplus-programming/154786-filing.html | CC-MAIN-2014-15 | refinedweb | 409 | 65.32 |
In the first part we used Maven ‘s org.apache.cxf.archetype to generate an Eclipse project that created a starter application that provides REST based service using JAX-RS. Here is the structure of the application that was generated
How it all works – web.xml has the references for CXF servlet that acts as the dispatcher servlet . This file also points to beans.xml . beans.xml is CXF configuration file and points to HelloWorld class that actually provide/implement the needed services. JsonBean is the helper bean that represents the objects being passed.
One important thing that we haven’t talked about is the dependencies that were automatically taken for us by Maven. If you look under Libraries you would find all the jars that are automatically included
It won’t be much fun if we used the autogenerated code as it is. So let us change it a little bit for fun. First rename the HelloWorld.java to App.java which is shown below. On line 9 the @Path annotation was for /hello we changed it to /services also on line 20 we changed /jsonBean to /json
package sample.restez;.Response; @Path("/services") public class App { @GET @Path("/echo/{input}") @Produces("text/plain") public String ping(@PathParam("input") String input) { return input; } @POST @Produces("application/json") @Consumes("application/json") @Path("/json") public Response modifyJson(JsonBean input) { input.setVal2(input.getVal1()); return Response.ok().entity(input).build(); } }
No changes to JsonBean.java
package sample.restez; public class JsonBean { private String val1; private String val2; public String getVal1() { return val1; } public void setVal1(String val1) { this.val1 = val1; } public String getVal2() { return val2; } public void setVal2(String val2) { this.val2 = val2; } }
beans.xml is the spring like CXF configuration clas. The only change we make is to make sure that it points to App class rather than the original HelloWorld class on line 19th
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="" xmlns: <import resource="classpath:META-INF/cxf/cxf.xml" /> <context:property-placeholder/> <context:annotation-config/> <bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer"/> <bean class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"/> <jaxrs:server <jaxrs:serviceBeans> <bean class="sample.restez.App" /> </jaxrs:serviceBeans> <jaxrs:providers> <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/> </jaxrs:providers> </jaxrs:server> </beans>
Finally web.xml is the typical web.xml that uses the CXF servlet provided by CXF framework. Another point to note is the reference to beans.xml on line 11
<?xml version="1.0" encoding="utf-8"?> <web-app <display-name>JAX-RS Simple Service</display-name> <description>JAX-RS Simple Service</description> >
Now we are ready to deploy this slightly modified app. First deploy it to your local NWCloud instance by doing the “Run as – Run on Server”. On success Eclipse might launch the browser with the URL which will not work. To do the first service test launch the following URL, it is an echo service
you should see RepeatAfterMe in the browser. To test the JSON service we would use the “Advanced REST Client” extension for chrome. We would use the following URL –
As you can see we are using POST method and posting a Content-Type of application/json with the value of {“val1″:”JSON-REPEAT”} and in the result we get two values in the json format.
So there you have it, you have just created a REST based JAX-RS application that has two services – echo a plain text based echo and json a similar service with json format. Now you can further adapt this example code for your business scenario. Once these start working locally you can deploy them on the cloud. | https://blogs.sap.com/2012/08/22/develop-and-deploy-jax-rs-based-rest-application-using-cxf-and-spring-on-sap-netweaver-cloud-2/ | CC-MAIN-2017-34 | refinedweb | 608 | 50.84 |
statvfs(), statvfs64()
Get filesystem information, given a path
Synopsis:
#include <sys/statvfs.h> int statvfs( const char *path, struct statvfs *buf ); int statvfs64( const char *path, struct statvfs64 *buf );
Since:
BlackBerry 10.0.0() and statvfs64() functions return a "generic superblock" describing a filesystem that you can use to acquire information about mounted filesystems. The statvfs64() function is a 64-bit (currently the device ID).
- char f_basetype[16]
- The type of the target filesystem, as a null-terminated string.
- unsigned long f_flag
- A bitmask of flags; the function can set these flags (the _MOUNT_* and ST_* bits are equivalent):
- unsigned long f_namemax
- The maximum filename length.
The values returned for f_files, f_ffree, and f_favail depend on the filesystem:
- fs-qnx6.so
- These filesystems have a fixed inodes table, so they fill in these fields.
- devf-*
- Flash filesystem drivers estimate the values of these fields, based on the amount of free space.
Last modified: 2014-06-24
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/s/statvfs.html | CC-MAIN-2016-50 | refinedweb | 172 | 66.44 |
09 May 2012 11:29 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
Production was disrupted on Wednesday morning by a ‘pipeline accident’, the source said, adding that it is as yet unclear when the plant can resume operations.
JX Nippon is in talks with customers to cancel or delay around 2,000 tonnes of May shipments, the source said.
“Our inventories are very low because of the earlier shutdown,’’ the source said who added that the producer may have to reduce export quantities in June as it has to build its inventories ahead of a 50-day turnaround in early August.
The first unplanned outage at the plant took place on 21 April and the plant was restarted on 29 April.
It is unclear if the two shutdowns are | http://www.icis.com/Articles/2012/05/09/9557590/japans-jx-nippon-shuts-ipa-plant-in-kawasaki-unexpectedly.html | CC-MAIN-2014-41 | refinedweb | 129 | 67.38 |
Python has become the number one and most widely used language in the programming world. The current machine learning boom has raised the number of Developers learning Python. Its high versatility nature made it widely acceptable in web, desktop apps, and in many other areas.
The popularity of Python is rising day by day: This is the reason why Python Certification is becoming a highly sought-after skill in the IT Sector. If you are aspiring to start your career in the Python programming language, then you must know the Frequently Asked Python Interview Questions to help you out, we have gathered a list of Python interview questions. Mastering these questions would help you in cracking the Python Interview on the very first attempt. Let's jump into the question and answer part.
Below mentioned are the Top Frequently asked Python Interview Questions and Answers that will help you to prepare for the Python interview. Let's have a look at them.
We have categorized Python Interview Questions - 2022 (Updated) into 7 levels they are:
What are the key features of Python?
What are the applications of Python?
What are the global and local variables in Python?
What are the two major loop statements?
What are the built-in types available in Python?
What is the difference between .py and .pyc files?
What do you understand by the term namespace in Python?
What is a boolean in Python?
What are the functions in Python?
What are Python Decorators?
If You Need A Video Explanation You Can Check Out:
Following are the Basic Python Interview Questions For Freshers:
Python is a high-level and object-oriented programming language with unified semantics designed primarily for developing apps and the web. It is the core language in the field of Rapid Application Development (RAD) as it offers options such as dynamic binding and dynamic typing.
The benefits of Python are as follows:
The following are the significant features of Python, and they are:
Python is suitable for scripting, but in general, it is considered a general-purpose programming language.
Top 10 Programming Languages that you need to watch out to boost your career in 2022
The applications of Python are as follows:
The difference between tuple and list is as follows:
Global Variables in Python: The variables that are declared outside the function are called global variables. These variables can be accessed or invoked by any function in the program.
Example:
def v() : print g g = "welcome to mindmajix" v()
Output:
Welcome to mindmajix
Local Variables in Python: The variables that are declared inside a function are called local variables. These types of variables can be accessed only inside the function.
PYTHONPATH is an environmental variable that is used when we import a module. Suppose at any time we import a module, PYTHONPATH is used to check the presence of the modules that are imported in different directories. Loading of the module will be determined by interpreters.
for and while
PEP 8 is the Python latest coding convention and it is abbreviated as Python Enhancement Proposal. It is all about how to format your Python code for maximum readability.
The major difference between Java and Python are as follows:
The module is defined as a file that includes a set of various functions and Python statements that we want to add to our application.
Example of creating a module:
In order to create a module first, we need to save the code that we want in a file with .py extension.
Save the module with module.py
def wishes(name): Print("Hi, " + name)
The built-in types in Python are as follows:
Decorator is the most useful tool in Python as it allows programmers to alter the changes in the behavior of class or function.
An example for Python Decorator is:
@gfg_decorator def hi_decorator(): print("Gfg")
We can detect bugs in python source code using a static analysis tool named PyChecker. Moreover, there is another tool called PyLint that checks whether the Python modules meet their coding standards or not.
py files are Python source files. .pyc files are the compiled bytecode files that are generated by the Python compiler
By using python or pythonx. y we can invoke a Python interpreter. where x.y is the version of the Python interpreter.
String in Python is formed using a sequence of characters. Value once assigned to a string cannot be modified because they are immutable objects. String literals in Python can be declared using double quotes or single quotes.
Example:
print("Hi") print('Hi')
A namespace in Python can be defined as a system that is designed to provide a unique name for every object in python. Types of namespaces that are present in Python are:
Scope of an object in Python:
Scope refers to the availability and accessibility of an object in the coding region.
Functions are defined using the def statement.
An example might be def foo(bar):
In Python, an iterator can be defined as an object that can be iterated or traversed upon. In another way, it is mainly used to iterate a group of containers, elements, the same as a list.
Functions return values using the return statement.
Slicing is a procedure used to select a particular range of items from sequence types such as Strings, lists, and so on.
As in Python the code which we write is not machine-level code before runtime so, this is the reason why Python is called an interpreted language.
Yes, this is valid. The function will then return a None object. The end of a function is defined by the block of code that is executed (i.e., the indenting) not by any explicit keyword.
In Python packages are defined as the collection of different modules.
In order to make a Python script executable on Unix, we need to perform two things. They are:
Script file mode must be executable and
The first line should always begin with #.
OS.unlink(filename) or OS.remove(filename) are the commands used to delete files in Python Programming.
Example:
import OS OS.remove("abc.txt")
Pickling in Python: The process in which the pickle module accepts various Python objects and converts them into a string representation and dumps the file accordingly using the dump function is called pickling.
Unpickling in Python: The process of retrieving actual Python objects from the stored string representation is called unpickling.
Local namespaces are created within a function when that function is called. Global namespaces are created when the program starts.
Boolean is one of the built-in data types in Python, it mainly contains two values, and they are true and false.
Python bool() is the method used to convert a value to a boolean value.
Syntax for bool() method: bool([a]).
Syntax for String replace() method:
str.replace(old, new [, count])
The built-in modules in Python are:
In Python, functions are defined as a block of code that is executable only when it is called. The def keyword is used to define a function in Python.
Example:
def Func(): print("Hello, Welcome toMindmajix") Func(); #calling the function
Output: Hello, Welcome to Mindmajix
These are mostly used as syntax constructions to ease the creation of lists and dictionaries based on existing iterable.
Lambda is the small anonymous function in Python that is often used as an inline function.
Triple quotes ‘’” or ‘“ are string delimiters that can span multiple lines in Python. Triple quotes are usually used when spanning multiple lines, or enclosing a string that has a mix of single and double quotes contained therein.
In Python self is defined as an object or an instance of a class. This self is explicitly considered as the first parameter in Python. Moreover, we can also access all the methods and attributes of the classes in Python programming using self keyword.
In the case of the init method, self refers to the newer creation of the object. Whereas in the case of other methods self refers to the object whose method was called.
The _init_ is a special type of method in Python that is called automatically when the memory is allocated for a new object. The main role of _init_ is to initialize the values of instance members for objects.
Example:
class Student: def _init_ (self, name, age, marks): self.name = name self.age = age self.marks = 950 S1 = Student("ABC", 22, 950) # S1 is the instance of class Student. # _init allocates memory for S1. print(S1.name) print(S1.age) print(S1.marks)
Output:
ABC 22 950
The way of implementing an effective representation of iterators is known as generators. It is only the normal function that yields expression in the function.
The docstring in Python is also called a documentation string, it provides a way to document the Python classes, functions, and modules.
the lower() function is used to convert string to lowercase.
Example:
str = 'XYZ' print(str.lower())
xyz
Ans: The elements can be removed from a Python array using the remove() or pop() function. The difference between pop() and remove() will be explained in the below example.
Example:
x = arr.array('d', [ 1.0, 2.2, 3.4, 4.8, 5.2, 6.6, 7.3]) print(x.pop()) print(x.pop(3)) x.remove(1.0) print(a)
Output:
7.3 4.8 array(‘d’, [2.2, 3.4, 5.2, 6.6])
A block that is preceded by the try keyword is known as a try block
Syntax:
try{ //statements that may cause an exception }
split() method in Python is mainly used to separate a given string.
Example:
x = "Mindmajix Online Training" print(a.split())
[‘Mindmajix’, ‘Online’, ‘Training’]
We can access the module written in Python from C by using the following method.
Module == PyImport_ImportModule("<modulename>");
To copy objects in Python we can use methods called copy.copy() or copy.deepcopy().
By using the list.reverse(): we can reverse the objects of the list in Python.
Following are the Python Programming Interview Questions with Answers
By using the following command we can debug the Python program
$ python -m pdb python-script.py
with open(SOME_LARGE_FILE) as countletter: count = 0 text = countletter.read() for character in text: if character.isupper(): count += 1
#,
The code to produce a star triangle is as follows:
def pyfun(r): for a in range(r): print(' '*(r-x-1)+'*'*(2*x+1)) pyfun(9)
Output:
* *** ***** ******* ********* *********** ************* *************** *****************
The code to sort a numerical dataset is as follows:
list = [ "13", "16", "1", "5" , "8"] list = [int(x) for x in the list] list.sort() print(list)
Output:
1, 5, 8, 13, 16
x = ['ab','cd'] print(list(map(list, x)))
The output of the following code is
[ [‘a’, ‘b’], [‘c’, ‘d’]
Following are Python Developer Interview Questions with Answers
We need to implement the following steps to install Python on Windows, and they are:
The difference between SciPy and NumPy is as follows:
The difference between Python array and Python list is as follows:
In python, there is no specific syntax to display multi-line comments like other languages. In order to display multi-line comments in Python, programmers use triple-quoted (docstrings) strings. If the docstring is not used as the first statement in the present method, it will not be considered by the Python parser.
Both the methods are mainly used in Python to iterate the for loop for a fixed number of times. They differ only when we talk regarding Python versions.
The difference between range and xrange is as follows:
Following are the Python Advanced Interview Questions with Answers
Django is an advanced python web framework that supports agile growth and clean pragmatic design, built through experienced developers, this cares much about the trouble of web development, so you can concentrate on writing your app without wanting to reinvent that wheel.
Django is a high-level Python web framework that was developed for realistic design, clean, rapid development.
The main goal to designing Django is to make it simple to its users, to do this Django uses:
Visit here to learn Python Training in Bangalore
A few common security issues that can be avoided by using Django are:
Few well-known companies that are using the Django framework are.
Ans: There are only three main steps for setting up Django static files
Yes, Django is used by many famous companies because it is quite stable.
Django web framework is operated and also maintained by an autonomous and non-profit organization designated as Django Software Foundation (DSF). The initial foundation goal is to promote, support, and advance this Django Web framework.
from django.contrib import admin from django.urls import path urlpatterns = [ path('appmajix/', appmajix.site.urls), ]
A session comprises a mechanism to store information on a specific server-side at the interaction by the web application. By default, session reserves in the database and allows file-based and cache-based sessions.
A cookie is a piece of information that is stored in a client's browser for a specific time. When the specific time is completed cookie gets automatically removed from the client browser.
The two methods to set and get cookie values are
Django-admin.py is a command-line argument that is utilized for administrative tasks
It is an automatically built file inside each Django project. It is a flat wrapper encompassing the Django-admin.py. It possesses the following usage:
Django has described as a loosely coupled framework because of the MTV architecture it’s based upon. Django’s architecture means a variant of MVC architecture and also MTV is helpful because this completely separates the server code of the client’s machine.
we can make use of the edit mysite/setting.py command, which is a simple Python module that consists of levels for presenting or displaying Django settings.
By default Django uses SQLite; this also makes it easy for Django users in case of any other type of installations. For example, if your database choice is different then you need to follow certain keys in the DATABASE like default items to match database connection settings.
Django mainly uses SQLite as its default database to store entire information in a single file of the filesystem. If you want to use different database servers rather than SQLite, then make use of database administration tools to create a new database for the Django project. Another way is by using your own database in that place, and the remaining is to explain Django about how to use it. This is the place in which Python’s project settings.py file comes into the picture.
We need to add the below code to the setting.py file:
DATABASE = { ‘Default’ : { ‘ENGINE’ : ‘django.db.backends.sqlite3’, ‘NAME’ : os.path.join(BASE_DIR, ‘db.sqlite3’), } }
There are three possible inheritance styles in Django, and they are:
The following code is used to save the image locally from the URL address which we know.
import urllib.request urllib.request.urlretrieve("URL", "local-filename.jpg").
Basically, a flask is a minimalistic framework that behaves the same as the MVC framework. So MVC will be perfectly suitable for the flask and we will consider the MVC pattern in the below example.
from flask import Flask In this code your, app = Flask(_name_) @app.route(“/”) Def hey(): return “Welcome to Appmajix” app.run(debug = True)
The following code can be fragmented into
Configuration part will be,
In this code your, app = Flask(_name_)
View part will be,
@app.route(“/”) Def hey(): return “Welcome to Appmajix”
While your main part will be,
app.run(debug = True)
Database-powered applications are supported by the flask. The relational database systems need to create a schema that requires piping the schema.sql file into an SQLite3 command. So, in this case, you need to install the SQLite3 command on your system to initiate and create the database in the flask.
We can request a database using flask in three ways, and they are:
The following are the steps used to minimize the outages of the Memcached server in your Python development, and they are.
Class Student: def __init__(self, name): self.name = name S1=Student("XYZ") print(S1.name)
This is defined as an occurrence of an event when the cache expires and also when the websites are hit with more requests by the client at a time. This dogpile effect can be averted by the use of a semaphore lock. If in the particular system the value expires then, first of all, the particular process receives the lock and begins generating new value.
Ans: Python is also an object-oriented programming language like other programming languages. It also contains different OOP's concepts, and they are
An object in Python is defined as an instance that has both state and behavior. Everything in Python is made of objects.
Class is defined as a logical entity that is a huge collection of objects and it also contains both methods and attributes.
In Python programming, the class is created using a class keyword. The syntax for creating a class is as follows:
class ClassName: #code (statement-suite)
Example of creating a class in Python.
Output:
XYZ
Ans: The syntax for creating an instance of a class is as follows:
<object-name> = <class-name>(<arguments>)
The Method is defined as the function associated with a particular object. The method which we define should not be unique as a class instance. Any type of object can have methods.
Multiple inheritances are supported in python. It is a process that provides flexibility to inherit multiple base classes in a child class.
An example of multiple inheritances
In simple words, abstraction can be defined as hiding unnecessary data and showing or executing necessary data. In technical terms, abstraction can be defined as hiding internal processes and showing only the functionality. In Python abstraction can be achieved using encapsulation.
Encapsulation is one of the most important aspects of object-oriented programming. The binding or wrapping of code and data together into a single cell is called encapsulation. Encapsulation in Python is mainly used to restrict access to methods and variables.
By using polymorphism in Python we will understand how to perform a single task in different ways. For example, designing a shape is the task and various possible ways in shapes are a triangle, rectangle, circle, and so on.
Python does not make use of access specifiers and also it does not provide a way to access an instance variable. Python introduced a concept of prefixing the name of the method, function, or variable by using a double or single underscore to act like the behavior of private and protected access specifiers.
Empty class in Python is defined as a class that does not contain any code defined within the block. It can be created using pass keywords and object to this class can be created outside the class itself.
Example:
class x: pass obj=x() obj.id="123" print("Id = ",obj.id)
Output:
123:
The _init_ method in Python stimulates the constructor of the class. Creating a constructor in Python can be explained clearly in the below example.
class Student: def __init__(self,name,id): self.id = id; self.name = name; def display (self): print("ID: %d nName: %s"%(self.id,self.name)) stu1 =Student("nirvi",105) stu2 = Student("tanvi",106) #accessing display() method to print employee 1 information stu1.display(); #accessing display() method to print employee 2 information stu2.display();
Output:
ID: 1 Name: nirvi ID: 106 Name: Tanvi
When an object of child class has the ability to acquire the properties of a parent class then it is called inheritance. It is mainly used to acquire runtime polymorphism and also it provides code reusability.
Following are the Frequently asked Python Interview Questions with Answers
There are many IDE’s to execute Python code. But, as a beginner, the following two IDE’s will be helpful
The following are some of the things that you can perform using Python:
Python alone can't replace Java, whereas a group of programming languages can replace Java but JVM can't be replaced.
There is no doubt, Python is the best choice for coding in the interview. Other than Python, if you prefer to choose C++ or java you need to worry about structure and syntax.
Choosing an appropriate language to code also matters at the time of the interview. Any language can be used for coding but coding in Python is seeming less and easy.
It is not that easy as we usually think. Mugging up some programs and executing the same will not work. The ideal way to crack the coding interview, you should be proficient in writing code without the support of any IDE. Don't panic or argue, test your code before you submit, wait for their feedback. Practicing mock interviews will help. Coderbyte platform will help you in enhancing your skills.
The following are the top 5 tips to crack Python interview:
There are many online coding sites and platforms exclusively for practice purposes. According to my the Ideal way of learning is by picking up a problem statement and working on it to build your confidence levels. On the StackOverflow website, we can see 100 software developers posting their problems.
Attending an interview as a fresher or first time is very challenging, but we are here to support you. Learn the fundamentals of programming, practice some available coding samples.
1. In-place swapping of two numbers
p, q = 20, 40 print(p, q) p, q = q, p print(p, q)
Output:
20 40 40 20
2. Reversing a String in Python
x = "MindmajixTraining" print( "Reverse is" , x[: : -1]
Output:
Reverse is gniniarTxijamdniM
3. Create a single string from all the elements in the list
x = ["Mindmajix", "Online", "Training"] print(" ".join(x))
Output:
Mindmajix Online Training
4. Use of Enums in Python
class Training: Mindmajix, Online, Mindmajix = range(3) print(MyName.Mindmajix) print(MyName.Online) print(MyName.Mindmajix)
Output:
2 1 2
5. Return multiple values from functions
def a(): return 4, 5, 6, 7 p, q, r, s = a() print(p, q, r, s)
Output:
4, 5, 6, 7
6. Print String N times
n = 3 x = "Mindmajix"; print(a * n)
Output:
MindmajixMindmajixMindmajix
7. Check the memory usage of an object
import sys x = 10 print(sys.getsizeof(x))
Output:
28
8. Find the most frequent value in a list
test = [1, 2, 3, 9, 2, 7, 3, 5, 9, 9, 9] print(max(set(test), key = test.count))
Output:
9
9. Checking whether the two words are anagrams or not
from collections import Counter def is_anagram(str1, str2): return Counter(str1) == Counter(str2) print(is_anagram('majix', 'magic')) print(is_anagram('majix', 'xijam'))
Output:
False True
10. Print the file path of imported modules
import os; import socket; print(os) print(socket)
Output:
<module 'os' from '/usr/lib/python3.5/os.py'> <module 'socket' from '/usr/lib/python3.5/socket.py'> | https://mindmajix.com/python-interview-questions | CC-MAIN-2022-40 | refinedweb | 3,831 | 63.7 |
Updated on Kisan Patel
Anonymous types defined with var keyword. So A simple anonymous type variable begins with the
var keyword, the assignment operator (=), and a non null initial value.
For Example,
var name = "Kisan";
Here, we have assign name anonymous variable with string value “Kisan” and this is identical to the following.
string name = "Kisan";
Note : Anonymous types must always have an initial assignment and it can’t be null.
Anonymous types mean you don’t specify the data type. You write
var and C# find what data type is defined in right side.
You can also use anonymous type syntax for initializing arrays. You can initialize anonymous type using
new keyword.
For Example,
var names = new string[]{ "Kisan", "Ketul", "Ravi", "Ujas" }; Console.WriteLine(names[1]);
You Can be used anonymous type with Simple or complex types, but composite anonymous types require member declaration. So Anonymous types that define composite types is just class without the “typed” class definition.
For Example,
var name = new {First=”Kisan”, Last=”Patel”}; Console.WriteLine(name.First); //Print the Kisan Console.WriteLine(name.Patel); //Print the Patel
Here, the member elements, defined by the member declarators are First and Last.
using System; namespace ConsoleApp { class Program { static void Main(string[] args) { var names = new { First = "Kisan" , Last = "Patel" }; Console.WriteLine(names.First); Console.WriteLine(names.Last); Console.WriteLine(names); } } }
The output of the above C# program… | http://csharpcode.org/blog/anonymous-types/ | CC-MAIN-2019-18 | refinedweb | 232 | 58.18 |
Introduction: Wallbots: Autonomous Magnetic Robots That Traverse Vertical Surfaces
The:
Step 1: Gather Materials
To make one robot, you will need:
Step 2: Hack the Servo Motors to Allow for Continuous Rotation (Part 1)
Off-the shelf servos allow for fixed motion. We want continuous rotation in order to control robot movement. You will need to make 2 simple modifications to each servo: remove the physical rotation barriers, and hack the potentiometer into always receiving a constant signal.
The black part of the motor is designed to stop movement after 180 degrees. This is done physically- there are two plastic knobs that prevent continuous movement.
1. Pry open the servo case
2. Take apart the gears
3. Cut the wires off from the black casing (the next step explains what to do with them)
4. Clip off the small plastic bearings that hinder continuos rotation
Step 3: Hack the Servo Motors to Allow for Continuous Rotation (Part 2)
Now 'trick' the potentiometer into always getting continuous signal
1. Cut the red, green and yellow wires from the black casing (you should have done this in the previous step)
2. Solder a 2.2K resistor between the green wire and yellow wire.
3. Solder a 2.2K resistor between the red wire and the yellow wire.
Step 4: Flip the Rotation of One of the Motors
Servos usually rotate in the same direction given the same analog signal. We'll need to arrange them symmetrically on the robot, so we'll have to reverse one of them. This can be done in code or hardware (I did hardware b/c I'm lazy with code).
To do a hardware direction reverse:
1. cut the red and blue wires that go from the motor to the motor's board
2. solder the red to the blue, and the blue to the red (criss-cross the wires)
Step 5: Re-assemble the Motors Back Together
This step is easy! Gently tuck the wires back into the case of the servos as much as you can and re-assemble the gears. I couldn't get the casing to fit after I added the resistors, so I taped everything back with electric tape.
Step 6: Attach the Magnetic Wheels to Each Motor
I used hot glue to do the 'attaching'- but any type of strong adhesive should work.
1. Cut 2 equal pieces of the hard wire. It should be about 1 inch long for each wheel.
2. Hot glue each wire into the top gear of each servo. Make sure the wire is centered.
3. Hot glue 3 magnetic disks onto the end of each wire*. Make sure the disks are centered.
*actually, I've found that once the magnets are glued on, working with the servos becomes really annoying- the stick to everything. You may want to hold off and do this at the very end.
Step 7: Connect the Servos to the Arduino Board
I'm using the Arduino Servo library, so I use pins 9 and 10 to drive the motors. So my setup looks like this:
Pin 9 -> Orange wire of Servo 1
Pin 10 -> Orange wire of Servo 2
Ground -> Black wires of Servos 1 and 2
VCC -> Red wires of Servos 1 and 2
Step 8: Attach the Photoresistors to the Arduino
Attach each photoresistor (light sensor) to the Arduino. There are 4 sensors, for the left, right, front and top of the robot.
The circuit diagram for each light sensor is shown below. One wire of the sensor goes to VCC (power). The other wire connects to the 10K and 100 ohm Resistors. The 10K resistor connects to ground. the 100ohm resistor connects to the input pin. The input (green wire) of each sensor goes to Analog Pins on the mini (A0, A1, A2, A3).
In my code, I have set it up like this:
Analog 0 -> Top Sensor
Analog 1 -> Left Sensor
Analog 2 -> Front Sensor
Analog 3 -> Right Sensor
Step 9: Connect the RGB LED to the Arduino
You can use any RGB LED, and connect it to any of the PWM pins on the Arduino. I'm only using Green and Red Colors, so my setup is:
Red-> Pin 5
Green -> Pin 6
Ground -> Ground
You may want to put a resistor between each pin and the LED (on the order of 200 ohms). I didn't do this bc my LED can take much higher current than the arduino can supply, so it will not burn out.
Step 10: Connect the Battery
Basically, any battery that supplies around 3-4volts will work, the lighter the better. I used the sparkfun Lithium battery. Attaching it is easy. Ground goes to ground, power goes to raw VCC on the arduino.
Step 11: Upload the Code Onto the Arduino
I'm pasting my code below. Each sensor is sampled, and the robot moves depending on which sensor detects a human hand, and whether or not it's red, green, or yellow (if it should move away or towards objects).
/*
Wallbots Code
Stacey Kuznetsov
May 6, 2009
for Making Things Interactive, Spring '09
This is the basic code to drive robotic movement of 2 sevo motors based on input
from 4 light sensors. Motion supports several settings, based on the robot mode.
Red robots move fast, towards objects (when light sensors detect darkness)
Green robots move at medium speed, away from objects (away from darker areas)
Yellow robots move slowerly, and stop to blink when objects are detected
The purpose of these robots is to move on walls using magnetic wheels.
Supported movement includes right, left and forward directions. Several
speeds are implemented based on the robot mode.
The light sensors auto-calibrate on reboot or when the top sensor is covered
for more than 3 seconds.
*/
#include <Servo.h>
// Right and left servos
Servo servo1;
Servo servo2;
// Light Sensors
int topSensor = 0; //700
int leftSensor = 1; /// Threshhold is 400
int frontSensor = 2; //400
int rightSensor = 3; //300
// Hardcoded thresholds (not used because we auto-calibrate)
int topThreshhold = 400;
int leftThreshhold = 550;
int frontThreshhold = 200;
int rightThreshhold = 650;
// Current robot type (red gree or yellow)
int STATE = 0;
// State values
int RED = 0;
int GREEN = 1;
int ORANGE = 2;
// Pins to drive the top tri-color LED
int redPin = 5;
int greenPin = 6;
// Values to hold sensor readings
int front;
int right;
int left;
int top;
// Auto-calibrate light sensor thresholds
void calibrate() {
Serial.println("CALIBRATING");
long int val = 0;
for (int i = 0; i<5; i++) {
val += analogRead(frontSensor);
delay(10);
}
frontThreshhold = (val /5) - 80;
val = 0;
for (int i = 0; i<5; i++) {
val = val + analogRead(topSensor);
Serial.println(analogRead(topSensor));
Serial.println(val);
delay(10);
}
topThreshhold = (val /5) -200;
val = 0;
for (int i = 0; i<5; i++) {
val += analogRead(rightSensor);
}
rightThreshhold = (val /5) - 100;
val = 0;
for (int i = 0; i<5; i++) {
val += analogRead(leftSensor);
}
leftThreshhold = (val /5) - 100;
// Print threshold values for debug
Serial.print("top: ");
Serial.println(topThreshhold);
Serial.print("right: ");
Serial.println(rightThreshhold);
Serial.print("left: ");
Serial.println(leftThreshhold);
Serial.print("front: ");
Serial.println(frontThreshhold);
}
void setup()
{
// turn on pin 13 for debug
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
// setup sensor pins
for (int i = 0; i<4; i++) {
pinMode(i, INPUT);
}
Serial.begin(9600);
calibrate();
// generate a random state
STATE = random(0, 3);
setColor(STATE);
}
// MOTOR FUNCTIONS
void turnLeft()
{
Serial.println("LEFT");
start();
delay(20);
for (int i = 0; i<20; i++) {
servo2.write(179);
servo1.write(1);
delay(20);
}
stop();
delay(20);
}
void turnRight() {
Serial.println("RIGHT");
start();
delay(20);
for (int i = 0; i<20; i++) {
servo2.write(1);
servo1.write(179);
delay(20);
}
stop();
delay(20);
}
void goForward(int del = 20) {
Serial.println("FORWARD");
start();
delay(20);
for (int i = 0; i<20; i++) {
servo1.write(179);
servo2.write(179);
delay(del);
}
stop();
delay(20);
}
void stop() {
servo1.detach();
servo2.detach();
delay(10);
}
void start() {
servo1.attach(10);
servo2.attach(9);
}
// Set the color of the top tri-color LED based on the current state
void setColor(int color) {
if (color == RED) {
digitalWrite(greenPin, 0);
analogWrite(redPin, 180);
}
else if (color == GREEN) {
digitalWrite(redPin, 0);
analogWrite(greenPin, 180);
}
else if (color == ORANGE) {
analogWrite(redPin, 100);
analogWrite(greenPin, 100);
}
}
// Blink the yellow color (when robot is confused)
void blinkOrange() {
for (int i = 0; i<5; i++) {
analogWrite(redPin, 100);
analogWrite(greenPin, 100);
delay(300);
digitalWrite(redPin, 0);
digitalWrite(greenPin, 0);
delay(300);
}
analogWrite(redPin, 100);
analogWrite(greenPin, 100);
}
void loop()
{
top = analogRead(topSensor);
long int time = millis();
while (analogRead(topSensor) < topThreshhold) {
delay(10); // while there is an arm wave from the user don't do anything
}
if ((millis() - time) > 3000) {
// if the sensor was covered for more than 3 seconds, re-calibrate
calibrate();
}
// if the top sensor was covered, we change state
if (top < topThreshhold) {
STATE = (STATE+1) %3;
setColor(STATE);
Serial.print("CHANGED STATE: ");
Serial.println(STATE);
}
// Read the other sensors
right = analogRead(rightSensor);
left = analogRead(leftSensor);
front = analogRead(frontSensor);
if (STATE == RED) {
// go towards objects
if (front < frontThreshhold) {
goForward();
} else if (right < rightThreshhold) {
turnRight();
} else if (left<leftThreshhold) {
turnLeft();
} else {
goForward();
}
}
if (STATE == GREEN) {
// go away from objects
if (front < frontThreshhold) {
int dir = random(0,2);
if (dir == 0 && right > rightThreshhold) {
turnRight();
} else if (dir == 1 && left > leftThreshhold) {
turnLeft();
}
} else if (right < rightThreshhold) {
if (left > leftThreshhold) {
turnLeft();
} else {
goForward();
}
} else if (left<leftThreshhold) {
if (right > rightThreshhold) {
turnRight();
} else {
goForward();
}
} else {
goForward();
}
delay(200);
}
if (STATE == ORANGE) {
// only move if there are no hand motions- otherwise blink
int dir = random(0, 3);
if (left<leftThreshhold || right<rightThreshhold ||
front<leftThreshhold) {
blinkOrange();
} else {
if (dir == 0) {
goForward();
} else if (dir == 1) {
turnRight();
} else if (dir == 2) {
turnLeft();
}
delay(1000);
}
delay(10);
}
}
Step 12: Create the Robot Casing
Since this robot will move vertically, it is important to make the casing as light as possible. I used cardboard, but paper or lightweight plastic will work too.
Before doing this step, make sure the code works and you can tell which servo is right and which is left.
I hot-glued the servos onto the cardboard base, and arranged the sensors to be on top, right, left, or front of the robot. I then created 'walls' of the case with more cardboard. I cut out the holes to fit light sensors and motor gears. The top of my robot is just a piece of paper!
... and you're done!
Recommendations
We have a be nice policy.
Please be positive and constructive.
50 Comments
Hi staceyk. Its a kool project. am trying to replicate but am facing following issues.
1. Single battery even a 9v is not able to power 2 servo and arduino uno. if i use single battery the servos move at very slow pace and that too out of sync. Adding individual batteries makes my car too heavy.
2. Placing just 2 tyres keeps my car off balance. i have to add one universal tyre in front to balance it.
Any suggestions
My assembly items
1. Arduino uno board
2 Two SG 90 continuous rotation servo motors
3 HS 05 BT
4 US distance sensor
5. Plastic bottle caps acting as tyres
6 Breadboard small
7 9v HW batteries - 3 nos
Super cool! You could also have add-ons for the white board like markers and erasers!;)
Neat gizmo! Did you consider, rather than using magnets as wheels, using rubber wheels for traction and mounting neodymium magnets on the bottom of the robot - so close to the level of the surface that the magnetic force would be strong enough to hold the robot to a vertical surface? That seems to me a better solution. I would think that having the magnets make direct contact with the surface, would make them difficult to turn, slow, and not provide enough traction. Just a thought.
Also, the circuit is a rat's nest of wires. Why not make a small PCB?
Overall, nice project! :)
brilliant
Amazing I am going to build this soon
just wanna ask if you have any programs on the part of arduino...
Very nice and good instructables for how to hack mini servo to
Thacks :)
I'm not great at electronics, but most of this makes sense and it looks awesome :)
BUT anyone know how I'd go about using a picaxe instead of arduino? Thanks muchly :)
It'd be nifty to have them clean yer windows; one on each side, like them aquarium magnets. Switch out the marker tail for a squeegie and Windex.
COOL!!! | http://www.instructables.com/id/Wallbots-Autonomous-Magnetic-Robots-that-Traverse/?comments=all | CC-MAIN-2018-09 | refinedweb | 2,080 | 60.75 |
The Fl_Repeat_Button is a subclass of Fl_Button that generates a callback when it is pressed and then repeatedly generates callbacks as long as it is held down. More...
#include <Fl_Repeat_Button.H>
The Fl_Repeat_Button is a subclass of Fl_Button that generates a callback when it is pressed and then repeatedly generates callbacks as long as it is held down.
The speed of the repeat is fixed and depends on the implementation.
Creates a new Fl_Repeat_Button widget using the given position, size, and label string.
The default boxtype is FL_UP_BOX. Deletes the button.
Deactivates the widget._DEACTIVATE to the widget if active_r() is true.
Currently you cannot deactivate Fl_Window widgets.
Reimplemented from Fl_Widget._Button. | http://www.fltk.org/doc-1.3/classFl__Repeat__Button.html | CC-MAIN-2013-20 | refinedweb | 112 | 60.41 |
Hi, I was wondering if you can help me figure how to go about this problem.
This is what I have to do:
Write a programme to generate an array of 100 random integers.
While the array is being filled incrementally, produce a sorted array by comparing the new element n+1 to a sorted array of n elements and inserting the new element into the appropriate position (this mean shifting all larger elements into one position up in the array).
This process will ultimately produce a sorted list of the 100 random numbers.
This is what I have so far.. I understood that there needs to be a function, that sorts out the array, while its being filled and produces new array.
I tried to use bubble sort in the function, but it doesnt appear to sort the array.
Can somebody please advice how can I fix this or is there a better way to go at it?
#include <iostream> #include <cstdlib> #include <time.h> using namespace std; int arraysort(int array[], int num, int size); int main() { int array[100], i, size = 0; srand(time(NULL)); for(i=0; i<100; i++){ array[i] = rand(); size++; array[i] = arraysort(array, array[i], size); } for (int i=0; i<100; i++) cout << array[i] << " "; return 0; } int arraysort(int array[], int num, int size){ int a, b, t; if (a == 0) return num; for (a=1; a<size; a++) for (b=size-1; b>=a; b--) { if(array[b-1] > array[b]) { t=array[b-1]; array[b-1] = array[b]; array[b] = t; } } for (t=0; t<size; t++) return array[t]; } | https://www.daniweb.com/programming/software-development/threads/353517/another-sorting-array-issue | CC-MAIN-2018-34 | refinedweb | 274 | 64.24 |
In the first part of this series, we looked at the theory and implementation of Fourier transforms, short-time Fourier transforms, mel scale, filter banks, mel frequency cepstral coefficients, and spectral features like spectral centroid, spectral bandwidth, and spectral contrast.
Up until now, we haven't tried to understand any specific kind of sound. We took a general approach to sound analysis and how any sound looks in the frequency domain. In this article, we'll look into music in particular.
Bring this project to life
Introduction
We saw how sound travels through space in the last article. We called those waves longitudinal waves and called their fluctuations compressions and rarefactions.
Take the case of a guitar. In a guitar these final sound waves are a result of the vibrations of different guitar strings. All objects have a natural frequency with which they vibrate when struck, strummed, or are otherwise perturbed.
When an object is forced to vibrate in a fashion that resonates with the natural frequency, the medium tends to create what we call standing waves. Standing waves are waves that have constant amplitude profiles.
The peaks are always the same on the X-axis. So are the zero amplitude points. The points with zero amplitude show no movement at all and are called nodes.
Fundamental Frequency and Harmonics
Frequencies at which standing waves are created in a medium are referred to as harmonics. At frequencies other than harmonic frequencies, vibrations are irregular and non-repeating.
The lowest frequency produced by any particular instrument is known as the fundamental frequency or the first harmonic of the instrument. Vibrations at the fundamental frequency can be represented as a standing wave with two nodes – one at each end of the string and one anti-node at the center of the string.
The second harmonic has a frequency twice that of the first harmonic, while the third harmonic has a frequency three times that of the first harmonic. And so on and so forth.
A great animated visualization of the first four harmonics as standing waves and their longitudinal counterparts can be found here.
Notes, Octaves, and Frequencies
Certain frequencies sound pleasant to our ears when played together. Such frequencies are said to be consonant.
In music, an interval is a way of measuring the difference in the pitch of different sounds. Popular intervals in music can be represented with the following whole number ratios:
- Unison --> 1:1
- Octave --> 2:1
- Major sixth --> 5:3
- Perfect fifth --> 3:2
- Perfect fourth --> 4:3
- Major third --> 5:4
- Minor third --> 6:5
So you could say that 880Hz is an octave higher than 440Hz. Or if 440Hz is the first harmonic then 880Hz is the second harmonic.
Playing two sounds together can create interesting phenomena like beats. When two sounds of slightly different frequencies are played simultaneously, there's a periodic variation in the amplitude of the sound whose frequency is the difference between the original two frequencies.
$$ f_{beat} = f_{1} - f_{2} $$
In music, frequencies are classified into different pitch classes. In English-speaking regions, they are represented by the first 7 letters of the alphabet: A, B, C, D, E, F and G. Some might also know this as Do, Re, Mi, Fa, Sol, La and Ti, while others might know this as Sa, Re, Ga, Ma, Pa, Dha and Ni. The eighth note, or the octave, is given the same name as the first after which the pattern repeats again.
Most musical instruments today use the 12-tone chromatic scale, which divides an octave into 12 equally spaced parts on a logarithmic scale. Each part is said to be a semitone apart -- the smallest possible interval in music. Most instruments are tuned to the equally tempered scale with the note A on the middle octave tuned to 440Hz.
The 12-tone chromatic scale built on C names the 12 notes in every octave as following: C, C♯/D♭, D, D♯/E♭, E, F, F♯/G♭, G, G♯/A♭, A, A♯/B♭ and B.
♯ is pronounced as sharp and ♭ as flat. A sharp means a semitone higher while a flat means a semitone lower.
To find the frequencies in the middle octave, we need to find the frequency of the middle C. Middle C or C4's frequency is half that of C5.
Once we have have our middle C, we can create an array of size 13 that is equally spaced between the log of C4 and log of C5. We will also remove the last element (or C5 in this case) from the array.
The code is shown below:
import numpy as np C5 = 2**np.linspace(np.log2(440), np.log2(880), 13)[3] freqs = 2**np.linspace(np.log2(C5/2), np.log2(C5), 13)[:-1]
The resulting frequencies:
array([261.6255653 , 277.18263098, 293.66476792, 311.12698372, 329.62755691, 349.22823143, 369.99442271, 391.99543598, 415.30469758, 440. , 466.16376152, 493.88330126])
Chroma Representation
A pitch can be separated into two components: tone height and chroma.
Tone height is the octave number. Middle C, for example, is also known as C4.
Chroma features, also known as chromagrams, provide a powerful way to visualize music. A chroma feature is closely related to the seven pitch classes or the twelve notes in the 12-tone chromatic scale that we just saw. A chroma representation bins all the frequencies present in a sound at any particular time into one of twelve buckets, with each bucket representing one note.
As we discussed, an octave higher than an A note is still an A even though the frequency is twice that of the previous A note. Enumerating chroma features from 0 to 11, the C note takes the index 0 and the following indices are filled by a semitone higher than the previous index.
A short time Fourier transform can be converted into a chroma representation by getting a dot product of the STFT values with chroma filters and normalizing the output.
librosa filters can be visualized using the snippet below:
chroma_filters = librosa.filters.chroma(sampling_rate, 2048) fig, ax = plt.subplots(nrows=6, ncols=2, figsize=(12,9)) for i, row in enumerate(ax): for j, col in enumerate(row): col.plot(chroma_filters[i + j]) plt.show()
The plots look like the image below:
We will be using the same audio sample as in the first part of this series.
example_name = 'nutcracker' audio_path = librosa.ex(example_name) x, sampling_rate = librosa.load(audio_path, sr=None)
You can get the chroma representation with the
librosa library using the following snippet of code.
S = librosa.stft(x)**2 chroma = librosa.feature.chroma_stft(S=S, sr=sampling_rate) fig, ax = plt.subplots(figsize=(15,9)) img = librosa.display.specshow(chroma, y_axis='chroma', x_axis='time', ax=ax) fig.colorbar(img, ax=ax) ax.set(title='Chromagram')
Onset Detection
Onset detection refers to a set of methods that allow us to locate the onset of notes through a sound. There are several methods to do this. They can broadly be split into the following categories:
- Energy-based methods
- Pitch-based methods
- Phase-based methods
- Supervised learning
Energy-based Methods
In energy-based methods, the spectrum is used to measure energy change in the time-frequency domain. First-order differences in spectral values have been used to find the onsets in past but are imprecise. According to psychoacoustic principles, a similar change in frequency can be detected better at lower amplitudes. A relative differencing scheme helps us find peaks better.
For example, spectrum D can be defined as follows:
$$ D_{m}(n) = 20log_{10}(|X_m(n)|^{2}) - 20log_{10}(|X_m(n-1)|^{2}) $$
where $X_{m}(n)$ is the discrete STFT of the input signal.
The commonly-used energy-based detection methods can be generalized as follows:
$$ M = \frac{1}{N} \sum_{m=1}^{N} H(D_{m}(n)) $$
Where $ H(x) = \frac{x + |x|}{2} $ is the half-wave rectifier function, N is the total number of frequency bins in the spectrum D, and M is the detection function.
The detection function is further smoothed with a moving average. A simple peak-picking operation is applied to find the onsets. Peaks with values over a certain threshold are returned as onsets.
Phase-based Methods
STFT can be considered a band-pass filter where $X_m(n)$ denotes the output of $m^{th} $ filter. In cases where there is only one stable sinusoid component passing the $m^{th} $ band-pass filter, the output of the $m^{th} $ filter must have a constant or nearly constant frequency.
Hence the difference between consecutive unwrapped phase values must remain approximately constant too.
$$ \phi_{m}(n) - \phi_{m}(n - 1) \approx \phi_{m}(n - 1) - \phi_{m}(n - 2) $$
or
$$ \bigtriangleup \phi_{m}(n) \approx \phi_{m}(n) - 2 \phi_{m}(n - 1) - \phi_{m}(n - 2) \approx 0 $$
During transitions, the frequency isn't constant. Hence the $\bigtriangleup \phi_{m}(n) $ tends to be high.
Pitch-based Methods
Pitch-based methods use pitch characteristics to segment the sound into steady state and transient parts such that onsets are found only in the transient parts.
In A Casual Rhythm Grouping, Kristoffer Jensen suggests a detection function called the perceptual spectral flux in which the difference in frequency bands is weighed by the equal-loudness contours.
Equal loudness contours or Fletcher-Munson curves are contours of sound in the frequency domain when the listener perceives a constant amplitude for steady tones of sound.
$$ PFS_{n} = \sum_{m=1}^{N}W(X_{m}(n)^{1/3} - X_{m}(n - 1)^{1/3})$$
$X_{m}$ is the magnitude of the STFT, obtained using a Hanning window. $W$ is the frequency weighting used to obtain a value closer to the human loudness contour and the power function is used to simulate the intensity-loudness power law. The power function furthermore reduces random amplitude variations.
Supervised Learning
Neural networks have been utilized to detect onset frames in an audio signal too. A typical neural network-based onset detection pipeline looks like this:
An audio signal is first converted into its spectrogram. This spectrogram is passed to a neural network that tries to classify each frame as either an onset or not. The ones that are classified as onsets are then passed through a peak-picking operation like thresholding.
There are several neural network architectures that can be utilized for this problem. The most popular choices have been recurrent networks and convolutional neural networks. Recently, audio transformers are becoming a popular choice for music classification.
The same networks can be repurposed for onset detection. Miyazaki et al, for example, use a hybrid of convolutional networks and transformer blocks for onset detection.
librosa has onset detection features in their API and can be used as follows.
o_env = librosa.onset.onset_strength(x, sr=sampling_rate).png')
The visualization will be able to point out estimated locations of places where a new note is played through the audio.
A visualization of the first five seconds can be obtained like this.
o_env = librosa.onset.onset_strength(x, sr=sampling_rate) total_time = librosa.get_duration(x) five_sec_mark = int(o_env.shape[0]/total_time*5) o_env = o_env[:five_sec_mark][:, :five_sec_mark],-5secs.png')
As we can see above, the vertical lines are lined up correctly where note onsets are found. The vertical lines are plotted against the magnitude curve. The spectrogram is displayed above with the same X-axis to compare note onset visually.
Beat and Tempo
A beat in music theory is a unit of time that tracks the periodic element in music. You can think of beats as the times you tap your feet while listening to a song. The tempo of a song is the number of beats per minute. The tempo might change over the course of the song.
Detecting beats and estimating the tempo of a song are closely related to onset detection. Usually, detecting beats and tempo of a song is done in three steps:
- Onset detection: computing the locations of onsets based on spectral flux
- Periodicity estimation: computing periodic patterns in the onset locations
- Beat location estimation: computing location of beats depending on the onsets and the periodicity information
In Tempo and Beat Estimation of Musical Signals, the authors give the following definition for spectral flux:
$$ E(m,n) = \sum_{n} h(n - k)G(m,n)$$
where $h(n)$ approximates a differentiator filter and
$$ G(m,n) = \mathcal{F}\{|X(m,n)|\}$$
where $X(m,n)$ is the STFT of our signal.
The transformation $\mathcal{F}$ takes the STFT of the signal and passes it through a low-pass filter and nonlinear compression algorithm using the inverse hyperbolic sine function.
The authors then use a median filter to pick out the onsets that are true note attacks instead of low-amplitude peaks.
The result of this detection function can be thought of as a pulse train which has a high magnitude at note attacks. This can be done in two ways.
Spectral Product
The idea here is that strong harmonics are found at frequencies which are an integer multiple of the fundamental frequency.
To find this frequency, we calculate the discrete Fourier transform of the signal and get a product of all of its values, leading to a reinforced frequency.
The estimated tempo T is then easily obtained by picking out the frequency index corresponding to the largest peak of the reinforced frequency values. The tempo is required to be between 60 and 200 BPM or beats per minute.
Autocorrelation
The classic approach to finding the periodicity in an audio signal is using autocorrelation. ACF or autocorrelation function can be defined as
$$r(\tau) = \sum_{k}p(k + \tau)p(k)$$
where $\tau$ is the lag value. To find the estimated tempo, the lag of the three largest peaks of $r(\tau)$ are analyzed. In the case that no multiplicity relationship is found, the lag of the largest peak is taken as the beat period.
To find the beat locations, an artificial pulse train is created of tempo T using either spectral product or autocorrelation functions. We then cross-correlate this with the original detection function output.
We call the time index where the correlation is maximum $t_{0}$ and the first beat. The second and subsequent beats in a given analysis window are found by adding a beat period $\mathcal{T}$
$$t_{i} = t_{i-1} + \mathcal{T}$$
librosa allows us to calculate a static tempo, dynamic tempo and also visualize the BPM over time using a tempogram.
To calculate the static tempo, run the following code:
onset_env = librosa.onset.onset_strength(x, sr=sampling_rate) tempo = librosa.beat.tempo(onset_envelope=onset_env, sr=sampling_rate) print(tempo)
You should get a single element array as the output:
array([107.66601562])
To get the dynamic tempo:
dtempo = librosa.beat.tempo(onset_envelope=onset_env, sr=sampling_rate, aggregate=None) print(dtempo)
The result is an array:
array([112.34714674, 112.34714674, 112.34714674, ..., 107.66601562, 107.66601562, 107.66601562])
You can also visualize the dynamic tempo using the tempogram:
fig, ax = plt.subplots(figsize=(15,9)) tg = librosa.feature.tempogram(onset_envelope=onset_env, sr=sampling_rate, hop_length=hop_length) librosa.display.specshow(tg, x_axis='time', y_axis='tempo', cmap='magma', ax=ax) ax.plot(librosa.times_like(dtempo), dtempo, color='c', linewidth=1.5, label='Tempo estimate (default prior)') ax.set(title='Dynamic tempo estimation') ax.legend() plt.savefig('tempogram.png')
Spectrogram Decomposition
Spectrograms can provide a lot more information about a sound that just visual cues on onset and frequencies. We can use spectrograms to separate different components of a piece of music.
One of the most common use cases would be to separate harmonic sounds from the percussive sounds, e.g. piano, keyboard, guitar, and flute compared to drums, bongos, etc. This can be done using the Harmonic Percussive Source Separation algorithm or HPSS.
Harmonic Percussive Source Separation (HPSS)
The HPSS algorithm has 4 steps to it:
- Calculating the spectrogram
- Vertical and horizontal median filtering
- Binary masking of the filtered spectrogram
- Inverting the masked spectrogram
We know that given an ordered list of $N$ values, the median is the $((N-1)/2)^{th}$ value if $N$ is odd or else the sum of the $(N/2)^{th}$ and $((N+1)/2)^{th}$ terms.
Then, given a matrix $B \in R_{N×K}$, we define harmonic and percussive median filters as follows:
$ medfilt_{h}(B)(n,k) = median({B(m−l_{h},k),...,B(m+l_{h},k)})$
$medfilt_{p}(B)(n,k) = median({B(n,k−l_{p}),...,B(n,k+l_{p})})$
where $2l_{h} + 1$ and $2l_{p} + 1$ are the length of the harmonic and percussive filters respectively. The enhanced spectrograms are them calculated as follows.
$ \phi_{h} = medfilt_{h}(|X(n, k )|^{2})$
$ \phi_{p} = medfilt_{p}(|X(n, k )|^{2})$
where $X(n,k)$ is the STFT of the sound signal.
Binary masking is applied on the filtered spectrograms. For the harmonic spectrogram, the values of the element $ M_{h}(n,k)$ is $1$ if the value of$ \phi_{h}(n,k)$ is greater than or equal to $\phi_{p}(n,k)$. Otherwise the value of $M_{h}(n,k)$ is 0.
Similarly, for the percussive spectrogram, the values of the element $ M_{p}(n,k)$ is $1$ if the value of $\phi_{p}(n,k)$ is greater than $\phi_{h}(n,k)$. Otherwise the value of $M_{p}(n,k)$ is 0.
Note that this formulation means that $M_{h}(n,k) + M_{p}(n,k) = 1$ for all $n$ and $k$. To get the spectrogram of the percussive and harmonic elements, we do an element-wise multiplication between the original STFT $X$ and the binary masks $M_{p}$ and $M_{h}$.
Due to our definition of binary masking, every frequency bin at every point is time is either assigned to $X_{h}$ or $X_{p}$.
$$ X_{h} = X \bigodot M_{h} $$
$$ X_{p} = X \bigodot M_{p} $$
Once you have these, you can get the percussive and harmonic elements of the signal by applying an inverse STFT.
librosa provides an out of the box implementation for the HPSS algorithm.
S = librosa.stft(x) H, P = librosa.decompose.hpss(S) fig, ax = plt.subplots(nrows=3, sharex=True, sharey=True) img = librosa.display.specshow(librosa.amplitude_to_db(np.abs(S), ref=np.max), y_axis='log', x_axis='time', ax=ax[0]) ax[0].set(title='Full power spectrogram') ax[0].label_outer() librosa.display.specshow(librosa.amplitude_to_db(np.abs(H), ref=np.max(np.abs(S))), y_axis='log', x_axis='time', ax=ax[1]) ax[1].set(title='Harmonic power spectrogram') ax[1].label_outer() librosa.display.specshow(librosa.amplitude_to_db(np.abs(P), ref=np.max(np.abs(S))), y_axis='log', x_axis='time', ax=ax[2]) ax[2].set(title='Percussive power spectrogram') fig.colorbar(img, ax=ax, format='%+2.0f dB')
You can get the segregated signals as follows:
y_harm = librosa.istft(H) y_perc = librosa.istft(P)
librosa implementation also allows to decompose the signal into three elements instead of two: harmonic, percussive and residual. You can do this by setting the margin argument's value as anything greater than 1.
H, P = librosa.decompose.hpss(S, margin=3.0) R = S - (H + P) y_harm = librosa.istft(H) y_perc = librosa.istft(P) y_res = librosa.istft(R)
Conclusion
In this article, we explored notes, harmonics, octaves, chroma representation, onset detection methods, beat, tempo, tempograms, and spectrogram decomposition using the HPSS algorithm.
In the next part of this series, we will try to build a text to speech engine with deep learning. As we all like to say – stay tuned!
Add speed and simplicity to your Machine Learning workflow today | https://blog.paperspace.com/audio-analysis-processing-maching-learning/ | CC-MAIN-2022-27 | refinedweb | 3,266 | 56.05 |
I wanted to add my Facebook status to my other blog which is running Community Server 2.0. All I needed to do was write a user control to pull the RSS feed and display the text. This seemed easy enough, but it turned out to be a little tricky.
First I tried to use the XmlDocument class and load the RSS URL directly. That complained about a missing DTD which was confusing since the URL works fine in a browser. After some debugging, I discovered that Facebook sniffs your User Agent. Since the XmlDocument was sending an unknown user agent field, Facebook was replying with this page.
I changed my tactics a bit and used the HttpWebRequest object which allows me to specify the user agent field. After that it was relatively simple to load the response stream into an XmlDocument, use an XPath query to find the node I wanted, and load the status text into a literal control. Feel free to copy this code if you have run into a similar problem.
<%@ Import namespace="System" %>
<%@ Import namespace="System.IO" %>
<%@ Import namespace="System.Net" %>
<%@ Import namespace="System.Xml" %>
<%@ Import namespace="System.Web.UI.HtmlControls" %>
<%@ Import namespace="System.Web.UI.WebControls" %>
<%@ Import namespace="System.Web" %>
<%@ OutputCache Duration="600" VaryByParam="none" %>
<%@ Control Language="vb" AutoEventWireup="true" EnableViewState="false" Debug="false" %>
<script runat="server" language="vb">
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ltlFacebook.Text = ""
Dim sReader as StreamReader
Dim resp as HttpWebResponse
Try
Dim req as HttpWebRequest = CType(WebRequest.Create(""), HttpWebRequest)
req.UserAgent = "Windows-RSS-Platform/1.0 (MSIE 7.0; Windows NT 5.1)"
resp = CType(req.GetResponse(), HttpWebResponse)
sReader = new StreamReader(resp.GetResponseStream(), Encoding.UTF8)
Dim xmldoc As New XmlDocument
xmldoc.LoadXml(sReader.ReadToEnd())
Dim node as XmlNode = xmlDoc.SelectSingleNode("/rss/channel/item/title")
ltlFacebook.Text = node.InnerText
Finally
sReader.Close()
resp.Close()
End Try
End Sub
</script>
<asp:Literal</asp:Literal>
PingBack from
You may have noticed that there is a small new addition to the site. My current Facebook status is displayed…
How do you discover your ‘own’ RSS feed url?
There is an RSS feed on your Facebook Mini-Feed Status Stories page.
From facebook…
While Mini-Feed is no longer available on Facebook, your profile still contains all of the interesting stories about you in the Wall tab. The Wall tab includes Wall posts that used to appear on the Wall application on your profile, as well as all of the stories that used to appear in your Mini-Feed. You can control the stories and posts on your Wall tab even more effectively now. For example, if there is a story on your Wall that you really like and want to highlight to your friends you can hover over the story in question, click the ‘edit’ icon to the right of the story and then select "Make bigger." You can also customize how the story displays when it is generated. For example, if you add new photos to your Wall, you will have the option to edit the story that appears on your Wall.
Odd. Here’s how I got that link to work: Open up a new tab and log into facebook. Without logging out, switch back to this post and click the link. When I do that, it goes to the correct page and shows the RSS feed. But if I’m not logged in then I just get the log in page and never end up at the right place. | https://blogs.msdn.microsoft.com/ben/2008/01/03/pulling-a-facebook-rss-feed-via-net/ | CC-MAIN-2019-22 | refinedweb | 589 | 58.48 |
#include <BelosMultiVec.hpp>
List of all members.
A concrete implementation of this class is necessary. The user can create their own implementation if those supplied are not suitable for their needs.
Definition at line 54 of file BelosMultiVec.hpp.
BelosMultiVec constructor.
Definition at line 59 of file BelosMultiVec.hpp.
BelosMultiVec destructor.
Definition at line 62 of file BelosMultiVec.hpp.
Creates a new empty BelosMultiVec containing
numvecs columns.
Creates a new BelosMultiVec and copies contents of
*this into the new std::vector (deep copy).
Creates a new BelosMultiVec and copies the selected contents of
*this into the new std::vector (deep copy). The copied vectors from
*this are indicated by the
index.size() indices in
index.
Creates a new BelosMultiVec that shares the selected contents of
*this. The index of the
numvecs vectors copied from
*this are indicated by the indices given in
index.
Obtain the std::vector length of *this multivector block.
Obtain the number of vectors in *this multivector block. a std::vector
b where the components are the individual dot-products, i.e.
b[i] =
A[i]^T*
this[i] where
A[i] is the i-th column of A.
Compute the 2-norm of each individual std::vector of
*this. Upon return,
normvec[i] holds the 2-norm of the
i-th std::vector of
*this.
Copy the vectors in
A to a set of vectors in
*this. The
numvecs vectors in
A are copied to a subset of vectors in
*this indicated by the indices given in
index.
Replace the vectors in
*this with random vectors.
Replace each element of the vectors in
*this with
alpha.
Print the
*this multivector. | http://trilinos.sandia.gov/packages/docs/r10.0/packages/belos/doc/html/classBelos_1_1MultiVec.html | crawl-003 | refinedweb | 274 | 52.36 |
Closed Bug 749500 Opened 10 years ago Closed 10 years ago
Bug 731878 breaks SDK 10
.5 build
Categories
(Core :: Widget: Cocoa, defect)
Tracking
()
mozilla15
People
(Reporter: m_kato, Assigned: masayuki)
References
Details
Attachments
(1 file, 1 obsolete file)
Now, thunderbird trunk is burning due to landing bug 731878. Is this API from 10.6? /builds/slave/macosx-comm-central-bloat/build/mozilla/widget/cocoa/nsChildView.mm:3963: warning: 'NSEvent' may not respond to '+pressedMouseButtons' /builds/slave/macosx-comm-central-bloat/build/mozilla/widget/cocoa/nsChildView.mm:3963: warning: (Messages without a matching method signature /builds/slave/macosx-comm-central-bloat/build/mozilla/widget/cocoa/nsChildView.mm:3963: warning: will be assumed to return 'id' and accept /builds/slave/macosx-comm-central-bloat/build/mozilla/widget/cocoa/nsChildView.mm:3963: warning: '...' as arguments.) /builds/slave/macosx-comm-central-bloat/build/mozilla/widget/cocoa/nsChildView.mm:3963: error: invalid conversion from 'objc_object*' to 'NSUInteger'
Yes. The API was introduced on 10.6.
(In reply to Masayuki Nakano (:masayuki) (Mozilla Japan) (away: 4/29 - 5/6) from comment #1) > Yes. The API was introduced on 10.6. I think you'll want to add something like this to the header then. > #if !defined(MAC_OS_X_VERSION_10_6) || \ > MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6 > @interface NSEvent (SnowLeopardEventFeatures) > + (NSUinteger)pressedMouseButtons; > @end > #endif I've also been told in the past to use [foo respondsToSelector:whatever] instead of OnVersionOrLater (feature detect instead of version check), but I think we're pretty mixed in there and that wouldn't be the issue.
The Thunderbird builders are going to be upgrading to 10.7 with an 10.6 sdk real soon (like next couple of weeks all being well), so I don't mind too much if this is broken there. Might want to consider if we're breaking developers using the 10.5 sdk though (I can't remember what has been said about sdk requirements).
zpao: Thank you, it works fine!
Assignee: nobody → masayuki
Status: NEW → ASSIGNED
Attachment #619003 - Flags: review?(smichaud)
Comment on attachment 619003 [details] [diff] [review] Patch Glad it's working! We do that sort of thing in a few other places as well. And on that note, we've kept other instances of this pattern to header files so my gut tells me we should do the same here, but I haven't spent that much time in this code. Steven will correct me if I'm wrong though!
Attachment #619003 - Flags: feedback-
I read Paul's comment (comment #5) after I did the review :-( Your patch works fine, Masayuki. But now I also think it might be better to put it into a header file. For example there's an NSEvent (Undocumented) category in nsChildView.h to which a definition of +[NSEvent pressedMouseButtons] might be added, with or without the version-specific ifdefs. It's not a big deal. Just a matter of style. The definition of +[NSEvent pressedMouseButtons] is (of course) needed when building on versions of the OS (or the SDK) that don't define it, so that you don't get compile errors (or warnings). You still also need to only call this method on versions of the OS that support it.
Attachment #619003 - Attachment is obsolete: true
Attachment #619235 - Flags: review?(smichaud)
Comment on attachment 619235 [details] [diff] [review] Patch Looks fine to me.
Attachment #619235 - Flags: review?(smichaud) → review+ Thank you. And sorry for my fault.
Target Milestone: --- → mozilla15
Status: ASSIGNED → RESOLVED
Closed: 10 years ago
Resolution: --- → FIXED | https://bugzilla.mozilla.org/show_bug.cgi?id=749500 | CC-MAIN-2022-33 | refinedweb | 575 | 58.18 |
Feb 01, 2013 05:25 AM|Mayur_Suchi|LINK
Hii friends,
In ASP.Net mobile application we use namespace "System.Web.Mobile" and make mobile based application.
Does these Mobile based application supports Android also?
I want to make my application which will run on tablet so i want it to be Android compatible.
Will ASP.Net Mobile application will be useful to me?
Please reply..
All-Star
37441 Points
Feb 01, 2013 05:28 AM|AidyF|LINK
Do you mean on a mobile browser, or as an android app? It won't make it an Andoid app.
Star
11166 Points
Feb 01, 2013 05:56 AM|nilsan|LINK
Please go through below links: (Framework that makes your app work cross browser/platform and provide consistent UI) - Responsive Design.
You can use HTML5, CSS3 for Responsive Design.
Star
14065 Points
Feb 01, 2013 11:40 AM|roopeshreddy|LINK
Hi,
I blogged the same -
Hope it helps u...
5 replies
Last post Feb 02, 2013 03:44 AM by Mayur_Suchi | https://forums.asp.net/t/1879563.aspx?ASP+net+Mobile+Application | CC-MAIN-2020-45 | refinedweb | 168 | 75.91 |
having problems with subscribe when using boost::bind
here is my code
#include <ros/ros.h> #include "costmap/costmap.h" #include <sensor_msgs/LaserScan.h> int main(int argc, char **argv) { ros::init(argc, argv, "costmap"); ros::NodeHandle n; costmap costmap_; ros::Subscriber sub = n.subscribe<sensor_msgs::LaserScan::ConstPtr>("scan", 1000, boost::bind(&upDateMap, _1, costmap_)); ros::spin(); return 0;} void upDateMap(const sensor_msgs::LaserScan::ConstPtr &msg, costmap &costmap_){}
and here is my costmap.h:
void upDateMap(const sensor_msgs::LaserScan::ConstPtr &msg, costmap &costmap_); class costmap {};
costmap is a class defined by me.
When i run catkin_make,
In file included from /home/mushen/catkin_ws/src/costmap/src/costmap.cpp:1:0:
/home/mushen/catkin_ws/src/costmap/include/costmap/costmap.h:14:61: error: ‘costmap’ has not been declared
comes out.
how could i solve this?
Is the
costmapclass actually declared in the
.cppfile that contains
main(..)? If not, it could be that you're simply missing an
#includefor the header that declares
costmap.
Isn't the issue that you're using
costmap(the class) in
upDateMap(..)before it's actually declared in
costmap.h?
Try swapping the declarations of
class costmapand
void upDateMap(..)and recompile.
This seems like a straightforward C++ issue to me, not a ROS or
boost::bindone. | https://answers.ros.org/question/311284/having-problems-with-subscribe-when-using-boostbind/ | CC-MAIN-2021-21 | refinedweb | 209 | 53.27 |
Basic TensorFlow Building Blocks
The following is an abbreviated look at Chapter 3 of Learning TensorFlow.
Workflow
Working in TensorFlow boils down to two simple steps
- Construct your execution graph
- Run it in a session
Say you wanted to use TensorFlow to implement the following.
from IPython.display import Image Image('images/graph.png')
Construct your execution graph
Arriving at our final value of
5 requires a few intermediate values along the way. We could express this in pure python with the following:
a = 5 b = 2 c = 3 d = a * b e = b + c f = d - e print(f)
5
The key difference between this approach and how TensorFlow is organized is that whereas all of this execution is actually happening line by line, when we construct our network, nothing actually gets exectuted. For example:
import tensorflow as tf a = tf.constant(5) b = tf.constant(2) c = tf.constant(3) d = tf.multiply(a, b) e = tf.add(b, c) f = tf.subtract(d, e)
Then, once we have our execution graph, we can run everything by spinning up a
Session object. As a best practice, we’ll use a context manager.
with tf.Session() as sess: result = sess.run(f) print(result)
5
A quick note on this–
f, our result variable, depended on everything before it (see the execution graph above). As a result, TensorFlow went ahead and executed each node in the graph (a process called fetching). If, however, we didn’t need any node in the graph, it would happily skip over it and save us resources/time.
Variables and Placeholders
As we saw above, we constructed our graph by instantiating some nodes and then doing things to them. In the example, we made
constants, but there are other types of nodes worth using.
tf.Variable, the trainable parameters of our model, modified as a result of training
tf.placeholder, used to pass input data
Variables
Unlike
tf.constants which are immutable, these objects can change as a result of execution, but also maintain state iteration-to-iteration.
Furthermore, they must be explicitly instantiated by running
tf.global_variables_initializer() at the beginning of your
tf.Session().
init_vals = [1, 2, 3] var = tf.Variable(init_vals) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) print(sess.run(var))
[1 2 3]
Placeholders
On the other hand, we’ll often want to pass data into a model for training/scoring purposes. If a regression is a big
y = mX + b problem, we need a way to pass in the
X.
Thus we use
tf.placeholder(), passing in a datatype and an expected shape. The shape variable can be a tuple of fixed size, but if we pass
None as any of the dimensions, we allow for arbitrarily many observations (often on the number-of-records-level).
The following are all valid instantiations.
tf.placeholder(tf.float32, shape=(1, 10)) tf.placeholder(tf.float64, shape=(None, 100)) tf.placeholder(tf.bool, shape=(None));
To actually use the placeholder, though, you must pass the
feed_dict argument to your
Session().run() call.
As a quick example, say you wanted, for some reason, to normalize a list of floats relative to all of the values in the list… using TensorFlow.
vals = tf.placeholder(tf.float64, shape=(None,)) mean, stdev = tf.nn.moments(vals, axes=0) normed = (vals - mean) / stdev
input_data = [1, 2, 3, 4, 5, 6, 7]
with tf.Session() as sess: normed_vals = sess.run(normed, feed_dict={vals: input_data}) print(normed_vals)
[-0.75 -0.5 -0.25 0. 0.25 0.5 0.75]
A note on datatypes
If you’ve got incompatible types between two tensors, the whole execution will error out.
a = tf.constant(1.0) b = tf.constant(2) try: c = a + b except TypeError: print("Whoops") with tf.Session() as sess: sess.run(c)
Whoops
But we can easily fix this using
tf.cast()
a = tf.constant(1.0) b = tf.constant(2) try: a = tf.cast(a, tf.int32) c = a + b except TypeError: print("Whoops") with tf.Session() as sess: print(sess.run(c))
3 | https://napsterinblue.github.io/notes/python/tensorflow/basics/ | CC-MAIN-2021-04 | refinedweb | 682 | 60.11 |
Red Hat Bugzilla – Bug 177564
The spec file install own version of pg_config.h which is missing support for Alpha
Last modified: 2013-07-02 23:07:34 EDT
Description of problem:
The spec file install own version of pg_config.h which is missing support for
Alpha. Please apply the following small patch that fixes it:
--- pg_config.h.orig 2005-12-15 22:38:07.000000000 +0300
+++ pg_config.h 2006-01-11 23:22:46.000000000 +0300
@@ -21,4 +21,6 @@
#include "pg_config_s390x.h"
#elif defined(__s390__)
#include "pg_config_s390.h"
+#elif defined(__alpha__)
+#include "pg_config_alpha.h"
#endif
It would help AlphaCore project to build this package unmodified.
Thank you.
Version-Release number of selected component (if applicable):
8.1.2-1
Yeah, this whole concept of trying to avoid header variations with architecture
seems messed up :-(. I wonder what other arches people are going to try to
build Fedora SRPMs on.
Note to self: mysql has same issue.
Yes, I don't see any advantage of it. We don't have different arch header files
in the same package. As far as I understand the pg_config.h is build by
configure for specific arch and won't be used on other arches.
The reason it's there is to allow installing both 32- and 64-bit devel RPMs on
multilib machines. It's an ugly solution but I don't (yet?) see a better one.
I see. How about doing this only for multilib arches. For non-multilib arches
copy postgres "pg_include.h" as pg_include_original.h and include it as last
chance if none of defines worked. It would keep current approach, but give other
arches the chance to work. :)
Thank you.
That's a good thought. Actually, on non-multilib machines there's no reason for
adding the indirection at all. I'll see what I can do.
Fixed in postgresql-8.1.3-1 | https://bugzilla.redhat.com/show_bug.cgi?id=177564 | CC-MAIN-2018-30 | refinedweb | 316 | 71.21 |
# Modes are vim’s killer feature? Seriously?
*Author of the original post in Russian: [varanio](https://habr.com/en/users/varanio/)*
You may have read a recent [article suggesting that vim is great unlike IDEs](https://habrahabr.ru/post/339908/), because of their allegedly low typing speed.
Let’s recall that the main message of that article was that vim’s killer feature consists in its modes that sort of outshine everything else. That said, the author acknowledged that IntelliJ IDEA and other IDEs provide hotkeys and other user experience which can be easily used. However, since they lack modes, vim is supposed to be everyone’s first choice.
The author then suggests that instead of pressing `ctrl+arrows` to move between words, it is easier to press Esc, e and then go back to the `i` editing mode. Understandably, all this trouble because the author finds it **inconvenient to hold `ctrl`**.
I know that articles that criticize vim get many negative votes, but I just have to speak out.
Are your lines of code so long that your finger grows tired holding the key to the point where you really need modes? I can get it when you are typing a long constant — in this case you can press Caps Lock and type its name. Even then I hardly press this key more often than once a year. But to switch modes back and forth for moving forward down a couple of words, let alone to call that vim’s killer feature, sounds like a bit of a stretch.
By the way, in IntelliJ IDEA, you can change the case of a word (or the selected text) with one key, so it does not really require using Caps Lock either.
I admit that vim can be good for editing config files on a remote server. Also, vim can be great for new languages that have not yet been played around with by JetBrains. Writing custom plugins is easier for vim (but in 99% of cases you won’t need them with an adequate IDE). Perhaps, it is more convenient for editing long texts. But that is irrelevant for standard industrial coding!
I should at once mention several points here.
### Vim can be turned into a kind of IDE by installing plugins and learning hotkeys to operate those plugins
It can indeed, but why would anyone bother?
It seems like a weird challenge considering that IDEs have it all, and with a much more user-friendly experience. You won’t have to use a mouse, I promise!
Let me explain the thing with editing without a mouse by using an example. I first open IntelliJ IDEA and create a new file.
I press p, and the IDE immediately prompts me with a suggestion of the word package. All I need to do is press Enter to put the word package into the text inside the editor.
Then I press `c`, and the IDE suggests class at once.
I enter the name of the class (e.g., `Habr`), type the curly brace `{`, and the IDE automatically completes the closing brace just behind the cursor.
Then I type pu, and the IDE understands that it’s probably public. I type in `H` and press `Enter` to get Habr, because the IDE has already got it that I want to create a constructor.
I proceed to writing the body of the constructor, e.g. I call the init() method, which is not there yet. My IDE highlights it with red color, which indicates that this method does not exist. Once I press `alt-ENTER`, the IDE will insert the code snippet in the right place:
```
private void init() {
}
```
If I happen to type `new Habr(5)` inside this method (the word Habr was also prompted of course), i.e. if I try to call a non-existing constructor, IntelliJ IDEA will underscore that bit right away, so I just press and choose what exactly I want to do: whether it is to add an int argument to the constructor or add a new constructor with an int parameter. I choose the latter option, and the IDE immediately adds a new constructor after the first one:
```
public Habr(int i) {
}
```
I won’t mention the automated indentation and other features that help you edit the code, since naturally they are present.
Here is what I got in the end:
```
package x;
class Habr
{
public Habr()
{
init();
}
public Habr(int i) {
}
private void init() {
new Habr(5);
}
}
```
All I did was literally hit a couple of keys and the hotkey.
I did not install any plugins.
I did not have to train for a month to be able to do this.
I NEVER TOUCHED THE MOUSE (I used Caps Lock here not because I wanted to shout out like a nutcase, but because it was fun to try the feature).
I did not switch to any modes and did not have to recall any key or knob combinations. The only one I used was (but that was a context-dependent thing, a sort of a “problem solving” hotkey).
If you hate using the mouse, you can navigate through the code using special hotkeys, such as for jumping to the right class, file, method, line number, etc.
You can select text by repeatedly pressing to select the current word, the current text between the braces, etc.
Vim allows you to jump to a particular character. For example, you can get to a letter x in the line of text without touching the mouse. Yet an IDE also gives you this opportunity through pressing and typing in the required chunk of text. This is also a sort of a mode by the way. It is called the search mode, duh!
I also don’t need the mouse to jump to the right function call and then, again without the mouse (press `ctrl-b`), to jump to the description of this function.
### Vim has several unique out-of-box editing features that are missing in IDEs
* **Move to the next/previous paragraph.**
Yes, it sounds like a useful feature for an IDE. But rather for editing articles for Habr than for actual coding.
* **Move to the next space character.**
Well, you can call it a useful feature, but not too cool. The repeated pressing of `ctrl+arrows` will produce the same effect.
* **Jump half a page up/down.**
I haven’t yet decided whether I need this one for anything.
* **Jumping to the first/last/middle line on the screen.**
I don’t really see what this is for. That is, it may come handy some time, but it is by no means a killer feature.
* **It is possible to delete exactly N lines of code.**
Yeah, right, I do this every day. Everybody needs to delete exactly 19 lines of code from time to time, right?
I am in no way a vim guru, so I may have missed some key aspects. Please share your thoughts in the comment section. Yes, of course there are zillions of plugins on top of that. But IDEs also have them, and in comparable quantities.
### Summary
Here is my own take-away from this. I will stay away from vim when it comes to code editing, no matter what you’ll say. I was not very impressed with using modes instead of holding ctrl or even `ctrl-alt-shift`. IDEs give you more out-of-box features, without the need to spend a while on learning and assigning [hotkeys](https://en.wikibooks.org/wiki/Vim). Most everyday tasks can be accomplished with an IDE by learning just a couple of hotkeys. You can even skip them altogether if you are happy using the mouse.
It has long been established that a programmer takes more time to learn code than to actually write it. So whether you’ll use your mouse or not does not make big difference. However, let me reiterate that IDEs allows you to do almost everything (if not everything) without using the mouse.
Vim will work better than nano for remotely editing config files on a server, provided that the following conditions are satisfied:
1. You need to have a good grip of vim.
2. You need to edit industrial quantities of config files to feel the advantage. If you only need to make changes to one configuration file once or twice a month, nano or indeed anything at all will work well.
You can start voting me down or, better still, offering your counter-arguments :). | https://habr.com/ru/post/436004/ | null | null | 1,428 | 80.51 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.