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 |
|---|---|---|---|---|---|
Important: Please read the Qt Code of Conduct -
Qt under windows: Switch to a new Platform SDK
Our application needs to implement features that aren't available in Qt. For that I need my windows application to use win32.
I implement my own win32 only class, and include:
@#include <windows.h>
#include <windowsx.h>
#include <WinUser.h>@
my problem is that it takes the include files from the default VS2005 location defined in the build environment setup inside Qt-Creator (VCINSTALLDIR). It is an older Platform SDK that doesn't support what I need.
I have a newer Platform SDK at:
@C:\Program Files\Microsoft SDKs\Windows\v6.1\include@
How do I make Qt-Creator take the windows include files from there without the ugliness of having full paths in my source code's #include ?
BTW: VS2005 and the new SDK are fine when built under visual Studio. No Compatibility issues whatsoever, But i'd rather stick to QT-Creator.
I have so far tried the following without success:
In Qt-Creator -> Projects -> build environment, I tried to modify the following items to reflect the path of the newer platform SDK first, ahead of the other paths:
@FRAMEWORKSDIR
INCLUDE
LIB@
Have you try add in your .pro file something like this:
@
INCLUDEPATH += C:\Program Files\Microsoft SDKs\Windows\v6.1\include
@
when building under Qt-Creator and windows, obviously other include paths exist, that are not defined in your *.pro file. If two identically named header files exist, one in an older SDK folder and one in a new SDK folder, and QT by default takes the old one. How do you force it to use the new one? what guarantees that what's specified in the *.pro file INCLUDEPATH statements will be taken into consideration first when looking for headers or library files? | https://forum.qt.io/topic/14782/qt-under-windows-switch-to-a-new-platform-sdk/3 | CC-MAIN-2020-34 | refinedweb | 305 | 64.1 |
QuickBundles [Garyfallidis12] is a flexible algorithm that requires only a distance metric and an adjacency threshold to perform clustering. There is a wide variety of metrics that could be used to cluster streamlines.
The purpose of this tutorial is to show how to easily create new
Feature
and new
Metric classes that can be used by QuickBundles.
DIPY provides a simple, flexible and fast framework to do clustering of sequential data (e.g. streamlines).
A sequential datum in DIPY is represented as a numpy array of size \((N \times D)\), where each row of the array represents a \(D\) dimensional point of the sequence. A set of these sequences is represented as a list of numpy arrays of size \((N_i \times D)\) for \(i=1:M\) where \(M\) is the number of sequences in the set.
This clustering framework is modular and divided in three parts:
Feature extraction
Distance computation
Clustering algorithm
The feature extraction part includes any preprocessing needed to be done on
the data before computing distances between them (e.g. resampling the number of
points of a streamline). To define a new way of extracting features, one has to
subclass
Feature (see below).
The distance computation part includes any metric capable of evaluating a
distance between two set of features previously extracted from the data. To
define a new way of extracting features, one has to subclass
Metric (see
below).
The clustering algorithm part represents the clustering algorithm itself
(e.g. QuickBundles, K-means, Hierarchical Clustering). More precisely, it
includes any algorithms taking as input a list of sequential data and
outputting a
ClusterMap object.
This section will guide you through the creation of a new feature extraction method that can be used in the context of this clustering framework. For a list of available features in DIPY see Tractography Clustering - Available Features.
Assuming a set of streamlines, the type of features we want to extract is the arc length (i.e. the sum of the length of each segment for a given streamline).
Let’s start by importing the necessary modules.
from dipy.segment.metric import Feature from dipy.tracking.streamline import length import numpy as np from dipy.data import get_fnames from dipy.io.streamline import load_tractogram from dipy.tracking.streamline import Streamlines from dipy.viz import window, actor, colormap from dipy.segment.clustering import QuickBundles from dipy.segment.metric import SumPointwiseEuclideanMetric from dipy.segment.metric import Metric from dipy.segment.metric import VectorOfEndpointsFeature
We now define the class
ArcLengthFeature that will perform the desired
feature extraction. When subclassing
Feature, two methods have to be
redefined:
infer_shape and
extract.
Also, an important property about feature extraction is whether or not its process is invariant to the order of the points within a streamline. This is needed as there is no way one can tell which extremity of a streamline is the beginning and which one is the end.
class ArcLengthFeature(Feature): """ Computes the arc length of a streamline. """ def __init__(self): # The arc length stays the same even if the streamline is reversed. super(ArcLengthFeature, self).__init__(is_order_invariant=True) def infer_shape(self, streamline): """ Infers the shape of features extracted from `streamline`. """ # Arc length is a scalar return 1 def extract(self, streamline): """ Extracts features from `streamline`. """ # return np.sum(np.sqrt(np.sum((streamline[1:] - streamline[:-1]) ** 2))) # or use a DIPY's function that computes the arc length of a streamline. return length(streamline)
The new feature extraction
ArcLengthFeature is ready to be used. Let’s use
it to cluster a set of streamlines by their arc length. streamlines = Streamlines(fornix)
Perform QuickBundles clustering using the metric
SumPointwiseEuclideanMetric and our
ArcLengthFeature.
metric = SumPointwiseEuclideanMetric(feature=ArcLengthFeature()) qb = QuickBundles(threshold=2., metric=metric) clusters = qb.cluster(streamlines)
We will now visualize the clustering result.
# Color each streamline according to the cluster they belong to. cmap = colormap.create_colormap(np.ravel(clusters.centroids))_arclength.png', size=(600, 600)) # Enables/disables interactive visualization interactive = False if interactive: window.show(scene)
This section will guide you through the creation of a new metric that can be used in the context of this clustering framework. For a list of available metrics in DIPY see Tractography Clustering - Available Metrics.
Assuming a set of streamlines, we want a metric that computes the cosine distance giving the vector between endpoints of each streamline (i.e. one minus the cosine of the angle between two vectors). For more information about this distance check.
Let’s start by importing the necessary modules.
We now define the class
CosineMetric that will perform the desired
distance computation. When subclassing
Metric, two methods have to be
redefined:
are_compatible and
dist. Moreover, when implementing the
dist method, one needs to make sure the distance returned is symmetric
(i.e. dist(A, B) == dist(B, A)).
class CosineMetric(Metric): """ Computes the cosine distance between two streamlines. """ def __init__(self): # For simplicity, features will be the vector between endpoints of a streamline. super(CosineMetric, self).__init__(feature=VectorOfEndpointsFeature()) def are_compatible(self, shape1, shape2): """ Checks if two features are vectors of same dimension. Basically this method exists so that we don't have to check inside the `dist` method (speedup). """ return shape1 == shape2 and shape1[0] == 1 def dist(self, v1, v2): """ Computes a the cosine distance between two vectors. """ norm = lambda x: np.sqrt(np.sum(x**2)) cos_theta = np.dot(v1, v2.T) / (norm(v1)*norm(v2)) # Make sure it's in [-1, 1], i.e. within domain of arccosine cos_theta = np.minimum(cos_theta, 1.) cos_theta = np.maximum(cos_theta, -1.) return np.arccos(cos_theta) / np.pi # Normalized cosine distance
The new distance
CosineMetric is ready to be used. Let’s use
it to cluster a set of streamlines according to the cosine distance of the
vector between their endpoints. = fornix.streamlines
Perform QuickBundles clustering using our metric
CosineMetric.
metric = CosineMetric() qb = QuickBundles(threshold=0.1, metric=metric) clusters = qb.cluster(streamlines)
We will now visualize the clustering result.
# Color each streamline according to the cluster they belong to. cmap = colormap.create_colormap(np.arange(len(clusters)))_cosine.png', size=(600, 600)) if interactive: window.show(scene). | https://dipy.org/documentation/1.4.1./examples_built/segment_extending_clustering_framework/ | CC-MAIN-2021-25 | refinedweb | 1,014 | 50.33 |
If you're not familiar with Backblaze, they're a handy and inexpensive service that backs up your computer. I've been using them for years, and I even had to restore files when my hard drive succumbed to the "click of death" a couple years ago, so totally worth it.
They have a cloud storage service too, in the same vein as AWS, Rackspace, etc. When you sign up they give you 10GB free to play around with, so let's take advantage of that and check out the Backblaze B2 Storage API..
Authenticating
As usual, you'll need to prove who you are before you can go making requests.
1. Generate an Application Key
While logged in to the Backblaze site, click on the "My Account" link in the upper-right, then the "Show Account ID and Application Key" link. A dialog captioned "Account ID & Application Key" appears. Press the "Create Application Key" button and you'll have the two vital pieces of data you need for authenticating with Backblaze.
2. Get an Authorization Token
You'll need to make an API call to get the authorization token, which then lets you make other more interesting API calls.
Using Curl
To get the authorization token, you can do one of a couple of things. If you have
curl available in your terminal, just run this, substituting
ACCOUNT_ID and
APPLICATION_KEY with the appropriate values.
curl -u "ACCOUNT_ID:APPLICATION_KEY"
{ "absoluteMinimumPartSize": 5000000, "accountId": <your_account_id>, "apiUrl": "", "authorizationToken": <your_new_shiny_auth_token>, "downloadUrl": "", "minimumPartSize": 100000000, "recommendedPartSize": 100000000 }
Using Postman
You can also do it from within Postman, by doing a
GET on, and setting up authorization like in the following screenshot. Just add the
ACCOUNT_ID and
APPLICATION_KEY in the username and password fields, and click the "Preview Request" button. That adds a new "Authorization" field under the "Headers" tab, which is the base-64 encoded version of your account id and application key.
A Quick Note on the apiUrl
Take a look at the response you get with the auth token in it. There's a field called
apiUrl, which is important too. When you make other API calls, if you try to use the same base url you used to authenticate, you'll get an error:...
{ "code": "bad_request", "message": "this request should go to a host name for B2_API", "status": 400 }
Just substitute
api.backblazeb2.com with whatever value is in the
apiUrl field:...
Testing It Out
There's a lot you can do - check out the docs. I'll just touch the tip of the iceberg here.
Create a Bucket
Let's try creating a bucket. Use the
apiUrl and
authorizationToken values you got in the previous call. Notice that we're using the
GET action here.
Flip over to the website if you want, and make sure it was created.
It's odd that they allow use of the
GET, but it's documented. Usually you
GET some piece of data, whereas creating something would generally be a
POST. You can do it that way too. (It's not shown here, but the Authorization token is still in the headers section.)
I implemented it in C#, so you can try it out from an actual language and not just Postman. Either copy from here (fill in your details) or try it on DotNetFiddle.
using System; using System.Net; public class Program { public static void Main() { var apiUrl = "API_URL"; //Provided by b2_authorize_account var authToken = "AUTH_TOKEN"; //Provided by b2_authorize_account var accountId = "ACCOUNT_ID"; //B2 Cloud Storage AccountID var bucketName = "my-very-first-bucket"; //The unique bucket ID var bucketType = "allPrivate"; var postUrl = $"{apiUrl}/b2api/v1/b2_create_bucket"; var jsonData = $"{{\"accountId\":\"{accountId}\",\"bucketName\":\"{bucketName}\",\"bucketType\":\"{bucketType}\"}}"; using (var client = new WebClient()) { client.Headers.Add("Authorization", authToken); var response = client.UploadString(postUrl, jsonData); Console.WriteLine(response); } } }
Delete a Bucket
Might as well clean up after ourselves. Now that you've created a bucket, how about deleting the bucket? That's as easy as posting to the right endpoint and providing the id of the bucket (returned in the creation above).
This highlights another odd decision though. REST provides a
DELETE action that would've been more intuitive, so that a call like this could've worked (if they had designed it that way).
DELETE<your_bucket_id>
One of the things I've noticed about REST is that there are few hard and fast rules... just a lot of guidelines, suggestions, and differing opinions. In this case it's not bad at all, but try hard enough and you can do some truly unintuitive stuff with REST.
I implemented this one in C# too. Copy the code below or try it on DotNetFiddle. Don't forget to fill in your own details.
using System; using System.Net; public class Program { public static void Main() { var apiUrl = "API_URL"; //Provided by b2_authorize_account var authToken = "AUTH_TOKEN"; //Provided by b2_authorize_account var accountId = "ACCOUNT_ID"; //B2 Cloud Storage AccountID var bucketId = "BUCKET_ID"; //The unique bucket ID var postUrl = $"{apiUrl}/b2api/v1/b2_delete_bucket"; var jsonData = $"{{\"accountId\":\"{accountId}\",\"bucketId\":\"{bucketId}\"}}"; using (var client = new WebClient()) { client.Headers.Add("Authorization", authToken); var response = client.UploadString(postUrl, jsonData); Console.WriteLine(response); } } }
Thoughts
It's great that the Backblaze API docs include sample usages in 6 different languages for each endpoint. This should make it far easier to get started, although I noticed the code snippets are a bit outdated, at least the C# snippet I started to use before I wrote my own.
The requirement to setup an "application", in order to generate an authentication token and allow calls to their API, seems to be pretty common. It makes sense, since any system - no matter how sophisticated - has limits. If a single user/account is found to be making too many requests, they can be throttled or disabled. | https://grantwinney.com/what-is-backblaze-b2-api/ | CC-MAIN-2021-43 | refinedweb | 957 | 55.03 |
Writing your first Burp Suite extension_
This guide will help you to write your first Burp extension in any of the supported languages (Java, Python & Ruby).
Basic steps to get an extension running
Before we get into specifics for each language, there is some general context to bear in mind: Burp looks for a class called
BurpExtender to instantiate (with no constructor parameters) and then calls
registerExtenderCallbacks() on this object passing in a "
callbacks" object. Think of this as the entrypoint for your extension, allowing you to tell Burp what your extension is capable of, and when Burp should ask your extension questions.
First of all you'll need an IDE. Some popular options are: IntelliJ IDEA, Netbeans, and Eclipse.
Create a new project, and create a package called "burp". Next you'll need to copy in the interface files which you can export from Burp at Extender / APIs / Save interface files. Save the interface files into the folder that was created for the burp package.
Now that you have the general environment set up you'll need to create the actual extension file. Create a new file called
BurpExtender.java (or a new class called
BurpExtender, if your IDE makes the files for you) and paste in the following code:
public class BurpExtender implements IBurpExtender
{ public void registerExtenderCallbacks (IBurpExtenderCallbacks callbacks) {
// your extension code here } }
This example does nothing at all, but will compile and can be loaded into Burp after you generate a JAR file from your IDE - it will usually be in a build or dist directory.. You will need to download the "Standalone Jar" version and configure Burp with its location (at Extender / Options / Python environment).
Now create a new file with any name you like, ending in '.py', and add the following content to that file:
class BurpExtender(IBurpExtender): def registerExtenderCallbacks( self, callbacks): # your extension code here
return
Then go to the Extensions tab, and add a new extension. Select the extension type "Python", and specify the location of your file.
This example does nothing at all, but should load into Burp without any errors.
Note: Because of the way in which Jython dynamically generates Java classes, you may encounter memory problems if you load several different Python extensions, or if you unload and reload a Python extension multiple times. If this happens, you will see an error like:
You can avoid this problem by configuring Java versions lower than 8 to allocate more PermGen storage, by adding a
XX:MaxPermSize option to the command line when starting Burp. For example:
This option is not available in Java 8+, and permgen size should instead be automatically managed by the JVM.
Burp relies on JRuby to provide its Ruby support. You will need to download the "Complete .jar" version and configure Burp with its location (at Extender / Options / Ruby environment).
Now create a new file with any name you like, ending in '.rb', and add the following content to that file:
java_import 'burp.IBurpExtender'
class BurpExtender include IBurpExtender
def registerExtenderCallbacks(callbacks) # your extension code here end end
Then go to the Extensions tab, and add a new extension. Select the extension type "Ruby", and specify the location of your file.
This example does nothing at all, but should load into Burp without any errors.
Useful APIs
The first important thing to note about programming extensions for Burp is that, for the most part, the data you will be inspecting is provided in the form of byte arrays (
byte[]) which might take some getting used to if you'd normally program with strings. It's important to understand that while it is possible to convert from byte to a string, this process is not entirely trivial and may bloat the memory usage of your extension. In some cases this is unavoidable (e.g. you need to execute a regex against a request/response), but on the whole you should try to stick to working with bytes directly.
Burp will provide various data objects to you which model HTTP requests, responses, parameters, cookies, etc. as well as Burp-specific items such as issues. We will discuss a number of these models under the assumption that you are familiar with HTTP and with Burp as a tool.
Assuming a starting point of the blank extension you created above, because you've implemented the
IBurpExtender interface, the entry point for your extension will be the method:
Sidenote: as the Python and Ruby compatibility is provided via a translation layer to Java bytecode, we will talk about all interfaces in the strictest sense. To read them as Python or Ruby functions you can simply drop the types. e.g. in Python:
def registerExtenderCallbacks self, callbacks)
or in Ruby:
def registerExtenderCallbacks(callbacks)
Using the Java definitions allows us to be as precise as possible, and allows us to discuss the finer points of the translation layer where it's useful. In the interests of clarity some of the method names mentioned in this document have been qualified further with the name of the interface.
The first useful thing you can do with the callbacks object is to tell Burp what your extension is called:
This allows users to see a pretty name for your extension.
The first thing you're likely to do is to get a copy of the helpers to make your life easier:
The first tools to check out are your byte utilities:
String bytesToString(byte[] data);
byte[] stringToBytes(String data);
String urlDecode(String data);
String urlEncode(String data);
byte[] urlDecode(byte[] data);
byte[] urlEncode(byte[] data);
byte[] base64Decode(String data);
byte[] base64Decode(byte[] data);
String base64Encode(String data);
String base64Encode(byte[] data);
These allow you to convert between string and byte where required, and provide you with encodings useful for working with data on the web.
Burp's extender APIs return a few data types to you apart from byte, to model HTTP concepts in a convenient manner. Briefly, those are
IHttpRequestResponse which gives you access to the
IHttpService (i.e. the domain, port and protocol) and wraps up the request and response. The requests and responses can be further processed via the various overloads for
IExtensionHelpers.analyzeRequest() in order for you to inspect parameters, cookies, etc.
A core part of writing an extension is in telling Burp what your extension is capable of dealing with, and this works through a mechanism of registering bits of your code with Burp so that this code can be executed by Burp at a later point. We won't go through all of the functionality provided by the IExtenderCallbacks object; it's best that you browse the source to see what possible functionality Burp understands, but as an example you could register an object (maybe your current one
this (in Java) or
self (in Python/Ruby) via the following API:
e.g.
Now, in order to understand what it means to be an
IExtensionStateListener you should take a look at the source for that API which is pretty simple since there's only one method to implement:
So you can determine when your extension is unloaded by the user, Burp will inform you of this (if you registered!) in order for you to do some cleanup, like closing a database connection. This is commonly referred to as an "Event-driven architecture", and is common in scenarios where you know that certain events might happen but you don't know when exactly. The registration mechanism allows you to be selective in what you want to deal with, allowing you to focus your efforts.
Often you might want to save some state; maybe you've asked a user for configuration, or simply discovered something that you would like to use later on. The easiest way to do this is to use the following APIs:
String IBurpExtenderCallbacks.loadExtensionSetting(String name);
The reason these APIs exist and are useful is that they avoid the complication of managing files or databases ourselves. For simple saving and re-loading of data you should always prefer to use these mechanisms rather than introducing the headache of filesystems, permissions, and differences across operating systems.
Another API that helps you to avoid managing files is:
byte[] ITempFile.getBuffer();
This is useful in case you are dealing with large amounts of data and do not wish to bloat your memory usage. Note that
ITempFile.delete() is deprecated; temp files are removed automatically by Burp on shutdown.
A special note on dealing with Java arrays in Python & Ruby
As mentioned previously, Python and Ruby compatibility is achieved via a translation layer and this implementation detail leaks out on occasion. You will notice this mostly when dealing with Java arrays, and most often with bytes.
To create a byte-compatible object to pass to the Burp Extender APIs:
To convert an existing list to a Java array:
array([1, 2, 3], 'i') ># => new int[] {1, 2, 3}
Note the
'i' which corresponds to "integer". The various primitive type names can be found in the Jython documentation.
To create a byte-compatible object to pass to the Burp Extender APIs:
To convert an existing array to a Java array:
Note the
:int which corresponds to "integer". The various primitive type names can be found in the JRuby documentation.
More examples
Some of the Burp APIs have been highlighted in example extensions at the bottom of the official extensibility page, their source code contains comments that explain the code, providing a rich resource for learning the various available APIs in a practical setting.
Burp Community
For more help and examples of Burp extensions, you can refer to the Burp Extensions community discussions in the Support Center.Take a look | https://portswigger.net/burp/extender/writing-your-first-burp-suite-extension | CC-MAIN-2018-09 | refinedweb | 1,613 | 56.59 |
UPDATE: The comments left on this post (1 and 3) in particular corrected my misreading of PEP 3113. There is no such wart as I describe in Python 3.0. I should have known better than to question GvR and friends. :-) I'm leaving this post as a reference.
In trying to make Crunchy useful & interesting for beginning programmers to learn Python, I designed a small graphics library following some "natural" notation. As an aside, Johannes Woolard is the one who made sure that this library could be easily used interactively within Crunchy. I mention his name since too many people seem to assume that I am the only one involved in Crunchy's design. Anyway, back to the library...
In that library, the function used to draw a line between two points uses the syntax
line((x1, y1), (x2, y2))
for example: line((100, 100), (200, 200))
which should be familiar to everyone. Unfortunately, following the implementation of PEP 3113 in Python 3.0, this syntax is no longer allowed. This is ... annoying! There are two alternatives I can use:
line(x1, y1, x2, y2)
for example: line(100, 100, 200, 200)
or
line(point_1, point_2)
where point_a = (x_a, y_a). Update: with this second definition, it will be possible to invoke the function as
line((100, 100), (200, 200))
Of course, either of these two option is easy to implement (and is going to be backward compatible with Python 2k). However, I don't find either one of them particularly clear for beginners (who might be familiar with the normal mathematical notation) and do not consider this a (small) wart of Python 3k.
4 comments:
Only tuple unpacking in function arguments has been deprecated; you can of course still pass two tuples as arguments to a function. For example,
def line((x1, y1), (x2, y2)):
# ...
can be rewritten:
def line(p1, p2):
x1, y1 = p1
x2, y2 = p2
# ...
the user API does not change.
Alex:
I realize this - I gave that as the second alternative. However, it means that a user calling the line function would have to do
p1 = (100, 100)
p2 = (200, 200)
line(p1, p2)
which is not as "simple" as simply writing
line((100, 100), (200, 200))
I'm think you're mistaken:
>>> def line(p1, p2):
... x1, y1 = p1
... x2, y2 = p2
... print x1, y1, x2, y2
...
>>> line((100, 100), (200, 200))
100 100 200 200
>>>
In line with Alex, reading PEP3113 closely, under the "No Loss of Abilities If Removed" heading, states that you can still pass in tuples, they just can't be unpacked automatically. | https://aroberge.blogspot.com/2007/12/bitten-by-pep-3113.html | CC-MAIN-2017-47 | refinedweb | 433 | 70.94 |
Queues are an abstract data type, specifically designed to operate in a FIFO context (first-in-first-out). The elements are inserted into one end of the container and extracted from the other. They are a type of container adaptor in the C++ Standard Library. The
queue::size() is a method available in the STL which returns the number of elements in the queue
Syntax:
queue_name.size();
Parameters: The
queue::size() method does not accept any parameter
Return value: Number of elements in the queue
Example of queue::size() method
#include <iostream> #include <queue> using namespace std; int main () { queue<int> q1; for(int i = 1; i <= 5; i++) q1.push(i); cout<<"Size of queue: "<<q1.size(); return 0; }
Output:
Size of queue: 5 | https://prepfortech.in/documentation/cpp/queue-size-method | CC-MAIN-2021-17 | refinedweb | 125 | 63.7 |
Intrexx Share 3.1 - Chat
Contents
General
Create chat
Chat - Overview
Options
Administration
Additional control
1. General
You can chat with colleagues in real-time with Intrexx Chat. Intrexx Chat is an independent application that is included in the
import packet
of Intrexx Share and can be positioned freely in the
portal menu structure
. When you open Chat in the browser, you will still have access to the
Intrexx Share Navigation portlet
. The functions and appearance are identical whether you open Chat from within Intrexx Share or not. Click on "Start now and create your first chat".
2. Create chat
Chat title
Provide the chat with a title here.
Select recipients / Selected recipients
The "Select recipients" list contains all users who can be selected for the chat. The users must have a business email address in the
Users module
and in their
profile
. Move the desired users from the "Select recipients" list to the "Selected recipients" list via the
button.
Participants can add/remove other users
With this setting, the participants of the current chat can modify who receives the message.
Enter your chat message here.
File
You can upload one or more files as needed.
Send
Click on "Send" when you are ready to send the message.
3. Chat - Overview
The number of new, unread messages for you are shown in the
Navigation portlet
next to "Chat". In the
Chat - Overview
portlet, you have access to all chat functions provided you have the corresponding permission. Click on "New" to
create a new chat
.
3.1. Options
The
"Options" button is shown to the right of the "New" button. It opens a menu that displays the online status.
Online status
Click on "Change status" to set your online status. You can choose from the following statuses, which are represented by a small colored symbol at the bottom right of the profile picture thumbnail, in Intrexx Share:
Online
The current user is shown as online. Color: green
Offline
The current user is shown as offline. Color: gray
Travelling
This status shows that the current user is not in the office. Color: orange
Busy
This status shows that the current user is busy. Color: red
Not at desk
This status shows that the current user currently is not at their desk. Color: blue
Status (Portal/Session)
If the current user is logged in to the portal, their status is shown as "Online". If they are logged out, their status is shown as "offline". The online status symbol has the corresponding color.
If you move the mouse over the symbol in the user image, the online status will be shown in a quicktip as text.
Hidden chats
Opens a page where chats, which were hidden via the
"Administration" menu
, can be viewed.
Click on the chat text in the left area to refresh the right area and show the selected chat. The profile picture thumbnails of the users who are recipients of the chat are shown at the top of the right area. You can add your own message to the chat via the "Message" field at the bottom of the area. Click on
"Send" to send your message to the recipients. Click on
"Administration" to open the menu for the chat.
3.2. Administration
Edit
Opens a page where the list of participants for the current chat can be modified. In addition, you can decide whether participants can add more users to the chat.
Show/Hide chat
Hides the current chat. Once it is hidden, you can choose the show it again with this option by going to the
hidden chat area
.
Enable/Disable email notification
Turns email notifications for new messages in this chat on or off.
Show/Hide chat window
Enables or disables the chat window that is shown at the bottom right of the browser via the
additional control
.
Leave chat
You will no longer take part in the chat. Once all participants have left the chat, it will be deleted automatically.
4. Additional control
The
additional control "Share messages"
displays new chat messages at the bottom right of the browser window. Click on the notification at the bottom right to open the chat in a small window where you can immediately read and reply to the message. | https://onlinehelp.unitedplanet.com/intrexx/9400/en/helpfiles/help.2.intrexx-share-chat.html | CC-MAIN-2020-34 | refinedweb | 709 | 72.97 |
dird
On older SCO, you could print the contents of a directory file in hexadecimal format by the command "hd ." (current directory).
With SCO OpenServer you get only 0000.
That's not good :-)
Typically, the reason for doing this was to either to see the order of the files in the directory (so you could tell how far along a backup or restore was that you were watching on another screen) or to look for "holes" (so that you could rearrange the order of entries by judicious copying and deleting). Why would you want to do that? If you have to ask, you'll probably never want to, but in some situations involving large directories and ultra critical performance, it's worth moving frequently accessed files to the "top", (assuming the namei cache can't help you, perhaps because you need that boost on the *first* access).
Yet another reason was to spot garbage characters in file names.
If all you need is the order of file names in the slots, ls -f will do it. Otherwise, you can get some of the remaining functionality by a simple C program like this:
#include <dirent.h> #include <stdio.h> main() { DIR *dirp; char *c; long offset=0L; struct dirent *dp; dirp = opendir( "." ); while ( (dp = readdir( dirp )) != NULL ) { printf("Inode: %8lu Offset %4ld Length %4hd ", dp->d_ino,offset,dp->d_reclen); printf("%s ",dp->d_name); offset = dp->d_off; c=dp->d_name; while (*c) { printf("%x ",*c++); } printf("\n"); } closedir( dirp ); }
You can add to this to display other information, of course, but while it does show the order, it doesn't show holes. You can infer holes from the directory size and offsets, and you can create holes where you want them by removing or copying files, but it's certainly true that an hd on a directory was useful now and then.
Got something to add? Send me email.
(OLDER) <- More Stuff -> (NEWER) (NEWEST)
Printer Friendly Version
Increase ad revenue 50-250% with Ezoic
Inexpensive and informative Apple related e-books:
El Capitan: A Take Control Crash Course
Take Control of Pages
Take Control of Upgrading to Sierra
Take Control of iCloud, Fifth Edition
iOS 8: A Take Control Crash Course
More Articles by Tony Lawrence
Find me on Google+
© 2009-11-07 Tony Lawrence
Printer Friendly Version
dird- dumps SCO_OSR5 directories | http://aplawrence.com/Unix/dird.html | CC-MAIN-2017-22 | refinedweb | 390 | 65.25 |
Routing is a mechanism that Laravel uses to decide which method is to be executed when a request is made to a controller class. A large application could have lots of request-handling logic defined. Storing these in a single file could make the code hard to maintain.
It is usually better to keep the code for all of this logic organized by making use of Controller classes. These are stored in the App/Http/Controllers directory.
A default Laravel installation has a base controller that controls other controllers. So, all controllers should extend the default controller. The code below is an example of what a basic controller in Laravel might look like:
<?php namespace App\Http\Controllers; use App\User; use App\Http\Controllers\Controller; class ProfileController extends Controller { /** * Show the profile for the given user. * * @param int $id * @return Response */ public function displayProfile($id) { return view('user.profile', ['user' => User::findOrFail($id)]); } }
To route the controller action above, use the following line of code:
Route::get('user/{id}', 'ProfileController@displayProfile');
When a request is made and it matches the URI in the specified route, the displayProfile method of the ProfileController class will be executed. The route parameters will also be passed to the method.
Controllers In Laravel: Namespaces
In the code above, we did not need to specify the full controller namespace when defining the route of the controller. What we did was to define the portion of the class name that follows App/Http/Controllers.
If you decide to create your controllers in a sub-directory of App/Http/Controllers use a class name that is relative to that directory. You don’t have to use the absolute path of the controller.
So, if your controller class is stored at App\Http\Controllers\Photos\DahsboardController for example, the route should be registered like this:
Route::get('foo', 'Photos\DashboardController@method');
Single Action Controllers
Sometimes, you may want to create a controller that handles just a single action. To do this, place a single __invoke method in the controller like this:
<?php namespace App\Http\Controllers; use App\User; use App\Http\Controllers\Controller; class DisplayProfile extends Controller { /** * Show the profile for the specified user * * @param int $id * @return Response */ public function __invoke($id) { return view('user.profile', ['user' => User::findOrFail($id)]); } }
When registering routes for single action controllers, you do not need to specify the method you want to work with. Here’s an example:
Route::get('user/{id}', DisplayProfile');
That’s it.
This is a primer on controllers in Laravel. I’ll gladly entertain questions on this topic if you have any. You can leave your comments and questions using the comments box below.
If you desire even more details, check out the official Laravel controllers documentation. | https://ehikioya.com/controllers-in-laravel-an-introduction/ | CC-MAIN-2022-27 | refinedweb | 461 | 54.73 |
I had not seen that before, and was wondering why one would do such a thing. It seems to be unintuitive. I found my answer through... GWT widgets. In this page, the author explain motivations behind doing such a thing:
While not 100% in tune with the MVC pattern, it is often convenient to access the servlet
container, the HTTP session or the current HTTP request from the business layer. The GWT-SL
provides several strategies to achieve this which pose a compromise in the amount of configuration
required to set up and the class dependencies introduced to the business code.
The easiest way to obtain the current HTTP request is by using the
ServletUtilsclass
which provides convenience methods for accessing the
HttpServletRequestand
HttpServletResponseinstances. Please note that it makes use of thread local variables
and will obviously not return correct values if used in any other than the invoking thread.
Still one can doubt if this is good design. In my long experience of web apps in Java I never had the need to do such a thing. Have you seen that pattern before?
Just look at the original com.google.gwt.user.server.rpc.RemoteServiceServlet class that has both #getThreadLocalRequest and #getThreadLocalResponse methods.
ThreadLocals provide convenient means for making context information available during request processing (especially when unsure when and where it might be needed). The alternative would be introducing extra parameters to all of your methods.
App servers use it. JTA probably does. I've used it myself to store the equivalent of JDBC connections in applications. It can be a useful technique for thread-confinement,; it is explained in a bit more detail in Java Concurrency in Practice, which is great book about a very complex subject.
It's actually a pretty standard practice. Some packages such as Apache Axis can hold both the request and response in the MessageContext.
Anytime you see a "context" object like that it's often just a class holding a
public class SomeContext
{
private static ThreadLocal<SomeContext> curr =
new ThreadLocal<SomeContext>();
private HttpServletRequest req;
private HttpServletResponse resp;
private SomeOtherData data;
private SomeContext() {};
public static SomeContext getCurr()
{
return curr.get();
}
public static loadContext(
HttpServletRequest request,
HttpServletResponse response,
SomeData some)
{
SomeContext current = new SomeContext();
current.req = req;
current.resp = response;
current.data = some;
curr.set(current);
}
}
for example...
james: Java Concurrency In Practice is an excellent book, the best imho on java concurrency. Here what I found surprising is the specific case of ServletRequest put in the ThreadLocal not in the general use of the ThreadLocal.
I know ThreadLocal is used here and there. One of the best use I have seen is in Hibernate, to maintain the session.
Thanks to the other comments I have learnt ServletRequest in ThreadLocal is more widely used that first thought: GWT, Axis!
To me it still feel a bit like Singleton, just making a global variable, which is generally a bad pattern but has its uses sometimes.
I don't see it like a Singleton. Both this approach, and Singleton for that matter, are good for what they are good for. Some things.
This approach does have its down sides. Of course it depends on a single thread serving a 'request'. I there is something asynchronous, it breaks down.
Little late to the picnic :)
Does ThreadLocal still work in an asynchronous web server which may only have a few threads and use selectors to process requests? The reason I ask is I see more async modes avail for most app servers now. But I still see a lot of libraries using ThreadLocal. | http://chasethedevil.blogspot.com/2007/08/original-pattern-servletrequest-in.html | CC-MAIN-2017-22 | refinedweb | 596 | 56.86 |
This post is the third
Assuming the dataset is named “people_wiki.csv”, place the below code in another .py file (let’s say indexing.py) in the same folder as the data.
import pandas as pd import numpy as np import json import time from elasticsearch import Elasticsearch start_time = time.time() es = Elasticsearch([{'host': 'localhost', 'port': 9200}]) start_time = time.time() data = pd.read_csv('people_wiki.csv') print 'Data prepared in ' + str((time.time()-start_time)/60) + ' minutes' json_body = data.reset_index().to_json(orient='index') json_body = json_body.decode('ascii','ignore').encode('utf-8','replace') json_parsed = json.loads(json_body) print np.shape(data) for elements in json_parsed: data_json = json_parsed[elements] id_ = data_json['URI'] es.index(index='wiki_search', doc_type='data', id=id_, body=data_json) print id_ + ' indexed successfully' print 'Indexed in '+str((time.time()-start_time)/60)+' minutes'
Executing this script will result in steaming logs which is ultimately leading to the data getting indexed in elasticsearch. That’s how easy it is!
Let’s spend the next few lines on what actually happened.
We declare our elasticsearch object configured on our local machine. Once that object is initialized we will use it to index all of our data.
Pandas is a python library for loading datasets in python and it works great. We use the read_csv() to load our data. Once that is done we have to convert it to a JSON format to send it to elasticsearch for indexing. We do this conversion by using the json library that is shipped with the anaconda distribution.
Every person on our data will be treated as a separate document. We are specifying the URI as the id of the documents as we can be sure that URI will always be unique for a document.
Once all this is in place, we can go ahead and call es.index() with the specified parameters to start indexing our documents iteratively.
Indexing in elasticsearch is the process that it goes through to understand the data beforehand. It will parse the free text, do all the pre-processing already discussed in Part 2 and store the data in shards to achieve blazing fast speed in query time.
Once this script has completed running, the elasticsearch module will be completely ready. From hereon we are done with building the search engine. We just have to build a frontend using AngularJS and all the awesomeness of elastisearch will be accessible through it.
In the next parts we will concentrate on building the front end and we will be done with how to build a search engine – our fuzzy and blazing fast. | https://machinelearningblogs.com/2016/12/26/how-to-build-a-search-engine-part-3/ | CC-MAIN-2018-47 | refinedweb | 428 | 59.7 |
view raw
We are using custom fonts in our project. It works well in Xcode 5. In Xcode 6, it works in plain text, attributed string in code. But those attributed strings set in storyboard all revert to Helvetica when running on simulator or device, although they look all right in storyboard.
I'm not sure if it's a bug of Xcode 6 or iOS 8 SDK, or the way to use custom fonts is changed in Xcode 6 / iOS 8?
The fix for me was to use an
IBDesignable class:
import UIKit @IBDesignable class TIFAttributedLabel: UILabel { @IBInspectable var fontSize: CGFloat = 13.0 @IBInspectable var fontFamily: String = "DIN Light" override func awakeFromNib() { var attrString = NSMutableAttributedString(attributedString: self.attributedText) attrString.addAttribute(NSFontAttributeName, value: UIFont(name: self.fontFamily, size: self.fontSize)!, range: NSMakeRange(0, attrString.length)) self.attributedText = attrString } }
Giving you this in the Interface Builder:
You can set up your attributedstring just as you normal do, but you'll have to set your fontsize and fontfamily once again in the new available properties.
As the Interface Builder is working with the custom font by default, this results in a what you see is what you get, which I prefer when building apps.
Note
The reason I'm using this instead of just the plain version is that I'm setting properties on the attributed label like the linespacing, which are not available when using the plain style. | https://codedump.io/share/hFYm2CleqlVz/1/attributed-string-with-custom-fonts-in-storyboard-does-not-load-correctly | CC-MAIN-2017-22 | refinedweb | 237 | 62.68 |
The screensaver is an example of a vestigial technology - it no longer serves its original purpose. However, this doesn't mean it isn't useful in other ways and it is supported on all versions of Windows including Windows 10..
It’s always helpful to examine the simplest example of a project type so that you can really see how things work. Although screensavers seem complicated they are just standard .EXE files with their file names changed to end in .SCR. They also live in either the Windows/System or Windows/System32 directory.
If you select a screensaver then
/p
Show a preview of your screensaver
(None)
Show the configuration dialog box with no parent window.
The good news is that you really only need to support the /s option to create the simplest possible screensaver.
Start a new C#(); break; case "/p": //preview break; } } else { ShowScreenSaver(); }}. Use the command Project,Add Windows Form. a reference to System.Windows.Forms if there isn't already one in the project. Use the Project,Add Reference command. You also need to add:
using System.Windows.Forms;
to the start of the file continuing the main function.
Now we are ready.
To make the screensaver work under Windows 10 you also need to change the Target Framework to 4.
Next we need to install the screensaver. To do this you have to navigate to the project’s debug directory, find ScreenSaver1.exe and rename it to ScreenSaver1.scr.
Next you can either copy it to the Windows/System32 directory or you can also.
<ASIN:0672329905>
<ASIN:0596527578>
<ASIN:1590599543>
<ASIN:1590598849>
<ASIN:0321485890>
<ASIN:1933988363> | http://i-programmer.info/projects/38-windows/350-useful-screensavers.html | CC-MAIN-2016-26 | refinedweb | 272 | 68.36 |
Apache HTTP Server Request Library
#include "apreq_param.h"
Go to the source code of this file.
Value:
Value:
Value:
apreq_hook_t *hook, \ apreq_param_t *param, \ apr_bucket_brigade *bb
Value:
apreq_parser_t *parser, \ apr_table_t *t, \ apr_bucket_brigade *bb
The callback function of a hook. See apreq_hook_t.
A hook is called by the parser whenever data arrives in a file upload parameter of the request body. You may associate any number of hooks with a parser instance with apreq_parser_add_hook().
The callback function implementing a request body parser.
A request body parser instance.
Special purpose utility for locating a parameter during parsing. The hook's ctx shoud be initialized to an apreq_hook_find_param_ctx_t *, with the name attribute set to the sought parameter name, the param attribute set to NULL, and the prev attribute set to the address of the previous hook. The param attribute will be reassigned to the first param found, and once that happens this hook is immediately removed from the chain.
Calls apr_brigade_cleanup on the incoming brigade after passing the brigade to any subsequent hooks.
Returns APREQ_ERROR_GENERAL. Effectively disables mfd parser if a file-upload field is present.
apr_xml_parser hook. It will parse until EOS appears. The parsed document isn't available until parsing has completed successfully. The hook's ctx pointer may be cast as (apr_xml_doc **) to retrieve the parsed document.
Generic parser. No table entries will be added to the req->body table by this parser. The parser creates a dummy apreq_param_t to pass to any configured hooks. If no hooks are configured, the dummy param's bb slot will contain a copy of the request body. It can be retrieved by casting the parser's ctx pointer to (apreq_param_t **).
RFC 2388 multipart/form-data (and XForms 1.0 multipart/related) parser. It will reject any buckets representing preamble and postamble text (this is normal behavior, not an error condition). See apreq_parser_run() for more info on rejected data.
RFC 2396 application/x-www-form-urlencoded parser.
RFC 822 Header parser. It will reject all data after the first CRLF CRLF sequence (an empty line). See apreq_parser_run() for more info on rejected data.
Construct a hook.
Run the hook with the current parameter and the incoming bucket brigade. The hook may modify the brigade if necessary. Once all hooks have completed, the contents of the brigade will be added to the parameter's bb attribute.
Fetch the default parser function associated with the given MIME type.
Add a new hook to the end of the parser's hook list.
Construct a parser.
Parse the incoming brigade into a table. Parsers normally consume all the buckets of the brigade during parsing. However parsers may leave "rejected" data in the brigade, even during a successful parse, so callers may need to clean up the brigade themselves (in particular, rejected buckets should not be passed back to the parser again).
Register a new parsing function with a MIME enctype. Registered parsers are added to apreq_parser()'s internal lookup table. | http://httpd.apache.org/apreq/docs/libapreq2/apreq__parser_8h.html | CC-MAIN-2016-36 | refinedweb | 491 | 59.19 |
So polymorphism is the act of inheriting a class and overriding methods from it/adding to it, so making a class based on another. And as polymorphism means many forms, we call this polymorphism...
Type: Posts; User: TP-Oreilly
So polymorphism is the act of inheriting a class and overriding methods from it/adding to it, so making a class based on another. And as polymorphism means many forms, we call this polymorphism...
Hi,
Im just trying to get the right idea about polymorphism.
Is polymorphism simply the act of inheriting an abstract class and defining the methods yourself. As polymorphism means many forms,...
Thanks. :)
Hi, in my code I have
public boolean equals(Object obj) {
if (this.equals(obj)){
return true;
}
return false;
}
I found out why....
The format of the sound file was .wav, i changed it to a .mp3 and now it sounds as it should.
Hi,
I have:
final MediaPlayer mp = MediaPlayer.create(this, R.raw.popping_sound_effect);
When I play the sound file it is how I want it to be, but when I run the app and making the...
I got it working now, just to let you know why it wasnt working:
I changed this:
public class BackgroundService extends Service{
@Override
public IBinder onBind(Intent intent) {
Ive created a service which plays the audio, but still when i change the layout on the activity the audio stops?
I cant because I have set it so that when I click on a button the this is called: setContentView(R.layout.menu_screen);
I tried making a different activity for the menu_screen.xml layout but when...
Hi,
Why does my MediaPlayer stop when I change the layout?
MediaPlayer mp = MediaPlayer.create(this, R.raw.background_song);
mp.setLooping(true);
mp.start();
To answer my own question............ What I'm actually doing is setting the content of the tab as an Activity???
This is what made me think that each activity is a different window:
"An activity is the equivalent of a Frame/Window in GUI toolkits. It takes up the entire drawable area of the screen"
I do have an understanding of Java. It's concept of an Activity which is confusing me. Reading different things on the internet have made me confused.
Hello, I'm trying to understand what exactly is happening in my code. Thanks in advance for replying, I'm pretty confused and need some help. I have read many things on the internet but i havnt found...
Thank you very much for your detailed reply.
I ask this because I havnt actually created an instance of my class so how can I be referring to an INSTANCE of my HelloAndroidActivity class?
Thanks for the reply. I also have another question, and as it is regarding this code I thought I'd ask it in this thread.
I know that the constructor of the TextView class requires a Context...
Hello, I following a "Hello World" tutorial for android development and I want to understand how the code works exactly, instead of just using it without understanding it, heres the code:
...
Thank you :)
Got it, thank you :)
Thank you very much for your detailed reply, much appreciated.
So, when i create an instance of my class which has extended JFrame, both my class constructor and the JFrame constructor is called...
I would understand how it all works if our class also inherits JFrame's constructor, if not then I can not see how creating an instance of our class creates a window.
Hi, I know when we extend a class our class gets all of the properties of the class we extend.
I am abit confused. I have read that when our class extends the JFrame class, our class then IS the...
Ah thank you, ive now got it to compile but it doesnt work.
I have to defined all of the methods of the KeyListener interface. I have removed the "if (keyCode == KeyEvent.VK_ESCAPE){" and just put...
This is my code, it is only small:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class MoveIcon implements KeyListener{ | http://www.javaprogrammingforums.com/search.php?s=f5c85cf983715e2ae34b46e7edc4410b&searchid=1929959 | CC-MAIN-2015-48 | refinedweb | 684 | 74.39 |
Blog Map
[Blog Map] [Table of Contents] [Next Topic]
Yield Return is a means to more elegantly implement the plumbing for iteration. Yield was introduced in C# 2.0, but my informal polling indicates that many developers don't yet understand it. It's not hard, but it deserves some explanation.
This blog is inactive.New blog: EricWhite.com/blogBlog TOCUse of this construct is vital for LINQ. Yield return allows one enumerable function to be implemented in terms of another. It allows us to write functions that return collections that exhibit lazy behavior. This allows LINQ and LINQ to XML to delay execution of queries until the latest possible moment. it allows queries to be implemented in such a way that LINQ and LINQ to XML do not need to assemble massive intermediate results of queries. Without the avoidance of intermediate results of queries, the system would rapidly become unwieldy and unworkable.
The following two small programs demonstrate the difference in implementing a collection via the IEnumerable interface, and using yield return in an iterator block.
With this first example, you can see that there is a lot of plumbing that you have to write. You have to implement a class that derives from IEnumerable, and another class that derives from IEnumerator. The GetEnumerator() method in MyListOfStrings returns an instance of the class that derives from IEnumerator. But the end result is that you can iterate through the collection using foreach.
public class MyListOfStrings : IEnumerable{ private string[] _strings; public MyListOfStrings(string[] sArray) { _strings = new string[sArray.Length]; for (int i = 0; i < sArray.Length; i++) { _strings[i] = sArray[i]; } } public IEnumerator GetEnumerator() { return new StringEnum(_strings); }} public class StringEnum : IEnumerator{ public string[] _strings; // Enumerators are positioned before the first element // until the first MoveNext() call. int position = -1; public StringEnum(string[] list) { _strings = list; } public bool MoveNext() { position++; return (position < _strings.Length); } public void Reset() { position = -1; } public object Current { get { try { Console.WriteLine("about to return {0}", _strings[position]); return _strings[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } }} class Program{ static void Main(string[] args) { string[] sa = new[] { "aaa", "bbb", "ccc" }; MyListOfStrings p = new MyListOfStrings(sa); foreach (string s in p) Console.WriteLine(s); }}
Using the yield return keywords, the equivalent in functionality is as follows. This code is attached to this page:
class Program{ public static IEnumerable<string> MyListOfStrings(string[] sa) { foreach (var s in sa) { Console.WriteLine("about to yield return"); yield return s; } } static void Main(string[] args) { string[] sa = new[] { "aaa", "bbb", "ccc" }; foreach (string s in MyListOfStrings(sa)) Console.WriteLine(s); }}
As you can see, this is significantly easier.
This isn't as magic as it looks. When you use the yield contextual keyword, what happens is that the compiler automatically generates an enumerator class that keeps the current state of the iteration. This class has four potential states: before, running, suspended, and after. This class has Reset and MoveNext methods, and a Current property. When you iterate through a collection that is implemented using yield return, you are moving from item to item in the enumerator using the MoveNext method. The implementation of iterator blocks is fairly involved. A technical discussion of iterator blocks can be found in the C# specifications.
Yield return is very important when implementing our own query operators (which we will want to do sometimes).
There is no counterpart to the yield keyword in Visual Basic 9.0, so if you are implementing a query operator in Visual Basic 9.0, you must use the approach where you implement IEnumerable and IEnumerator.
One of the important design philosophies about the LINQ and LINQ to XML technologies is that they should not break existing programs. Adding new keywords will break existing programs if the programs happen to use the keyword in a context that would be invalid. Therefore, some keywords are added to the language as contextual keywords. This means that when the keyword is encountered at specific places in the program, it is interpreted as a keyword, whereas when the keyword is encountered elsewhere, it may be interpreted as an identifier. Yield is one of these keywords. When it is encountered before a return or break keyword, it is interpreted by the compiler as appropriate, and the new semantics are applied. If the program was written in C# 1.0 or 1.1, and it contained an identifier named yield, then the identifier continues to be parsed correctly by the compiler, and the program is not made invalid by the language extensions.
Maybe I'm missing something but I can do this with out the yield keyword or any other ienumerable code.
For instance, the following code interates, using a foreach, over an arbitrary class named banana.
I am using visual studio express 2008.
banana [] b = new banana[3];
b[0] = new banana(true);
b[1] = new banana(false);
b[2] = new banana(true);
foreach(banana h in b)
Console.WriteLine(h.isPeeled.ToString());
Brian, yield return is the means by which you create iterators. You can certainly write the code in an imperative style, but the point is, a declarative, FP style is faster to write and easier to maintain. But to write such code, you have to understand iterators, and moreover, how to write a function that is an iterator.
Uhm, in your last code example ("Using the yield return keywords, the equivalent in functionality is") there is one line of code that seems obsolete to me:
string[] _sa = sa;
Why are you storing the parameter? You don't use it in the yield block. Does this happen for some magic reason I don't understand?
Sam, you are correct, that line is not required. It's been some time since I wrote this code, but I think that it was code left there inadvertently. I removed it.
In the paragraph that starts with "This isn't as magic as it looks.", you state that the yield creates a new class that contains the Reset and MoveNext methods and a Current property. This is correct in the sense that the Reset method will throw an exception when called on an enumerator created by the compiler through the yield syntax.
I just though I'd mention this.
Regards,
Meile
Closures are one of the key components in C# 3.0 that makes functional programming easy, and results | http://blogs.msdn.com/b/ericwhite/archive/2006/10/04/the-yield-contextual-keyword.aspx | CC-MAIN-2014-42 | refinedweb | 1,059 | 56.05 |
I'm using this program in C++ to calculate wind chill:
I have two problems:I have two problems:Code:#include <cstdlib> #include <iostream> #include <math.h> using namespace std; int main(int argc, char *argv[]) { cout << "Wind Chill Calculator...\n" ; cout << "By William Seed\n" ; int temp, vel; int ch; cout << "Enter the temperature:"; cin >> temp; cout << "Enter the wind speed:"; cin >> vel; ch = 35.75 + (.6215 * temp) - (35.75 * pow(vel,.16)) + (.4275 * temp * pow(vel,.16)); cout << "The wind chill is: "; cout << ch; cout << "\n"; system("PAUSE"); return EXIT_SUCCESS; }
1. (most important) I want this program to keep running until I tell it to stop (using imput as yes or no.
2. If I try to use a decimal for 'temp', then the program ends...
I'm new, so no flaming, please.
Thanks in advance,
Will | http://cboard.cprogramming.com/cplusplus-programming/98794-keep-running-program-%27int%27-problem.html | CC-MAIN-2013-48 | refinedweb | 139 | 84.37 |
Recursion is a powerful tool in your coding toolbox. Understanding it is a key skill on your path to mastery. This article gives you a thorough introduction to this important computer science concept.
What is Recursion?
Stephen Hawking used a concise explanation: “to understand recursion, one must first understand recursion.”
Recursion is a popular computer science concept where a problem is solved using a recursive function.
You create a recursive function f in four steps:
- Break the original problem into smaller problem instances,
- Take the smaller problem instances as the input of function f (which will then break the smaller input into even smaller problem instances and so on),
- Define a “base case” which is the smallest possible input that can be solved directly without any further call of the function f, and
- Specify how you can recombine the obtained smaller solutions into the larger solution.
What’s a Simple Example for Recursion?
Consider the factorial function that calculates the product of all numbers up to number n:
f(5) = 5 * 4 * 3 * 2 * 1 = 120 f(4) = 4 * 3 * 2 * 1 = 24 f(3) = 3 * 2 * 1 = 6
The following example shows that the factorial can be defined by using itself on a smaller problem instance. In other words, we define the factorial function recursively!
The recursive definition of the factorial function showcases an important element of recursion: every recursive function definition must specify
- how the recursion base case is defined, and
- how to obtain the solution to a bigger problem from the smaller problem.
This definition shows that the base case of the factorial function appears for n=1. The factorial of 1 is 1: there’s no need to proceed with the recursion.
You can also see that the problem is made easier in each call of the recursive function. Using the solution to the easier case (the factorial of n-1), we can directly obtain the solution of the harder case (the factorial of n) by multiplying the easier solution with n.
Here’s how the recursive factorial looks like in Python code:
def factorial(n): if n<2: return 1 else: return n * factorial(n-1) for i in range(10): print(factorial(i)) """ Output: 1 1 2 6 24 120 720 5040 40320 362880 """
Say, you have already found a solution to the factorial of n-1. Now, it’s easy to find the factorial of n by just multiplying n with the factorial of n-1. To prevent the recursion from proceeding forever, we define the base case for n<2.
What is Mutual Recursion?
Mutual recursion arises if function a() calls function b() — and function b() calls function a() to find a solution.
In other words, functions a() and b() are interdependent.
Here’s an example:
def ping(i): if i>0: return pong(i-1) return "0" def pong(i): if i>0: return ping(i-1) return "1" print(ping(29))
Puzzle: What’s the output of this code snippet?
This puzzle gives an example for mutual recursion: function ping calls function pong which calls function ping. Each function call solves a slightly easier problem.
In recursive problem solving, a function knows the result for some base cases (i.e., the naive solutions). It breaks a complex problem into a combination of less complex subproblems. As the subproblems are getting easier, they finally reach the base cases.
These are the least complex subproblems and we know their solutions. The idea is to build the solution of the complex problem from the solutions of the subproblems.
So when you call ping(29), the ping function reduces this question to pong(28) – an easier problem. The calling function ping waits for pong to return a solution. But pong asks back ping(27) and waits for a solution. On a higher level, ping receives odd and pong even argument values for the initial input i=29. Thus, the last call is pong(0), which returns 1. Each calling function is waiting for the result of the called function. Each calling function receives the value 1 and returns it to its parent calling function. Finally, the top-most functional instance ping(29) returns the value 1 as the final result.
Where to Go From Here?
The article has given you a concise introduction into recursion (and mutual recursion) using simple examples.
The examples are taken from my book “Coffee Break Python” which teaches you all important concepts and features you need to know to get started with Python.
| https://blog.finxter.com/recursion/ | CC-MAIN-2020-10 | refinedweb | 754 | 53.81 |
Allen Huang wrote:
Advertising
I made a login_form that allows user to input username and password and sends them to a login dtml method that checks username and password with a zobject that contain this attributes and redirect the users to a status sheet. How do I keep the username in the namespace so I can use it again in the status page.
I have also tried using acl_users.getUser(REQUEST.username).authenticate(REQUEST.password, RESPOND). Even though I have the right username and password zope will pop up a query box asking me the input the username and password again for three times as if I input the wrong thing. At the end zope tells me that I am not autherized to use autenticate() method and denied me access.
Can some on help me with these two problem please...
Hi Allen, this mailinglist is for zope.org (website) related issues.
zope@zope.org is the right place to ask. ( archives and registration at )
Michael
--
_______________________________________________ Zope-web maillist - Zope-web@zope.org | https://www.mail-archive.com/zope-web@zope.org/msg00008.html | CC-MAIN-2017-51 | refinedweb | 173 | 72.16 |
In this codelab you will manage how users access data on the frontend of a web app by controlling user roles from a managed server-side environment. In practice, this could be any secure environment you control that the client cannot directly access, such as Google Cloud Functions or App Engine. In this example, your computer will play the role of a managed environment. You will be running the code locally. You will learn how to:
Before starting this codelab make sure you have installed:
In this section, you will download the project code and dependencies required to set up the FireFlicks web app.
Begin by cloning the sample project:
git clone
Before taking a look at the server-side code, let's set up the FireFlicks web app. This app lists movies and allows users to review them. Moderators are able to add new movies, which is where the server-side code comes in. You'll see that later on in the codelab.
Change to the directory of the web app, and then run
npm install:
cd fireflicks/web_app npm install
Installing the Node packages may take a while.
Take a look at what's inside this project.
ls
You'll see the following folders and files:
firebase.json firestore.indexes.json firestore.rules index.html manifest.webmanifest node_modules package-lock.json package.json src tsconfig.json webpack.config.js yarn.lock
The
firebase.json file contains information about different Firebase features the app is using. The
firestore.rules dictates rules for accessing Cloud Firestore from the web app. You'll be deploying those rules shortly. The
firestore-indexes.json contains indexes for sorting data in Cloud Firestore. The files
package.json,
package-lock.json,
manifest.webmanifest,
webpack.config.js,
tsconfig.json, and
yarn.lock all configure the appearance, behavior, and dependencies of the app. If you're a web developer, you're probably already familiar with these files. If not, don't worry about it! The directions will walk you through setup.
If you open
index.html in Chrome, you'll notice the app doesn't look like much. In fact, it's a blank screen! There's still more setup to complete before the app is ready.
In the Firebase console click on Add Project and call it FireFlicks.
Click Create Project.
To let users sign in on the web app you'll use Google auth, which needs to be enabled.
In the Firebase Console open the Authentication section > SIGN-IN METHOD tab (click here to go there) you need to enable the Google Sign-in Provider and click SAVE. This will allow users to sign in to the Web app with their Google accounts
You'll also be using anonymous auth, so this needs to be enabled as well.
In the Firebase Console open the Authentication section > SIGN IN METHOD tab (click here to go there) you need to enable the Anonymous Sign-in Provider and click SAVE. This allows users to sign in the Web app anonymously, allowing you to secure data to authenticated users without requiring a prompt to sign in right away.
The app uses Cloud Firestore to store data about movies. To enable Cloud Firestore on your Firebase project visit the Database section (click here to go there) and click the Create Database button on the Cloud Firestore window.
Then Click Enable on the popup about security rules. This enables the database in locked mode, which means the data is not yet accessible from the client.
Now you're going to download your project's
ServiceAccountKey.json file from Firebase console and drag it to the
fireflicks folder. To access the Service Account Key, go to Project Settings > Service Accounts (click here to go there) and select "GENERATE NEW KEY".
Once the Service Account Key is downloaded, drag it into the
fireflicks folder. The file has a long name, like
fireflicks-4f400-...fidksf.json. Rename this file to exactly
serviceAccountKey.json because this is what the project is looking for.
The Service Account Key is used to initialize the Admin SDK.
The Firebase Command Line Interface (CLI) allows you to serve the web app locally and deploy your web app.
To install or upgrade the CLI run the following npm command:
npm -g install firebase-tools
To verify that the CLI has been installed correctly, open a console
Make sure you are in the
web_app directory then set up the Firebase CLI to use your Firebase Project:
firebase use --add
Then select your Project ID and follow the instructions. When prompted, you can choose any Alias, such as
codelab for instance.
Earlier, you enabled Cloud Firestore in locked mode. This means that if you were to run the web app now, no data would be accessible from the app even if the user is authenticated. Rules can be updated from the Firebase Console or the CLI. The project includes Cloud Firestore rules in a file called
firestore.rules. Deploy these to your Firebase project using the command
firebase deploy --only firestore
Once the rules deploy, the web app is configured to run. Run it locally with this command:
npm run dev
To view the app, open Chrome and navigate to
You'll see something like this:
The app doesn't display any movies yet. Next, you'll set up the server code, which will also populate the view with some movies.
But first, use the "Log In" button on the right of the toolbar to sign in using your Gmail account. In order to apply custom claims to your user, the user account must already exist in the Firebase project. Signing in now creates a new Firebase user with your email.
You will run a Node.js Express server which handles setting custom claims on user accounts. Server code is located in the
backend/admin-service directory of the Git repo. Start by opening a new terminal window and installing the required dependencies:
cd backend/admin-service npm install
Next, build the server app.
npm run build
FireFlicks uses Cloud Firestore as its database. Run the following command to populate the database with some sample data. This creates two new collections named "movies" and "ratings" in your Firestore database.
npm run upload-data
Now we are ready to start the Express server. Following command starts a web server that listens on port 3000.
npm run serve
The server implementation uses the Firebase Admin SDK for Node.js (i.e. firebase-admin package). The Admin SDK gets initialized with the service account key you obtained earlier. Here's the relevant code fragment from the app.ts file:
import * as admin from 'firebase-admin'; const serviceAccount = require('../../../serviceAccountKey.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), });
The web server exposes following endpoints:
Try calling the GET endpoint using curl or a web browser. You should get a 401 Unauthorized response.
curl -v > GET /movies/test HTTP/1.1 > Host: localhost:3000 > User-Agent: curl/7.53.1 > Accept: */* > < HTTP/1.1 401 Unauthorized < X-Powered-By: Express < Content-Type: application/json; charset=utf-8 < Content-Length: 36 < ETag: W/"24-mZDp0pnuUM+7C5nI03U41Hl4kOA" < Date: Mon, 11 Jun 2018 21:46:17 GMT < Connection: keep-alive < {"message":"ID token not specified"}
It seems the server is looking for an ID token value on the request. Try sending some random string as the ID token. You should still get a 401 response, but this time with a different error message.
curl -v -H "X-Firebase-ID-Token: random-value" > GET /movies/test HTTP/1.1 > Host: localhost:3000 > User-Agent: curl/7.53.1 > Accept: */* > X-Firebase-ID-Token: random-value > < HTTP/1.1 401 Unauthorized < X-Powered-By: Express < Content-Type: application/json; charset=utf-8 < Content-Length: 265 < ETag: W/"109-2Zi+hNzS1hAeN/IcOBoqIY1jbSc" < Date: Mon, 11 Jun 2018 21:54:27 GMT < Connection: keep-alive < {"message":"Request not authorized","details":"Decoding Firebase ID token failed. Make sure you passed the entire string JWT which represents an ID token. See for details on how to retrieve an ID token."}
As you can see our server implementation authorizes incoming requests based on the ID token provided. Each request must contain a valid Firebase ID token. This prevents unauthorized users from tampering with user roles and the movie database. Here's the relevant bit of server code from the
app.ts file:
const idToken = req.header('X-Firebase-ID-Token'); if (!idToken) { return next(new HttpError('ID token not specified', 401)); } try { await fireflicks.checkAuth(idToken); } catch (err) { return next(new HttpError('Request not authorized', 401, err)); }
The
checkAuth() method is implemented as follows. You can find it in the
fireflicks.ts file. Notice how it uses the Admin SDK to verify ID tokens, and assert required claims.
export async function checkAuth(idToken: string): Promise<void> { const decoded = await admin.auth().verifyIdToken(idToken); if (decoded.moderator !== true) { throw new Error('User does not have moderator privileges'); } }
Note that this implementation also requires the caller of the service to be a moderator of the FireFlicks app. This is enforced by checking whether the "moderator" claim is present on the caller's decoded ID token. Therefore in order to test this service further, we need a user account with the moderator role. Open a new terminal window and navigate to
admin-service
cd backend/admin-service
You should now have three terminal windows: one running the web app locally, one running the server locally, and one for the next command you're going to run. Run the following command with the email address you use to login to FireFlicks. This promotes your user account to moderator status by setting the required claim:
npm run promote -- your@email.address
Here's the relevant code that sets the moderator claim on the user account:
export async function grantModeratorRole(email: string): Promise<void> { const user = await admin.auth().getUserByEmail(email); if (user.customClaims && (user.customClaims as any).admin === true) { return; } return admin.auth().setCustomUserClaims(user.uid, { moderator: true, }); }
Methods like
setCustomUserClaims() are only available in the Firebase Admin SDK, and require elevated privileges in a Firebase project to invoke. In this demo, you gain the necessary authorization from the service account credentials used to initialize the Admin SDK. You cannot execute such operations in a client-side environment due to the security implications.
Next you will invoke the Node.js Express back-end service through the FireFlicks web app. The web app authenticates users with Firebase Auth, and therefore can provision a valid Firebase ID token required to call the service. Thanks to the promote step earlier, the ID token issued to you is guaranteed to contain the required moderator claim.
Navigate to the
web_app folder of the project. It may be easiest to open this app in an IDE that lets you view the whole project, such as VSCode. This allows you to easily navigate the different project components.
Navigate to
src/components/ModAddMovie and open
index.ts.
Notice that there is a base_url variable, which is. This is the same port where you were testing requests earlier. If your server code was live,
base_url would be equal to your server endpoint.
export default class ModAddMovie extends Vue { base_url = ""; //... }
FireFlicks creates a new movie in the database by running the
onPublishMovie() function. Right now the body is just a list of TODOs. Replace the body of the function with the code below:
async onPublishMovie() { // if fields aren't correct, exit function if (!this.verifyFields()) { return; } const movie = await this.getMovie(); const token = await this.fst.auth.currentUser.getIdToken(); const result = await this.postData(`${this.base_url}movies`, movie, token); if (result) { alert("New Movie Created!"); this.movie_title = ""; this.movie_description = ""; this.image_url = ""; } }
The function first verifies that all required movie fields are filled out. It then creates a JSON object that contains the information about the movie. This data is passed to the
postData function, along with the ID token of the current user. The string version of the url passed to
postData is
`${this.base_url}movies`, which is
"
".
Below is the function
postData(). Right now your version just has a couple of TODOs. Replace the body of the function with the code below:
async postData(url: string, data: {}, token: string) { return fetch(url, { body: JSON.stringify(data), credentials: "same-origin", headers: { "X-Firebase-ID-Token": token, "content-type": "application/json" }, method: "POST", mode: "cors", redirect: "follow", referrer: "no-referrer", }) .then(response => response.json()); } }
postData is the function that makes the post request to the server endpoint. In this case, that endpoint is the localhost. Thanks to hot reloading, the app will be updated in Chrome as soon as you save the file. Now the owner of that email (you, presumably) has the ability to add new movies. You may notice, however, that no Moderator tab is visible.
Right click on the toolbar and click Inspect.
This opens developer tools so you can see what's going on under the hood of a web page. Under the myTopnav, you'll see a class, "dropdown-admin hidden". This is a flag that is set when the currently authenticated user doesn't have the moderator claim set.
Select the div with the class name "dropdown-admin hidden". Under "styles", you'll see that display is set to "none". The tag is simply hidden from view. This means that users with a little web development knowledge could inspect the page and find the source code. However, even if they found the server endpoint in the source code, they would get an unauthorized error, just as you saw earlier when you tried to make requests to it before adding your email as a moderator.
The reason the div is still hidden is because the auth token used to first sign you in did not include the custom claim. If the token is refreshed, it will have the Moderator claim. The easiest way to refresh the token is to sign out and back in. Go ahead and sign out and in. You should now see the Moderator tab.
Great work! You've successfully configured the Moderator custom claim using the Admin SDK. Time to celebrate by adding a movie. Navigate to the Moderator tab and add a new movie. Looking for some inspiration for your movie? Use this:
Title: FireFlicks Codelab
Description: Follow a developer on their journey to create an app that can handle different types of users. You'll laugh, you'll cry, you'll learn!
Genres: Action, Comedy, Drama
ImageUrl:
Click submit and a pop up appears letting you know the movie was added successfully.
Navigate to the home page and you'll see your new movie added to the list. Great job!
In this codelab, you learned how to add custom claims to Firebase Auth users through the Firebase Admin SDK. By setting custom claims on user accounts, you can assign different roles to the users of your app. You can then check if a given user has a certain role in our frontend and/or back-end code. Find the full solution in the fireflicks repository on the "complete" branch.
To learn more about Firebase Auth and the Admin SDK, visit the following resources:
Introduction to Firebase Auth
Getting Started with the Firebase Admin SDK
Introduction to the Admin Auth API
Implementing custom Auth claims with the Admin SDK | https://codelabs.developers.google.com/codelabs/firebase-admin/index.html?index=..%2F..%2Findex | CC-MAIN-2018-47 | refinedweb | 2,556 | 66.23 |
Sourpuss & unfair gripe of the day
It's hard to take the xerces-c project seriously with build instructions like this.
I particularly like the way they make you set an environment variable, although the "runConfigure" script is pretty astounding, too.
(Not that I like the default autoconf/configure much, but it's pretty standard; I have to re-read the instructions for xerces-c everytime I build it, this way.)
WSGI support for Trac
Took the existing patch for adding WSGI support to Trac and added a simple SCGI server and a dumb CGI server to wrap the WSGI app.
Here. Works for me, so far...
trac, incidentally, is pretty cool. Small, neat, to the point. And pretty.
DoS attack
Finally got the chance to investigate some intermittent Web server downtime. Turns out that it was neither name service nor Apache config problems, but instead a DoS SYN flood. This guide was useful; I got the site back up and running in no time flat. I'm still getting lots of connections, though. If it escalates I'll start using iptables to block.
I'm not sure which site they're after. Perhaps wrightflyer.org?
twill additions
Ed Rahn sent me a nice patch adding run and runfiles functionality to twill. These enable the execution of straight Python statements and other twill scripts from within twill. He also submitted something enable $variable substitution, which I'm still a bit iffy on; people tend to expect "this $variable" to be substituted, which doesn't work yet. Adding that could be a bit of a mess.
Ed's patch catalyzed a namespace reorganization and the addition of setglobal and setlocal commands, as well.
All in all, it sounds like a busy weekend -- but it wasn't ;). Lotsa sleep. hooray!
--titus | http://www.advogato.org/person/titus/diary.html?start=109 | CC-MAIN-2016-26 | refinedweb | 299 | 64.81 |
Cross Compilation and RPC¶
Author: Ziheng Jiang, Lianmin Zheng
This tutorial introduces cross compilation and remote device execution with RPC in TVM.
With cross compilation and RPC, you can compile a program on your local machine then run it on the remote device. It is useful when the remote device resource are limited, like Raspberry Pi and mobile platforms. In this tutorial, we will use the Raspberry Pi for a CPU example and the Firefly-RK3399 for an OpenCL example.
Build TVM Runtime on Device¶
The first step is to build the TVM runtime on the remote device.
Note
All instructions in both this section and the next section should be executed on the target device, e.g. Raspberry Pi. We assume the target is running Linux.
Since we do compilation on the local machine, the remote device is only used for running the generated code. We only need to build the TVM runtime on the remote device.
git clone --recursive cd tvm make runtime -j2
After building the runtime successfully, we need to set environment variables
in
~/.bashrc file. We can edit
~/.bashrc
using
vi ~/.bashrc and add the line below (Assuming your TVM
directory is in
~/tvm):
export PYTHONPATH=$PYTHONPATH:~/tvm/python
To update the environment variables, execute
source ~/.bashrc.
Set Up RPC Server on Device¶
To start an RPC server, run the following command on your remote device (Which is Raspberry Pi in this example).
python -m tvm.exec.rpc_server --host 0.0.0.0 --port=9090
If you see the line below, it means the RPC server started successfully on your device.
INFO:root:RPCServer: bind to 0.0.0.0:9090
Declare and Cross Compile Kernel on Local Machine¶
Note
Now we go back to the local machine, which has a full TVM installed (with LLVM).
Here we will declare a simple kernel on the local machine:
import numpy as np import tvm from tvm import rpc from tvm.contrib import util n = tvm.convert(1024) A = tvm.placeholder((n,), name='A') B = tvm.compute((n,), lambda i: A[i] + 1.0, name='B') s = tvm.create_schedule(B.op)
Then we cross compile the kernel. The target should be ‘llvm -target=armv7l-linux-gnueabihf’ for Raspberry Pi 3B, but we use ‘llvm’ here to make this tutorial runnable on our webpage building server. See the detailed note in the following block.
local_demo = True if local_demo: target = 'llvm' else: target = 'llvm -target=armv7l-linux-gnueabihf' func = tvm.build(s, [A, B], target=target, name='add_one') # save the lib at a local temp folder temp = util.tempdir() path = temp.relpath('lib.tar') func.export_library(path)
Note
To run this tutorial with a real remote device, change
local_demo
to False and replace
target in
build with the appropriate
target triple for your device. The target triple which might be
different for different devices. For example, it is
'llvm -target=armv7l-linux-gnueabihf' for Raspberry Pi 3B and
'llvm -target=aarch64-linux-gnu' for RK3399.
Usually, you can query the target by running
gcc -v on your
device, and looking for the line starting with
Target:
(Though it may still be a loose configuration.)
Besides
-target, you can also set other compilation options
like:
- -mcpu=<cpuname>
Specify a specific chip in the current architecture to generate code for. By default this is inferred from the target triple and autodetected to the current architecture.
- -mattr=a1,+a2,-a3,…
Override or control specific attributes of the target, such as whether SIMD operations are enabled or not. The default set of attributes is set by the current CPU. To get the list of available attributes, you can do:
llc -mtriple=<your device target triple> -mattr=help
These options are consistent with llc. It is recommended to set target triple and feature set to contain specific feature available, so we can take full advantage of the features of the board. You can find more details about cross compilation attributes from LLVM guide of cross compilation.
Run CPU Kernel Remotely by RPC¶
We show how to run the generated CPU kernel on the remote device. First we obtain an RPC session from remote device.
if local_demo: remote = rpc.LocalSession() else: # The following is my environment, change this to the IP address of your target device host = '10.77.1.162' port = 9090 remote = rpc.connect(host, port)
Upload the lib to the remote device, then invoke a device local compiler to relink them. Now func is a remote module object.
remote.upload(path) func = remote.load_module('lib.tar') # create arrays on the remote device ctx = remote.cpu() a = tvm.nd.array(np.random.uniform(size=1024).astype(A.dtype), ctx) b = tvm.nd.array(np.zeros(1024, dtype=A.dtype), ctx) # the function will run on the remote device func(a, b) np.testing.assert_equal(b.asnumpy(), a.asnumpy() + 1)
When you want to evaluate the performance of the kernel on the remote
device, it is important to avoid the overhead of network.
time_evaluator will returns a remote function that runs the
function over number times, measures the cost per run on the remote
device and returns the measured cost. Network overhead is excluded.
time_f = func.time_evaluator(func.entry_name, ctx, number=10) cost = time_f(a, b).mean print('%g secs/op' % cost)
Out:
2.057e-07 secs/op
Run OpenCL Kernel Remotely by RPC¶
For remote OpenCL devices, the workflow is almost the same as above. You can define the kernel, upload files, and run via RPC.
Note
Raspberry Pi does not support OpenCL, the following code is tested on Firefly-RK3399. You may follow this tutorial to setup the OS and OpenCL driver for RK3399.
Also we need to build the runtime with OpenCL enabled on rk3399 board. In the TVM root directory, execute
cp cmake/config.cmake . sed -i "s/USE_OPENCL OFF/USE_OPENCL ON/" config.cmake make runtime -j4
The following function shows how we run an OpenCL kernel remotely
def run_opencl(): # NOTE: This is the setting for my rk3399 board. You need to modify # them according to your environment. target_host = "llvm -target=aarch64-linux-gnu" opencl_device_host = '10.77.1.145' opencl_device_port = 9090 # create schedule for the above "add one" compute declaration s = tvm.create_schedule(B.op) xo, xi = s[B].split(B.op.axis[0], factor=32) s[B].bind(xo, tvm.thread_axis("blockIdx.x")) s[B].bind(xi, tvm.thread_axis("threadIdx.x")) func = tvm.build(s, [A, B], "opencl", target_host=target_host) remote = rpc.connect(opencl_device_host, opencl_device_port) # export and upload path = temp.relpath('lib_cl.tar') func.export_library(path) remote.upload(path) func = remote.load_module('lib_cl.tar') # run ctx = remote.cl() a = tvm.nd.array(np.random.uniform(size=1024).astype(A.dtype), ctx) b = tvm.nd.array(np.zeros(1024, dtype=A.dtype), ctx) func(a, b) np.testing.assert_equal(b.asnumpy(), a.asnumpy() + 1) print("OpenCP test passed!")
Summary¶
This tutorial provides a walk through of cross compilation and RPC features in TVM.
- Set up an RPC server on the remote device.
- Set up the target device configuration to cross compile the kernels on the local machine.
- Upload and run the kernels remotely via the RPC API.
Total running time of the script: ( 0 minutes 0.107 seconds)
Gallery generated by Sphinx-Gallery | https://docs.tvm.ai/tutorials/cross_compilation_and_rpc.html | CC-MAIN-2019-26 | refinedweb | 1,203 | 59.6 |
for connected embedded systems
scandir()
Scan a directory
Synopsis:
#include <sys/types.h> #include <sys/dir.h> int scandir( char * dirname, struct direct * (* namelist[]), int (*select)(struct dirent *), int (*compar)(const void *,const void *) );
Arguments:
- dirname
- The name of the directory that you want to scan.
- namelist
- A pointer to a location where scandir() can store a pointer to the array of directory entries that it builds.
- A pointer to a user-supplied subroutine that scandir() calls to select which entries to included in the array. The select routine is passed a pointer to a directory entry:
See also:
alphasort(), closedir(), free(), malloc(), opendir(), qsort(), readdir(), rewinddir(), seekdir(), telldir() | http://www.qnx.com/developers/docs/6.3.2/neutrino/lib_ref/s/scandir.html | crawl-003 | refinedweb | 109 | 54.22 |
This section of the documentation will contain various tutorials. These are guides that are designed to take you from beginning to end on building various types of projects with Masonite. We may not explain things in much detail for each section as this part of the documentation is designed to just get you familiar with the inner workings of Masonite.
Since this section of the documentation is designed to just get you up and coding with Masonite, any further explanations that should be presented are inside various "hint blocks." Once you are done with the tutorial or simply want to learn more about a topic it is advised that you go through each hint block and follow the links to dive deeper into the reference documentation which does significantly more explaining.
You will see various hint blocks throughout the tutorials. Below are examples of what the various colors represent.
You'll see hint blocks that are green which you should follow if you want to learn more information about the topic currently being discussed.
You'll also see hint blocks that are blue. These should not be ignored and typically contain background information you need to further understand something.
This tutorial will assume you have already installed Masonite. If you haven't, be sure to read the Installation guide to get a fresh install of Masonite up and running. Once you have one up and running or if you already have it running, go ahead and continue on.
In this tutorial we will walk through how to create a blog. We will touch on all the major systems of Masonite and it should give you the confidence to try the more advanced tutorials or build an application yourself.
Typically your first starting point for your Masonite development flow will be to create a route. All routes are located in
routes/web.py and are extremely simple to understand. They consist of a request method and a route method. Routing is simply stating what incoming URI's should direct to which controllers.
For example, to create a
GET request route it will look like:
We'll talk more about the controller in a little bit.
We will start off by creating a view and controller to create a blog post.
A controller is a simple class that holds controller methods. These controller methods will be what our routes will call so they will contain all of our application's business logic.
Think of a controller method as a function in the
views.py file if you are coming from the Django framework
Let's create our first route now. We can put all routes inside
routes/web.py and inside the
ROUTES list. You'll see we have a route for the home page. Let's add a route for creating blogs.
ROUTES = [Get('/', '[email protected]').name('welcome'),# Blog RoutesGet('/blog', '[email protected]')]
You'll notice here we have a
[email protected] string. This means "use the blog controller's show method to render this route". The only problem here is that we don't yet have a blog controller.
Let's create the
BlogController in the next step: Part 2 - Creating Our First Controller
All controllers are located in the
app/http/controllers directory and Masonite promotes 1 controller per file. This has proven efficient for larger application development because most developers use text editors with advanced search features such as Sublime, VSCode or Atom. Switching between classes in this instance is simple and promotes faster development. It's easy to remember where the controller exactly is because the name of the file is the controller.
You can of course move controllers around wherever you like them but the craft command line tool will default to putting them in separate files. If this seems weird to you it might be worth a try to see if you like this opinionated layout.
Like most parts of Masonite, you can scaffold a controller with a craft command:
$ craft controller Blog
This will create a controller in
app/http/controllers directory that looks like this:
"""A BlogController Module."""from masonite.request import Requestfrom masonite.view import Viewfrom masonite.controllers import Controllerclass BlogController(Controller):"""BlogController Controller Class."""def __init__(self, request: Request):"""BlogController InitializerArguments:request {masonite.request.Request} -- The Masonite Request class."""self.request = requestdef show(self, view: View):pass
Simple enough, right? You'll notice we have a
show method we were looking for. These are called "controller methods" and are similiar to what Django calls a "view."
But also notice we now have our show method that we specified in our route earlier.
We can return a lot of different things in our controller but for now we can return a view from our controller. A view in Masonite are html files or "templates". They are not Python objects themselves like other Python frameworks. Views are what the users will see (or view).
This is important as this is our first introduction to Python's IOC container. We specify in our parameter list that we need a view class and Masonite will inject it for us.
For now on we won't focus on the whole controller but just the sections we are worried about. A
... means there is stuff in between code that we are not worried about:
from masonite.view import View...def show(self, view: View):return view.render('blog')
Notice here we "type hinted" the
View class. This is what Masonite calls "Auto resolving dependency injection". If this doesn't make sense to you right now don't worry. The more you read on the more you will understand.
Be sure to learn more about the Service Container.
You'll notice now that we are returning the
blog view but it does not exist yet.
All views are in the
resources/templates directory. We can create a new file called
resources/templates/blog.html or we can use another craft command:
$ craft view blog
This will create that template we wanted above for us.
We can put some text in this file like:
This is a blog
and then run the server
$ craft serve
and open up. You will see "This is a blog" in your web browser.
Most applications will require some form of authentication. Masonite comes with a craft command to scaffold out an authentication system for you. This should typically be ran on fresh installations of Masonite since it will create controllers routes and views for you.
For our blog, we will need to setup some form of registration so we can get new users to start posting to our blog. We can create an authentication system by running the craft command:
$ craft auth
We should get a success message saying that some new assets were created. You can check your controllers folder and you should see a few new controllers there that should handle registrations.
We will check what was created for us in a bit.
In order to register these users, we will need a database. Hopefully you already have some kind of local database setup like MySQL or Postgres but we will assume that you do not. In this case we can just use SQLite.
Now we just need to change a few environment variables so Masonite can create the SQLite database.
These environment variable can be found in the
.env file in the root of the project. Open that file up and you should see a few lines that look like:
DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=masoniteDB_USERNAME=rootDB_PASSWORD=root
Go ahead and change those setting to your connection settings by adding
sqlite to the
DB_CONNECTION variable and whatever you want for your database which will be created for you when you migrate. We will call it
blog.db:
DB_CONNECTION=sqliteDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=blog.dbDB_USERNAME=rootDB_PASSWORD=root
Once you have set the correct credentials, we can go ahead and migrate the database. Out of the box, Masonite has a migration for a users table which will be the foundation of our user. You can edit this user migration before migrating but the default configuration will suit most needs just fine and you can always add or remove columns at a later date.
$ craft migrate
This will create our users table for us along with a migrations table to keep track of any migrations we add later.
Now that we have the authentication and the migrations all migrated in, let's create our first user. Remember that we ran
craft auth so we have a few new templates and controllers.
Go ahead and run the server:
$ craft serve
and head over to and fill out the form. You can use whatever name and email you like but for this purpose we will use:
Username: demoEmail: [email protected]Password: password
Now that we have our authentication setup and we are comfortable with migrating our migrations, let's create a new migration where we will store our posts.
Our posts table should have a few obvious columns that we will simplify for this tutorial part. Let's walk through how we create migrations with Masonite.
Not surprisingly, we have a craft command to create migrations. You can read more about Database Migrations here but we'll simplify it down to the command and explain a little bit of what's going on:
$ craft migration create_posts_table --create posts
This command simply creates the start of a migration that will create the posts table. By convention, table names should be plural (and model names should be singular but more on this later).
This will create a migration in the
databases/migrations folder. Let's open that up and starting on line 6 we should see something that looks like:
def up(self):"""Run the migrations."""with self.schema.create('posts') as table:table.increments('id')table.timestamps()
Lets add a title, an author, and a body to our posts tables.
def up(self):"""Run the migrations."""with self.schema.create('posts') as table:table.increments('id')table.string('title')table.integer('author_id').unsigned()table.foreign('author_id').references('id').on('users')table.string('body')table.timestamps()
This should be fairly straight forward but if you want to learn more, be sure to read the Database Migrations documentation.
Now we can migrate this migration to create the posts table
$ craft migrate
Now that we have our tables and migrations all done and we have a posts table, let's create a model for it.
Models in Masonite are a bit different than other Python frameworks. Masonite uses Orator which is an Active Record implementation of an ORM. This bascially means we will not be building our model and then translating that into a migration. Models and migrations are separate in Masonite. Our models will take shape of our tables regardless of what the table looks like.
Again, we can use a craft command to create our model:
$ craft model Post
Notice we used the singular form for our model. By default, Orator will check for the plural name of the class in our database (in this case posts) by simply appending an "s" onto the model. We will talk about how to specify the table explicitly in a bit.
The model created now resides inside
app/Post.py and when we open it up it should look like:
"""A Post Database Model."""from config.database import Modelclass Post(Model):pass
Simple enough, right? Like previously stated, we don't have to manipulate the model. The model will take shape of the table as we create or change migrations.
Again, the table name that the model is attached to is the plural version of the model (by appending an "s") but if you called your table something different such as "blog" instead of "blogs" we can specify the table name explicitly:
"""A Post Database Model."""from config.database import Modelclass Post(Model):__table__ = 'blog'
Orator by default protects against mass assignment as a security measure so we will explicitly need to set what columns we would like to be fillable:
"""A Post Database Model."""from config.database import Modelclass Post(Model):__fillable__ = ['title', 'author_id', 'body']
The relationship is pretty straight forward here. Remember that we created a foreign key in our migration. We can create that relationship in our model like so:
"""A Post Database Model."""from config.database import Modelfrom orator.orm import belongs_toclass Post(Model):__fillable__ = ['title', 'author_id', 'body']@belongs_to('author_id', 'id')def author(self):from app.User import Userreturn User
Because of how Masonite does models, some models may rely on each other so it is typically better to perform the import inside the relationship like we did above to prevent any possibilities of circular imports.
We won't go into much more detail here about different types of relationships but to learn more, read the ORM documentation.
Let's setup a little HTML so we can learn a bit more about how views work. In this part we will setup a really basic template in order to not clog up this part with too much HTML but we will learn the basics enough that you can move forward and create a really awesome blog template (or collect one from the internet).
Now that we have all the models and migrations setup, we have everything in the backend that we need to create a layout and start creating and updating blog posts.
We will also check if the user is logged in before creating a template.
The URL for creating will be located at
/blog/create and will be a simple form for creating a blog post
<form action="/blog/create" method="POST">{{ csrf_field }}<input type="name" name="title"><textarea name="body"></textarea></form>
Notice here we have this strange
{{ csrf_field }} looking text. Masonite comes with CSRF protection so we need a token to render with the CSRF field.
Now because we have a foreign key in our posts table, we need to make sure the user is logged in before creating this so let's change up our template a bit:
{% if auth() %}<form action="/blog/create" method="POST">{{ csrf_field }}<label> Title </label><input type="name" name="title"><br><label> Body </label><textarea name="body"></textarea><input type="submit" value="Post!"></form>{% else %}<a href="/login">Please Login</a>{% endif %}
auth() is a view helper function that either returns the current user or returns
None.
Masonite uses Jinja2 templating so if you don't understand this templating, be sure to read their documentation.
For simplicity sake, we won't be styling our blog with something like Bootstrap but it is important to learn how static files such as CSS files work with Masonite so let's walk through how to add a CSS file and add it to our blog.
Firstly, head to
storage/static/ and make a
blog.css file and throw anything you like in it. For this tutorial we will make the html page slightly grey.
html {background-color: #ddd;}
Now we can add it to our template like so right at the %}
That's it. Static files are really simple. It's important to know how they work but for this tutorial we will ignore them for now and focus on more of the backend.
Javascript files are the same exact %}<script src="/static/script.js"></script>
For more information on static files, checkout the Static Files documentaton.
Notice that our action is going to
/blog/create so we need to direct a route to our controller method. In this case we will direct it to a
store method.
Let's open back up routes/web.py and create a new route. Just add this to the
ROUTES list:
and create a new store method on our controller:
...def show(self, view: View):return view.render('blog')# New store Methoddef store(self):pass
Now notice above in the form we are going to be receiving 2 form inputs: title and body. So let's import the
Post model and create a new post with the input.
from app.Post import Postfrom masonite.request import Request...def store(self, request: Request):Post.create(title=request.input('title'),body=request.input('body'),author_id=request.user().id)return 'post created'
Notice that we now used
request: Request here. This is the
Request object. Where did this come from? This is the power and beauty of Masonite and your first introduction to the Service Container. The Service Container is an extremely powerful implementation as allows you to ask Masonite for an object (in this case
Request) and get that object. This is an important concept to grasp so be sure to read the documentation further.
Read more about the Service Container here.
Also notice we used an
input() method. Masonite does not discriminate against different request methods so getting input on a
GET or a
POST request doesn't matter. You will always use this input method.
Go ahead and run the server using craft serve and head over to and create a post. This should hit the
/blog/create route with the
POST request method and we should see "post created".
Lets go ahead and show how we can show the posts we just created. In this part we will create 2 new templates to show all posts and a specific post.
Let's create 2 new templates.
$ craft view posts$ craft view single
Let's start with showing all posts
Let's create a controller for the posts to separate it out from the
BlogController.
$ craft controller Post
Great! So now in our
show method we will show all posts and then we will create a
single method to show a specific post.
Let's get the
show method to return the posts view with all the posts:
from app.Post import Post...def show(self, view: View):posts = Post.all()return view.render('posts', {'posts': posts})
We need to add a route for this method:
Our posts view can be very simple:
{% for post in posts %}{{ post.title }}<br>{{ post.body }}<hr>{% endfor %}
Go ahead and run the server and head over to route. You should see a basic representation of your posts. If you only see 1, go to to create more so we can show an individual post.
Remember we made our author relationship before. Orator will take that relationship and make an attribute from it so we can display the author's name as well:
{% for post in posts %}{{ post.title }} by {{ post.author.name }}<br>{{ post.body }}<hr>{% endfor %}
Let's repeat the process but change our workflow a bit.
Next we want to just show a single post. We need to add a route for this method:
Notice here we have a
@id string. We can use this to grab that section of the URL in our controller in the next section below.
Let's create a
single method so we show a single post.
from app.Post import Postfrom masonite.request import Requestfrom masonite.view import View...def single(self, view: View, request: Request):post = Post.find(request.param('id'))return view.render('single', {'post': post})
We use the
param() method to fetch the id from the URL. Remember this key was set in the route above when we specified the
@id
For a real application we might do something like
@slug and then fetch it with
request().param('slug').
We just need to display 1 post so lets just put together a simple view:
{{ post.title }}<br>{{ post.body }}<hr>
Go ahead and run the server and head over the route and then and see how the posts are different.
By now, all of the logic we have gone over so far will take you a long way so let's just finish up quickly with updating and deleting a posts. We'll assume you are comfortable with what we have learned so far so we will run through this faster since this is just more of what were in the previous parts.
Let's just make an update method on the
PostController:
def update(self, view: View, request: Request):post = Post.find(request.param('id'))return view.render('update', {'post': post})def store(self, request: Request):post = Post.find(request.param('id'))post.title = request.input('title')post.body = request.input('body')post.save()return 'post updated'
Since we are more comfortable with controllers we can go ahead and make two at once. We made one that shows a view that shows a form to update a post and then one that actually updates the post with the database.
$ craft view update
<form action="/post/{{ post.id }}/update" method="POST">{{ csrf_field }}<label for="">Title</label><input type="text" name="title" value="{{ post.title }}"><br><label>Body</label><textarea name="body">{{ post.body }}</textarea><br><input type="submit" value="Update"></form>
Remember we made 2 controller methods so let's attach them to a route here:
That should be it! We can now update our posts.
Let's expand a bit and made a delete method.
from masonite.request import Request...def delete(self, request: Request):post = Post.find(request.param('id'))post.delete()return 'post deleted'
Notice we used a
GET route here, It would be much better to use a
POST method but for simplicity sake will assume you can create one by now. We will just add a link to our update method which will delete the post.
We can throw a delete link right inside our update template:
<form action="/post/{{ post.id }}/update" method="POST">{{ csrf_field }}<label for="">Title</label><input type="text" name="title" value="{{ post.title }}"><br><label>Body</label><textarea name="body">{{ post.body }}</textarea><br><input type="submit" value="Update"><a href="/post/{{ post.id }}/delete"> Delete </a></form>
Great! You now have a blog that you can use to create, view, update and delete posts! Go on to create amazing things! | https://docs.masoniteproject.com/creating-a-blog | CC-MAIN-2020-34 | refinedweb | 3,660 | 65.12 |
A failure story
For the past two months, Pepe and I were working on a redesign project for a new client, the goal of the project is to pay some of the technical debt this customer has. They’ve been running a business for several years on top of a PHP app with tons of legacy code that was getting pretty unmaintainable.
We decided to split this app into two separated ones, one for the frontend and the other for the backend. This way the former contractor the client had could focus on providing an API while Pepe and I work on the frontend.
The plan seemed like a good one, but things didn’t go as expected, the other provider was having a hard time delivering the API endpoints we needed, and this problem was delaying us and our ability to show progress. We couldn’t just show a bunch of disconnected components, or could we?
That’s when I realized we could use StoryBook to show the client our progress without building much harness code that was likely to change shortly.
The StoryBook
Storybook is a tool that integrates with your current react app and allows you to develop components in isolation. That means, instead of developing your component inside a parent component it provides a blank sheet where you can build without worrying about anything else.
You may think this is not needed, or that you have enough practice to do it correctly without any complementary tools but at least in our case, it helped a lot. Bear with me; it has some significant advantages.
Component variations
Every time I write a component I overlook the variations it may have. Because my goal is to finish the page I’m working on, my primary focus is in the best case scenario that gets my page to render correctly.
Since StoryBook is disconnected from the page and its main feature is to present the different variations of a component it forces me to think about that first.
Imagine a simple table:
<Employees list={this.props.employees} sortable />
My first instinct when creating this type of component is to get a table rendering.
But if you want to have this rendering on a StoryBook the tool will ask you to think about the variations, here is how Employees may look like in a StoryBook definition.
import React from 'react'; import { storiesOf } from '@kadira/storybook'; import Employees from '../components/Employees'; storiesOf('Employees', module) .add('with empty list', () => <Employees list={[]} />) .add('with one element', () => <Employees list={[employee1]} />); .add('with one element and sortable', () => <Employees list={[employee1]} sortable />);
Similar to what happens when unit testing things upfront, storybook forces you to think about the input(s) (and their relations) beforehand. In this example, should I make the list sortable if it has only one element?
Avoid API leaking
Another great feature storybook provides for my mental model is to un-tight the structure of the objects that live in the store (either redux, mobx or local state) from the props.
Should I have an employee list or maybe just a generic table with some config options will do?
This type of questions helps me draw the line between how much coupling I want my components to have with the data structure saved in the store.
Collaborate in the open
As we develop the app, the client wants to check the progress, and we want them to check it, so we can correctly set the expectations.
Having this tool helped a lot to close the feedback loop, we experiment with new UI solutions in the open by deploying the storybook to an internal URL and gather enormous feedback that gets us closer to what the customer needs.
Wrapping up
So far we are pretty happy with development process storybook has enabled us and I have a lot more to share in a follow-up post like how to use it with
connected components or how to set up testing directly inside storybook, but that's for another post.
As a conclusion I encourage you to check storybook, it’s very unobtrusive and easy to set up. If you are lucky enough to use create react app, it's even easier; the CLI does everything for you.
As a conclusion I encourage you to check storybook, it’s very unobtrusive and easy to set up. If you are lucky enough to use
create react app, it's even easier; the CLI does everything for you. | https://cherta.website/adding-storybook-to-our-workflow/ | CC-MAIN-2020-40 | refinedweb | 751 | 57.61 |
@danchapman Thanks for the tip. I removed the .py files and I was using this one import in last version:
import io.thp.pyotherside 1.4
Everything was working, but in the last update of Ubuntu Touch (2018-W40), the python side is not working.
In the last UT version I have the package libpython3.5:armhf, then I think the error is coming because the libpython3.4 doesn't exist. But... I'm just importing "io.thp.pyotherside 1.4", the crash (IMO) is coming from the pyotherside from the system (?).
I tried
import io.thp.pyotherside 1.5, but same result.
Any help please? Thanks in advance! | https://forums.ubports.com/user/costales/posts | CC-MAIN-2019-51 | refinedweb | 109 | 81.09 |
- Help mouse over a link to change a diffrent cell's background in Netscape
- math with int and floats doesn't work?
- document.url
- onKeyPress in Opera 7.11
- passing information between webpages using cookie
- MySQL use with JavaScript, client side
- Can you make this work in Netscape 7 (javascript CSS manipulation)
- Javascript news ticker required
- max call using onSubmit?
- Help, how can you parse a decimal and ...
- regular expressions
- Opening a New Internet Explorer Pop Windows to a remote IP
- Need a little help :)
- Include another file in a script
- Javascript To Resize Window?
- help: create a spreadsheet-like feel
- <DIV> show/hide...both appear...why oh why?
- script to store articles
- simple script needed..
- hitting enter causes a page reload (I think)
- disable all href/links when user click a link
- OnUnLoad
- forcing URL in frame??
- how to know what the opener is loading from the opened window
- how to fill some field in parent window from a child window
- location.replace() in the onUnload event?
- refresh opener
- remove options
- refreshing two frames with only one click
- Submit form to pop-up - why does this code not work?
- closing brower windows
- document.getElementById / appendChild
- Question about Key Codes
- Javascript:LaunchCenter
- Does submit count as an onChange event ?
- Changing the 'display' of multiple items
- File Name Validation when Uploading Images
- Pick Color From Downloaded Image
- Input prompt
- Read HTTP Headers with Javascript???
- Playing Quicktime movies
- Auto insert Date in form input field
- Setting focus on radio button
- CSS and javascript interaction
- Can javascript POST without refresh?
- Getting supported methods of objects
- using applets
- MY WAY OR THE HIGHWAY
- is there a suplement in Netscape for resizeTo(widht,height)
- Can javascript give me image dimensions?
- Password protection
- Object scoping issue
- Click link in popup window and insert link text in a field of mother window
- popup rollover menu hiding behind frame
- Elementary question: How do I set BG IMAGE SiZE for all monitors?
- onChange problem with two dropdowns and one form
- checkbox help needed
- roll over
- again: foreign page finished loading
- Can I focus a popup window without refreshing it?
- changing or at least detecting character encoding via javascript ?
- Combo Box and text box
- Simple Iframe & Form question
- Help With A Calculation
- Javascript and Netscape 4.7
- iframe and netscape question
- Yet another inexplicable js error!
- How do you make sure a frameset is loaded? I'm trying to open a frameset in a new window which shows a specific html page in a specific frame
- Opera 7.11 reloads *.js wrong
- help in detecting aol popup blocker
- IBM Sash
- Javascript innerHTML
- Auto Populate Text Box
- myArray instanceof Array fails after passing to a different page
- Caret Position in a Text Field
- text mesg
- get html source from a url
- Frames and Images
- Using history in frameset
- Referencing dynamic forms with Javascript events
- Javascript Target For ondblclick Event
- Probably a daft question?
- convert string to object reference
- Close specific parent window
- displaying special characters in a <div>
- Returning multiple results from a subroutine ?
- Pop-up question
- Automatic Pop-up Window Sizer
- Simple Question = simple answer?
- Transferring value from one select box to another
- Carriage return inefficiency in a textarea control
- avoid innerHTML parsing
- add a text in the same HTML page
- Hiding multiple rows in a dynamic table
- Trying to execute a function *following* RESET clearing the textfields...
- floating point numbers question
- Wrong connection string to a sql-server
- How can I click on a joke and have a new joke appear?
- Determining background color of a cell...
- Dynamic Include Page? Change what's included as mouse moves?
- Netscape 7.1 and IFrames/ILayers Src
- De-activating windows using Javascript
- Looping Through Forms: Best Practice
- JS development tool?
- password validation with reg exp
- Javascript onLoad error "Object doesn't support this action"
- Assigning between arrays by value
- Popup Question: on popup have one button to close and another to close and then redirect to another page
- How do I print one frame?
- Javascript in a php document
- Sub menus
- linked dropdownboxes, php
- get data from another page
- Does any have example of js code to resize images?
- window.print with no print dialog prompt
- Scaling images in IE
- forms and frames
- Question on JavaScript Objects
- String manipulation in javascript?
- User Agent Detection Logic
- Changing HTML input text style color from javascript
- bookmark for ebook
- looking for the best online DOM reference
- Submit a value
- How to check HTTP_ACCEPT_LANGUAGE using Javascript?
- focus() onLoad
- No Netscape or IE 4.x support??
- viewing javascript generated html code
- embed methods
- dropdown menu?
- dynamic file input controls
- Going nuts with random number routine HELP!
- Problem with Javascript windows
- Form submit on load
- Forcing document to submit cookies
- My javascript works great for every browser but Safari. How can I fix that?
- evaluation context of event handler string
- Edit javascript in IE
- How to add a timeout to a javascript ad tag
- innerHTML and images loading
- How to add event to mouseover without replace the existing one
- new popup window does not jump to anchor
- unload()
- Howto Add a timeout to a javascript ad tag
- Can I make browsers display contents of a window triggered by onClick before page finishes loading?
- two action commands within one html form?
- call js after page loads
- Javascript
- write to a different frame
- Refreshing a browser with onClick event
- a website opens in my iframe Is there a way to know the address of the link the visitor clicks on ?
- Question on the use of IFRAMES
- arrays and objects
- Mouse Pointer Location
- Simple question I hope!
- need javascript to show a layer
- Counting checked checkboxes in a form
- Changing drop-down field to text field.
- "this" object
- image swapping - js and webserver portibiltiy
- javascript optimization
- Time picker
- Div and select element
- change styles?
- 2 Selection Lists in a web form
- get a a char's position when its string is clicked
- Strange result in comparison function
- onResize + IE = torture
- DIV and Dropdowns
- if file exist
- big binary string
- default style.backgroundColor value
- How to pass data between two window without Session??
- form questions
- "print" in JavaScript
- javascript generated html
- Script to condense a line of text
- pop up windows on user command
- Slideshow from local PC
- Javascript Security and History functions
- javascript and html
- Override method question
- querying textfields outside of forms...
- How to force reload of "temperature.js" data
- Textfield Numeric Sorting?
- Catching 404 and 500 in IFRAMEs?
- createElement applet and Opera 7
- settimeout problem
- Show complete select box entry
- returning variable from javascript function to C#.net
- What does this do
- how to set html page without scrollbars
- How to get value(s) from Multiple Selection enabled Select Box
- Resizing an IFrame
- Is it OK to use <div> to change text and images?
- How do I hide a picture when loading a page?
- How do I show something I've hidden?
- Button resizing in Opera
- How do I change the size of an image?
- Mind Reading Web Site!
- Why doesn't onmouseover work in a function?
- sorry for this trivial question about dates
- Scroll Bar Visibility
- reading 'type' from eventhandlers
- javascript to have a new browser window open maximized or aligned top
- onload and move to a point down the page
- Open and close window
- Please wait image does not animate
- Pop up issue
- Save new page on server
- basic question
- getVersion of the Java VM?
- Control charcters in form input field
- Page with many form elememts
- changing styles of createElement | appendChild
- Popup windows ("window.open") no longer works!
- Show/hide TR
- How to hit a server in the background?
- Problem - part 2
- Open function
- form field arrays
- Mozilla, innerHTML question.
- Is there a global script to open all links on a page in a pop up for a photo album.
- Any way to fire off an HTTP request without 'waiting' for a result?
- JavaScript cookies (in subdirectories) and PHP file
- Using DOM to access other windows
- help with function
- Can't seem to attach to "onbeforeunload" event.
- IE5 + ok, netscape 7.1 no workie
- Help with indexOf()
- how to include " in my validation script
- Capture PrintDialog Events
- Javascript Navigation
- Can I get my local IP address from javascript under IE?
- <object> persistence across pages?
- Using execCommand to edit an existing HTML page
- reading image opacity
- Help:: Why Class ID is used
- onMouseOver
- drag and drop ranking system
- document.print change default headers and footers
- onclilck variable
- Post Data with Javascript and without using a form tag.
- Validate form for 4-digit integer
- Making my own attibutes for HTML Tags
- Checking radio buttons
- Problem...help
- Need Remote Button with sub-topics
- Convert for netscape?
- Display user's IP address when visiting internal site
- retreiving fontSize and/or DIV dimensions from linked stylesheet
- Sending html data to the IFrame contents
- TextArea Validation
- Order of execution
- Refreshing a href variable using OnChange of a select list
- detecting flash
- Executing Programs Using Javascript
- Forcing an onChange event to fire
- IP Info Code Snippet problem
- RIGHT Mouse Button - on Click? Prevent photo download
- Trigger checkbox when combo box is changed
- window.location & cookies?
- help :O( cant reference element within an inline frame
- Capturing the onkeydown event i an IFRAME.
- IE 6 Question Mark Wierdness
- Why won't this onsubmit action fire?
- detecting when a frame has loaded the result of a form submit
- Can't change window.status message - help!
- Does anybody have any ideas?
- window.open does not work?
- reloading windows
- Using external js fil
- How to create a RADIO button using DOM
- Really need some help
- Open Fullscreen in SAME WINDOW.... please help
- how to use applet in IE or Netscape
- javascript popup window that stays in front of parent window?
- Pause() function?
- Help: Imbedded </script> within a document.write()
- How to check for existance of Input elements that are type=TEXT???
- back() and reload() at the same time?
- Forms without HTML
- getElementById errors
- .onmouseover=... syntax question re NN events
- Multiple Check Boxes URL Jump TIA
- Wrong syntax for formatNumber() ? I'm stuck.
- onunload and a couple of things...
- Control the URL for all documents
- In search of a good linked list implementation
- Secure logins...
- Carriage return inside a message of alert
- Scope of instance of an object
- Encrypting JS Code on wscript
- popup error (javascript)
- Function to create GUID equivalent?
- Detect when new window is opened?
- Javascript -- confused on the return false -- simple validate function?
- language redirect
- How do you know what button was pressed in the submit?
- Missing text
- Server logs.
- UTF-8 to Shift JIS
- automated scrollTo() problem
- PDF Save Option
- Possible to check for empty input boxes when names generated dynamically?
- calling a windows application (from hyperlink?)
- [RegExp] Making non-greedy; Escaping parentheses?
- how to make the control boxes disappear?
- Push html content peer to peer
- How to Customize Internet Explorer Menus Using JS and Any other Scripting Language
- what's wrong with this line?
- "the page was replaced while you was trying ..."
- Placing a focus
- send variables to function in new window
- submit formvalues with javascript
- I want a popup window onclick which close itself when next page is displayed
- Sorting HTML Table based on a column (Using JavaScript)
- Where to store a "variable" in a <div>?
- javascript in forms
- JS in frame1 <--> JS in frame2
- 'document is not an object' when trying to change <DIV> content
- Mouse won't change (onmousedown="this.style.cursor='different'")
- Advanced onclick button which disable all other buttons on the document problem
- click() question
- browsers and javascript
- How do I read the Value of the submit Button
- how to jScript into one line?
- How to get a selected value from <Select> using DOM
- DHTML issues with IE
- scanning a directory using javascript
- JavaScript function to print a pdf file.
- How to create Check Box and Select Tag
- Accessing table rows length via DOM?
- Add moving text to image
- JavaScript animation doesn't work
- "complex" rollover animation question
- Execute web page without loading
- test blank string
- passing vars
- How to detect when user presses browser back buttons
- please verivy this code
- Arrays as form elemtents
- location of prompt box - can you dictate?
- LiveConnect packages
- Accessing document form elements outside a function
- Favourites & Homepage
- NS + JS = BS
- checking existence of an element?
- IE6 and navigator.plugin solution?
- Measuring Web Download Time (client Vs server side)
- compare strings -- what's the trick?
- clip in Opera
- download PDF in new window
- Why doesn't window.document.getElementById('junk') return 'undefined'?
- Prototype not working:
- checking for back button
- checking type?
- Change Event Handler Programatically
- MAC + Netscape = error
- Objects as Array Indices ?
- event.keyCode
- a little array query
- Mozilla, written html and getElementById
- Mozilla and setInterval
- Disable Submit Button until Accept Terms and Redirect Page on Submit
- Opening new window in Mozilla
- Detecting when the select element's dropdown list is open and/or closed
- Javascript and frames
- How to escape a quote in a string?
- PLEASE -- why doesn't this validate function work? PLEASE?
- how to put javascript in a file
- creating a web keyboard for data entry within IFRAME
- calculating in table made by createElement and appendChild
- HOW TO FORCE PASSING A REFERER
- Where is good JavaScript Reference site online?
- Centering Browser Pop-Up Window?
- Self contained system for color transition
- accessing javascript objects from another frame
- variables and html
- Search/replace patterns in web pages?
- Web design sites
- how close modal dialog from the first window
- Advanced DHTML Dropdown List component with Autofilter feature
- Calculating "working days" for a given period
- get USERNAME
- Regular Expression pattern
- saving info
- cascademenu.js problem with Mozilla vs IE
- Functions as objects
- Keeping Web Page at Fixed Width
- If a mailto is sent the page does not continue to load
- checkboxes
- Animation - only first and last images display
- Dropdown menu with links
- if statement with checkbox.checked
- for in and arrays
- DROPDOWN MENU & Frames
- Simpleton singleton that installs its own function type properties
- GMT/UTC help
- Nested function X vs. nested varX = function
- javascript & frames
- function source to HTML ?
- color in the user input box
- Focusable elements
- Javascript forms question, please help.
- showModalDialog leaves gap at right hand edge
- Javabeans - handling multiple forms on a single JSP
- for loop
- Sending message on load
- javasript problem - submiting
- How do I write a reg expression to search for NOT a substring?
- defining and accessing js objects.
- submit buttons - changing behaviour
- How to set width of text input to physical text width
- Opera - .closed not accessible if window is closed?
- Reset setTimeout
- Popup above cursor
- Site help
- Help: Make all fields in table tag required.
- weird problem with variable
- Onblur() event cause infinite loop
- Script-generated code displaying differntly than the exact same code displayed staticly... help!?!?!
- select boxes and ordering
- try-catch error handling -- display line number?
- dynamic for loop
- input type text value
- Flickering mouse pointer when scrolling background images
- IE6: setInterval, this==window arrgh
- setTimeout causes return of 32 million instead of x,y coordinate
- Trying to understand this code
- I need a simple Javascript shopping cart.
- loggout.php fails to properly redirect
- Please Advise
- Javascript code for fitting a background image to the window
- Links to frame
- which <option> was clicked on?
- document.layers & Mozilla
- req help: make page open 'itself' without toolbars
- Loop multiple sounds onClick w/js?
- submitting form through javascript
- javascript resource list needed
- Can some fix this code? Delet table rows.
- Netscape DOM issue?
- How do I convert a string integer into a number?
- What could cause scrollWidth to return 0?
- open .exe from link with no confirm box?
- Hey guys, I didn't really make my question too clear I guess... sorry.
- How can I put a <div> in <td> ??
- Why can't I access child frame elements with the direct form?
- user input box: first 2 characters as a read only value
- Form validation problem...
- Change Stylesheet definition based on browser resolution
- return value from JSP to Javascript
- Global event handler of new window being lost on location change
- Use of the same variable on multiple pages
- please nobody who can help me with this simple script?
- using 'name' or using 'id' of a form?
- [Netscape] href in iframe hangs when calling function in parent window
- Getting Unix login name or home dir from client-side JavaScript
- how to access an object in a form with getElementById?
- disable minimize button in pop up window
- Frame gets overriden by a page
- Add properties to function while in function with out specifying function ?
- I think it has something to do with array...but not sure...pls help
- Easy Regex (when you know how... and I don't)
- Can I resize Excel window from IE browser?
- Inheritace and super.class calling
- stop refresh windows?
- two different behaviours with 'return value' of a function
- Detecting cookies
- How do I center a div both vertically and horozontally?
- how to set window.print() property?
- Class or Type?
- Begginer Stuck!!
- Correct way to implement visitor tracking?
- Cookies set one time, I delete cookie, cookie is never set again!
- Dealing with possible namespace clashes
- Noob question...
- Display Business Hours Adjusted for the Visitor's Time Zone
- ONBLUR() LOOP
- Mouse movement while a button is pressed
- change text: foo -> bar
- Reaching a sibling frame ?????
- Reading Cookie from a different domain?
- Image upload dimension check
- Acces to TD in array on html document ?
- ** IE5, IE6 and NETSCAPE COMPATIBILITY PROBLEM **
- problem with accessing functions
- Some rather complex animated line/circle drawing
- java plugin targeting through javascript
- window.close()
- does this way to start a function not work with NS?
- regex question
- Refresh values with a button
- Classes and functions for IM's
- changing class properties
- Beginner Needing Help
- Javascript, signing, and Netscape 7
- Browser Close event Problem
- IE6, xhtml, scrollbars and you
- How to get source of nested function ?
- Server-side scripts with ASP
- onclick Javascript Problem
- Function Exists -- Parent Window
- pop ups
- javascript page error
- need help debugging opensource script on Mac IE
- second pop up window
- any chance to get notification on changing innerHTML
- Backslash does NOT escape Apostrophe
- showModalDialog() Jumping to Bottom of Popup's Body
- Dynamically Show/Hide table rows?
- input names with '-' in their names.
- Javascript and Menus using styles
- JavaScript as a general purpose programming language?
- locked out of .style.cursor changes
- Beginner Needing Help!!
- Use JavaScript in VB Application
- writing to external javascript file
- onMouseOver event - Question
- Secondary sort
- offset top calculation problem
- rollover problem
- sysdate function
- Reliability/Availability of Option, Select, etc. objects
- set checkbox
- Multiple Popup windows
- Form Validation
- document layers question
- insert text in textarea
- JavaScript becomes disabled - HELP!!
- OnMouseDown in NN4.7
- view server time
- javascript error
- Drop Down Menu
- create a photogallery by code.
- xml, xsl, css ... in netscape
- Extracting everything after penultimate backslash
- IFRAME AS FORM TARGET! POSSIBLE?
- Inaccuracies in absolute positioning
- mysql ?
- Can I use CSS to specify event handlers ?
- With clause syntax errors but how do I fix it?
- target div
- To test a function with a Broser
- Setting Scrollable position for div tag
- override part of css
- What causes all windows & popups to shake and quiver and shiver ? | https://bytes.com/sitemap/f-286-p-66.html | CC-MAIN-2021-10 | refinedweb | 3,164 | 54.63 |
set qicon to qpushbutton
- user4592357
i'm trying to set an icon to qpushbutton, and the image for the icon is in the same directory as this source file, but it won't show up on the button. however, if i put the image in the root directory and specify the full path for it, say "C:\\1.png", the image will show up.
why is this? and how can i set an icon from current directory (or say, one directory above)? i've tried "./1.png" which didn't work.
thanks.
#include <QApplication> #include <QPushButton> #include <QIcon> int main(int argc, char **argv) { QApplication app(argc, argv); QIcon icon("1.png"); QPushButton button; button.setIcon(icon); button.show(); return app.exec(); }
Hi..
You must add your png in resource file and then insert url in brackets.
QIcon icon(":/new/ok.png"); QPushButton *button = new QPushButton(this); button->setIcon(icon); button->show(); | https://forum.qt.io/topic/82322/set-qicon-to-qpushbutton | CC-MAIN-2018-26 | refinedweb | 152 | 59.5 |
3.2-stable review patch. If anyone has any objections, please let me know.------------------From: Jonathan Austin <Jonathan.Austin@arm.com>commit 078c04545ba56da21567728a909a496df5ff730d upstream.Currently when ThumbEE is not enabled (!CONFIG_ARM_THUMBEE) the ThumbEEregister states are not saved/restored at context switch. The default stateof the ThumbEE Ctrl register (TEECR) allows userspace accesses to theThumbEE Base Handler register (TEEHBR). This can cause unexpected behaviourwhen people use ThumbEE on !CONFIG_ARM_THUMBEE kernels, as well as allowingcovert communication - eg between userspace tasks running inside chrootjails.This patch sets up TEECR in order to prevent user-space access to TEEHBRwhen !CONFIG_ARM_THUMBEE. In this case, tasks are sent SIGILL if they try toaccess TEEHBR.Reviewed-by: Will Deacon <will.deacon@arm.com>Signed-off-by: Jonathan Austin <jonathan.austin@arm.com>Signed-off-by: Russell King <rmk+kernel@arm.linux.org.uk>Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>--- arch/arm/mm/proc-v7.S | 12 ++++++++++++ 1 file changed, 12 insertions(+)--- a/arch/arm/mm/proc-v7.S+++ b/arch/arm/mm/proc-v7.S@@ -382,6 +382,18 @@ __v7_setup: mcr p15, 0, r5, c10, c2, 0 @ write PRRR mcr p15, 0, r6, c10, c2, 1 @ write NMRR #endif+#ifndef CONFIG_ARM_THUMBEE+ mrc p15, 0, r0, c0, c1, 0 @ read ID_PFR0 for ThumbEE+ and r0, r0, #(0xf << 12) @ ThumbEE enabled field+ teq r0, #(1 << 12) @ check if ThumbEE is present+ bne 1f+ mov r5, #0+ mcr p14, 6, r5, c1, c0, 0 @ Initialize TEEHBR to 0+ mrc p14, 6, r0, c0, c0, 0 @ load TEECR+ orr r0, r0, #1 @ set the 1st bit in order to+ mcr p14, 6, r0, c0, c0, 0 @ stop userspace TEEHBR access+1:+#endif adr r5, v7_crval ldmia r5, {r5, r6} #ifdef CONFIG_CPU_ENDIAN_BE8 | http://lkml.org/lkml/2012/4/19/493 | CC-MAIN-2017-34 | refinedweb | 283 | 58.08 |
Hi Bob and Chris, On Wed, 2004-06-30 at 15:52, Bob Friesenhahn wrote: > I was going to suggest using AC_TRY_LINK but for some reason I can't > find it in the Autoconf documentation anymore. Instead I see a > AC_LINK_IFELSE macro which must be used in conjunction with > AC_LANG_PROGRAM. Maybe AC_TRY_LINK has been retired. Yep. From what I recall the AC_*_IFELSE macros provide more uniform/consistent interfaces than their deprecated AC_TRY_* counterparts. Perhaps Akim can confirm this. > Unfortunately, I do not have time to write an example. I think that > almost any compilable code fragment which lacks a main routine will > serve as a test. You would temporarily add the library to be tested > to LIBS. If you have a successful link, then a main() routine was > found somewhere. Here's an example from the ACE configure script: dnl Use a more comprehensive test for shm_open() since the prototype dnl may not be visible on all platforms without enabling POSIX.1b dnl support (e.g. when the user defines _POSIX_C_SOURCE > 2). AC_MSG_CHECKING([for shm_open]) AC_LINK_IFELSE([AC_LANG_PROGRAM( [[ #ifndef ACE_LACKS_SYS_TYPES_H # include <sys/types.h> #endif #include <fcntl.h> #include <sys/stat.h> #include <sys/mman.h> ]], [[ const char name[] = "Foo"; const int oflag = O_RDONLY; const mode_t mode = 0400; /* Whatever */ const int fd = shm_open (name, oflag, mode); ]])], [ AC_DEFINE([ACE_HAS_SHM_OPEN]) AC_MSG_RESULT([yes]) ], [ AC_MSG_RESULT([no]) ]) You'll of course have to add the library you're testing for to $LIBS before you run the link-time test, and remove it if the test fails. HTH, -Ossama -- Ossama Othman <ossama @ dre . vanderbilt . edu> 1024D/F7A394A8 - 84ED AA0B 1203 99E4 1068 70E6 5EB7 5E71 F7A3 94A8 | https://lists.gnu.org/archive/html/autoconf/2004-06/msg00138.html | CC-MAIN-2015-48 | refinedweb | 271 | 66.84 |
Given a sample code:
1 public class Test implements Runnable {
2 public void run() {
3 System.out.println("Inside run");
4 }
5 public static void main(String[] args) {
6 // place code here.
7 // place code here.
8 t.start();
9 System.out.println("End of main");
}}
What statement should be placed at line number 6 and 7 so that result will
come as
"Inside run"
"End of main"
Choose the correct option:
(A) Runnable r = new Runnable(); and Thread t = new Thread(r);
(B) Runnable r = new Thread(); and Thread t = new Thread(r);
(C) Runnable r = new Test(); and Thread t = new Thread(r);
(D) Runnable r = new Test(); and Thread t = new Thread(new Test);
| http://www.roseindia.net/tutorial/java/scjp/part8/question2.html | CC-MAIN-2016-50 | refinedweb | 117 | 75.54 |
Simple MNIST and EMNIST data parser written in pure Python
Project description
Simple MNIST and EMNIST data parser written in pure Python.
MNIST is a database of handwritten digits available on. EMNIST is an extended MNIST database.
Requirements
- Python 2 or Python 3
Usage
git clone
cd python-mnist
Get MNIST data:
./get_data.sh
Check preview with:
PYTHONPATH=. ./bin/mnist_preview
Installation
Get the package from PyPi:
pip install python-mnist
or install with setup.py:
python setup.py install
Code sample:
from mnist import MNIST mndata = MNIST('./dir_with_mnist_data_files') images, labels = mndata.load_training()
To enable loading of gzip-ed files use:
mndata.gz = True
EMNIST
Get EMNIST data:
./get_emnist_data.sh
Check preview with:
PYTHONPATH=. ./bin/emnist_preview
To use EMNIST datasets you need to call:
mndata.select_emnist('digits')
Where digits is one of the available EMNIST datasets. You can choose from
- balanced
- byclass
- bymerge
- digits
- letters
- mnist
EMNIST loader uses gziped files by default, this can be disabled by by setting:
mndata.gz = False
You also need to unpack EMNIST files as get_emnist_data.sh script won’t do it for you. EMNIST loader also needs to mirror and rotate images so it is a bit slower (If this is an issue for you, you should repack the data to avoid mirroring and rotation on each load).
Notes
This package doesn’t use numpy by design as when I’ve tried to find a working implementation all of them were based on some archaic version of numpy and none of them worked. This loads data files with struct.unpack instead.
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/python-mnist/ | CC-MAIN-2018-26 | refinedweb | 284 | 67.76 |
agrimm (Andrew Grimm)
- Registered on: 11/08/2009
- Last connection: 07/11/2014
Issues
- Assigned issues: 0
- Reported issues: 25
Projects
Activity
05/06/2014
- 11:01 PM Ruby trunk Bug #5828: Non anonymous classes can't be frozen, cloned and then inspected
- I'm happy for this bug to be closed, as I don't have a need to freeze and clone a class.
01/02/2014
- 09:11 AM Ruby trunk Bug #9340 (Closed): Document order related behavior in Array#uniq
- The behavior of Array#uniq without a block in Ruby 2.1.0 is inconsistent with the behavior of Array#uniq in Ruby 2.0....
10/03/2013
- 11:08 AM Ruby trunk Bug #8975: Confusing code sample for assert_send
- To be honest, it's not so much a "legacy app" issue as a "legacy programmer" issue.
I started programming back in ...
10/02/2013
- 07:48 AM Ruby trunk Bug #8975 (Closed): Confusing code sample for assert_send
- Test::Unit::Assertsions#assert_send has the code sample
assert_send([[1, 2], :member?, 1]) # -> pass
asse...
09/18/2013
- 07:37 AM Ruby trunk Feature #8691: Add warning for variable that is re-assigned but not re-used
- Yes, close the ticket. If someone else wants the functionality, or has implemented the functionality and wants to sub...
09/10/2013
- 08:26 AM Ruby trunk Feature #8691: Add warning for variable that is re-assigned but not re-used
- A third party tool that I use, called Rubocop, has implemented such functionality....
07/26/2013
- 08:52 AM Ruby trunk Feature #8691 (Closed): Add warning for variable that is re-assigned but not re-used
- The following code
def reassigned_unused
a = 42
b = a.to_s
a = 56
b
end
Does not currently generat...
05/01/2013
- 04:54 PM Ruby trunk Bug #8351 (Closed): Error message is not grammatical
- Enumerable#chunk has the error message "symbol begins with an underscore is reserved".
This is not grammatical. As...
02/23/2013
- 10:29 PM Ruby trunk Bug #7920 (Closed): Version of RubyGems in NEWS incorrect
- NEWS claims that RubyGems 2.0.0.preview2 is used, but according to ChangeLog, 2.0.0 (non-preview) is used.
If ther...
01/23/2013
- 03:51 PM Ruby trunk Feature #7730 (Closed): Top level variables aren't checked for assigned but unused behavior
- In the following code, variable a in the method gets a warning, but variable b in top level code doesn't get any warn... | https://bugs.ruby-lang.org/users/950 | CC-MAIN-2018-51 | refinedweb | 413 | 60.24 |
Arduino LCD Thermostat!
Introduction: Arduino LCD Thermostat!
In this project we'll use an arduino uno, an LCD and a temperature sensor to control your air conditioning.! Also You can modify the code for a heater. The code is well explained! I show even how I made mine permanent!
Great your beginners to learn arduino and for hot room that have an old manual a/c. This is a project to try!
Step 1: Prototyping the Test Circuit
This circuit is to test if the thermostat is working or not. The lcd should display a hello,world! sketch, the the current temperature of the room, and below is the ideal temperature or settemp. If the current temperature is off by a little you may need to adjust the code which calculates the 10 bit number read from A0 into a temperature reading in degrees Fahrenheit. If you need Celsius will will also need to change the line of code the calculates the temperature. If you wan to control an a/c, you can remove the led and replace it with an N-Channel MOSFET ( Metal Oxide Semi-conductor Field Effect Transistor). Then TO USE A PROTECTION DIODE! I will go over this as well. In the next step.
Parts list:
12 volt power supply
7805 5 volt voltage regulator
arduino uno or other arduino dev board
3x 10k ohm resistors
led
jumper wire
solderless breadboard
arduino ide
10k potentiometer ( or a 1k ohm and a 220 ohm resistor) (or the 3rd pin can go to ground)
16x2 Hitachi driven hdd44780 LCD
10k thermistor a.k.a. (10k ohm NTC, (Negative Thermal Coefficient)
2x tactile button switches ( or any other button switch)
usb b type connector to program arduino
For use with an a/c:
N-channel MOSFET
120VAC 20-40A relay
1N4007 - 1N4004 rectifier diode
a/c
To finalize:
perfboard / PCB
Project enclosure
And tool that everyone should have
Let's get started!
Step 2: The Code
So the code:
// written by Dylon Jamna (ME!)
// include the library code
#include <EEPROM.h>
#include <LiquidCrystal.h>// include the library code
int tempPin = A0; // make variables// thermistor is at A0
int led =13; // led is at pin
float temp; // make a variable called temp
float settemp; // make a variable called temp
int swtu = 7; // switch up is at pin 7
int swtd = 6; // switch down is at pin 6
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // lcd is at 12,11,5,4,3,2
void setup() {
pinMode (led,1); // make led or pin13 an output
Serial.begin (9600); // set the serial monitor tx and rx speed
lcd.begin(16, 2); // set up all the "blocks" on the display
lcd.setCursor(0,0); // set the cursor to colum 0 row 0
lcd.print("hello, world!"); // display hello world for 1 second
lcd.clear(); // clear the lcd
EEPROM.read (1); // make the eeprom or atmega328 memory address 1
}
void loop() {
int tvalue = analogRead(tempPin); // make tvalue what ever we read on the tempPin
float temp = (tvalue / 6.388888888889); // the math / conversion to temp
lcd.setCursor (0,0); // set the cursor to 0,0
lcd.print (temp); // Print the current temp in f
lcd.print ('F');
Serial.println (temp); // print the temp it the serial monitor
settemp = EEPROM.read(1); // read the settemp on the eeprom
delay (250); // wait for the lcd to refresh every 250 milliseconds
if // if we se the switch up pin reading on 1 or 5 volts
(digitalRead(swtu)== 1 )
{
settemp ++ // add one to the settemp, the settemp is the ideal temperature for you
;
}
else{// other wise do nothing
}
if
(digitalRead (swtd) == 1)// if we detect a 1 on the other switch pin
{
(settemp --);// subtract one fromm the settemp
}
else {
// else, do nothing
}
if (temp > settemp) // if the temperature exceeds your chosen settemp
{
digitalWrite (led, 1); // turn on the led
}
else // if that doesn't happen, then turn the led off
{
digitalWrite (led,0);
}
lcd.setCursor (0,1); // set the cursor to 0,1
lcd.print ("Set To "); // Print set to and your ideal temperature in f
lcd.print (settemp);
lcd.print ('F');
Serial.println(settemp); // Print the settemp in the serial montior
EEPROM.write (1,settemp); /* write the most recent settemp in eeprom data stoage
so that if the power is disconnected, you settemp is saved!*/
delay (250); // wait 250 milliseconds
} // we're done
Step 3: The Build
Now to actually make this project useful we need to make it more permanent. We do this by soldering it to the perfboard. Now there are many ways to solder on perfboard. The way I prefer to solder it is by soldering on thick buses for power and ground made of solder. Then I strip, tin, and solder ribbon cable wire to every necessary connection. But you can tin track on the board, or wire above the board and solder below which is very popular. Also to switch our a/c on or off we need to modify the led. Now there are a few seps to follow.
Step 1 - remove the led
Step 2- attach the gate of your N channel MOSFET Check your datasheet for the pin out!!!!
Step 3 - Attach the ground to your source pin on the MOSFET
Step 4 - Attach the Drain pin to your MOSFET
Step 5 - Attach your relay's coil to 12v depending on the relay, and the other to you drain pin on the MOSFET
Step 6 - Add the the protection diode, connect the striped silver end (cathode) to your 12v, and you other end (anode) to your Drain pin on the MOSFET.
use the other diagram for the power input.
Step 4: The Final Product
Now I know this isn't the best looking project enclosure as you saw in the intro, but here's how I did it. I use 1/4 plywood type of scrap kind of wood, and you can check the Home depot for it and look carefully. I cut it up to size and nailed it together with an air compressor nailing gun. It actually didn't split,( Take your time or it will split!) No glue is necessary. I drill hole for the wire like the thermister and 3 wires for the separate relay power control box, and drilled one big one were the lcd was supposed to go. This was so I could stick a jigsaw blade in there and cut out a rectangle. The 2 tactile switches had tall shafts which poked through the plywood just barely. You could glue or epoxy on plastic rods from a pen tube or something.
Also I embedded an atmega8 not an atmega328 just because my sketch was only 6k bytes. The atmega8 only holds 8k bytes so I was safe. I pretty much made a stand alone arduino on perboard. I used a voltage divider for the lcd which was 1k and 220 ohm resistor. 1k goes to 5 volts and pin 3 on the LCD, and the 220 ohm resistor goes to ground and the pin 3 on the LCD.
To prop up the board to the front panel. The 3 pin header connector was from the connection the the relay power box.
I used an iec connector, I soldered a main female connector to this one so I can plug it in the box. I used hot glue this time for the box and it worked surprisingly well.
Remember to comment or contact me if you have any problem. Any go to arduino.cc and arduino forums or more troubleshooting and help.
tvalue / 6.388888888889. but what is the tvalue. hou do i calculate it to Celsius
Hello,
I m newbe.
hoe do i set F to Celsius.
I have to chance float temp = (tvalue / 6.388888888889); // the math / conversion to temp
to what?
thanks
Wiring is wrong on breadboard for the LCD backlight needs reversing.
Small errors in code notes, needs some mean values on coding as too sensitive for central heating it toggles too much near changeover threshold OK for electrical heating.
Arduino termisotr
How to change max. set temp with 250F to 350F???
How to change the set temp???????
You use the push buttons with a pull down resistor in this configuration to change the set temp. But do change it for your application, this is a rough version that still could use a little tweaking because the subtle temperature changes trigger the a/c on and off a million times. Good luck!
I made it FINALLY after months of problems!!! i reworked the code a bit and added 3 relays total and a toggle switch cause where i live sometimes you just want it off!
the relays are for
1. hot
2. cold
3. fan
and my switch is a 4 way switch so it can click to heat, cool, fan, and off
thanks a bunch!!! if i get a nice sheild made i may do a kickstarter! do you have a way for me to donate some $ to you?
Hi Dylon,
Your project seems useful so I tried to replicate it but using Grove-LCD RGB Backlight display instead.
Everything is flowing nicely until I get to the user buttons. Im using a-pushto-off button with only 2 connecting wires.
So the problem I'm facing is, when I pressed the up button, the temperature (settemp) will go up and not stop. Same goes if I press the down button.
I'll give you my codes below but Im sure it's similar..
Please help me if you can. It's giving me sleepless nights... :(
// Declare variables
#include <Wire.h>
#include <EEPROM.h>
#include <Bounce2.h>
#include "rgb_lcd.h"
rgb_lcd lcd;
const int colorR = 30;
const int colorG = 30;
const int colorB = 60;
float tempC;
float settemp;
int tempPin = A0; //temp sensor plugged in pin 0
int ledPin = 13; //closest to ground
int fan1 = 2; // fan connected to pin 6
int swtu = 7;
int swtd = 6;
Bounce bouncer = Bounce();
// Write setup programme
void setup()
{
Serial.begin(9600); //Open serial port to communicate. sets data rate to 9600
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// initialize the serial communications:
lcd.setRGB(colorR, colorG, colorB);
lcd.print("Temp = ");
delay(250);
pinMode(ledPin, OUTPUT);
pinMode(fan1, OUTPUT);
pinMode(swtu, INPUT);
bouncer.attach (swtu);
bouncer .interval(5);
pinMode (swtd, INPUT);
bouncer.attach (swtd);
bouncer .interval(5);
EEPROM.read(1); //make eeprom memory address
}
//Write loop that will control the
void loop()
{
tempC = analogRead(tempPin); // read the analog value from the lm35 sensor.
tempC = (5.0 * tempC * 100.0)/1024.0; // convert the analog input to temperature in centigrade.
lcd.setCursor(8,0);
lcd.print(tempC);
lcd.print("'C");
Serial.print((byte)tempC); // send the data to the computer.
settemp = EEPROM.read(1); // read the settemp at memory 1
delay (250);
if (digitalRead (swtu)==1)
{
(settemp ++);
EEPROM.write(1, settemp);
}
else{
}
if (digitalRead(swtd)==1)
{
(settemp --);
EEPROM.write(1, settemp);
}
else {
}
if (tempC > settemp)
{
digitalWrite(ledPin, HIGH);
digitalWrite(fan1, HIGH);
}
else
{
digitalWrite(ledPin, LOW);
digitalWrite(fan1, LOW);
}
lcd.setCursor(0,1);
lcd.print("Set Temp To: ");
lcd.print(settemp);
Serial.print((byte)settemp);
// EEPROM.write(1, settemp);
delay(250);
}
In the code, you have
if (temp > settemp) // if the temperature exceeds your chosen settemp
{
digitalWrite (led, 1); // turn on the led
}
else // if that doesn't happen, then turn the led off
{
digitalWrite (led,0);
}
I'm guessing that turning on the LED also activates the MOSFET and turns on the A/C, correct?
My main question is this: For someone who has both a heater and an A/C, could you have it do something like this:
if (temp > settemp + 2) // if the temperature exceeds your chosen settemp
{
digitalWrite (led, 1); // turn on the led for the A/C circuit
}
elseif (temp < settemp - 2) //If the temperature exceeds your settemp
{
digitalWrite (led, 1); // turn on the LED for the heater circuit
}
else // if that doesn't happen, then turn the led off
{
digitalWrite (led,0);
// digitalWrite (ledX,0); //ledX would be the second led for the heater circuit
}
My goal with this is to replace the "heat/cool" switch on a regular thermostat, and have it be a pure climate control system (where it either turns the heat or A/C on to keep the temp at what you want). Also, I added the + 2 and - 2, because most furnaces and A/C's won't start until the temp is 2 degrees above/below your set temp. It might have to be tweaked out to 3 or 4, depending on whether your furnace and/or A/C stops before the actual temp gets more than 2 degrees from your set temp. Otherwise, your heater and a/c will constantly be turning off and on to keep your temp set.
Have a great day.:)
Patrick.
The code is a good beginning but needs revision on the EEPROM.write command being used through every loop. EEPROM has a limited number of write cycles before it wears out. A better idea would be to only write to it periodically or only when the value to be written changes.
I know what you mean. But I used a cheap atmega8 that can be rewriten about 10,000 times before having errors. Plus, I really new to coding up the arduino.
The easiest way to reduce the number of write cycles would be to move the 'EEPROM.write' command to a new line just below each of the
'(settemp ++);' and '(settemp --);' lines. This way the EEPROM is only being written to each time a button is being pressed.
thx I'll try and change my code
Add your relay pin control to pin 10-8 or else you will flick to relay on and of rapidly it the start of the code. | http://www.instructables.com/id/Arduino-LCD-Thermostat/ | CC-MAIN-2017-43 | refinedweb | 2,304 | 72.56 |
Introduction to Java programming, Part 2
Constructs for real-world applications
More-advanced Java language features
Content series:
This content is part # of # in the series: Introduction to Java programming, Part 2
This content is part of the series:Introduction to Java programming, Part 2
Stay tuned for additional content in this
- Using class variables and class methods
You'll start enhancing
Person by overloading one of
its methods.
Overloading methods
When you create two methods with the same name but with different argument lists (that is, different numbers or types of parameters), you have an overloaded method. At runtime, the JRE decides which variation of your overloaded method to call, based on the arguments that were passed to it.
Suppose that
Person needs a couple of methods to print an
audit of its current state. I call both of.
Remember two important rules when you use overloaded methods:
- You can't overload a method just by changing its return type.
- You can't have two same-named methods with the same parameter list.
If you violate these rules, the compiler gives you an error.
Overriding methods
When a subclass provides its own implementation of a method that's defined
on one of its parent classes, that's called method overriding. To
see how method overriding is useful, you need to do some work on an
Employee class. Once you have that class set up, I show you
where method overriding comes in handy.
Employee: A subclass of Person
Recall from Part 1 of this tutorial that an
Employee class might
be a subclass (or child) of
Person that has
additional attributes such as taxpayer identification number, employee
number, hire date, and salary.
To declare the
Employee class, right-click the
com.makotojava.intro package in Eclipse. Click New
> Class... To open the New Java Class dialog box, shown in
Figure 1.
Figure 1. New Java Class dialog box
Enter
Employee as the name of the class and
Person as its superclass. Click Finish, and
you can see the
Employee class code in an edit window.
You don't explicitly need to declare a constructor, but go ahead and
implement both constructors anyway. With the
Employee class
edit window having the focus, go to Source > Generate
Constructors from Superclass.... In the Generate Constructors
from Superclass dialog box (see Figure 2), select both constructors and
click OK.
Figure 2. Generate Constructors from Superclass dialog box
Eclipse generates the constructors for you. You now have an
Employee class like the one in Listing 2.
Listing 2. The as a child of Person
Employee inherits the attributes and behavior of its parent,
Person. Add some attributes of
Employee's own,
as shown in lines 7 through 9, as you did for in the "Your first Java class" section in Part 1.
Overriding the printAudit() method
Now you'll override the
printAudit() method (see Listing 1) that you used to format the current
state of a
Person instance.
Employee inherits
that behavior from
Person. If you instantiate
Employee, set its attributes, and call either of the
overloads of
printAudit(), the call succeeds. However, the
audit that's produced doesn't fully represent an
Employee.
The
printAudit() method can't format the attributes specific
to an
Employee, because
Person doesn't know
about them.
The solution is to override the overload of
printAudit() that
takes a
StringBuilder as a parameter and add code to print
the attributes specific to
Employee.
With
Employee open in the editor window or selected in the
Project Explorer view, go to Source > Override/Implement
Methods.... In the Override/Implement Methods dialog box,
shown in Figure 3, select the
StringBuilder overload of
printAudit() and click OK.
Figure 3. Override/Implement Methods dialog box, or they won't be
included in the audit output.
Comparing objects
The Java language provides two ways to compare objects:
- The
==operator
- The
equals()method
Comparing objects with ==
The
== syntax compares objects for equality such that
a == b returns
true only if
a and
b have the same value. For objects, this will be the case if
the two refer to the same object instance. For primitives, if the
values are identical.
Suppose you generate a JUnit test for
Employee (which you saw
how to do in the "Your first Java class" section in Part 1. The JUnit test is shown in Listing 4.
Listing)); } }
Run the Listing 4 code inside Eclipse (select
Employee in the
Project Explorer view, then choose Run As > JUnit
Test) to generate the following output:
instance."
Comparing objects with equals()
equals() is a method that every Java language object gets for
free, because it's defined as an instance method of
java.lang.Object (which every Java object inherits from).
You call
equals() like this: 4 to the one in
Listing 5 (which I've called
anotherTest()), which uses
equals() to compare the two objects.
Listing 5 code produces this output: (boxed)
int value is the same.
For
Employee, you didn't override
equals(), so
the default behavior (of using
==) returns what you'd()— and you can do this in Eclipse. With
Employee having the focus in the IDE's source window, select
Source > Override/Implement Methods to open the
dialog box shown in Figure 4.
Figure 4. Override/Implement Methods dialog box
— name, and age — are the same.
Autogenerating equals()
Eclipse can generate an
equals() method for you based on the
instance variables (attributes) that you define for a class. Because
Employee is a subclass of
Person, you first
generate
equals() for
Person. In the Eclipse
Project Explorer view, right-click
Person and choose
Generate hashCode() and equals(). In the dialog box
that opens (see Figure 5), click Select All to include
all of the attributes in the
hashCode() and
equals() methods, and click OK.
Figure 5. Generate hashCode() and equals() dialog box
Eclipse generates an
equals() method that looks like the one
in Listing 6.
Listing 6.; }
The
equals() method generated by Eclipse looks complicated,
but what it does is simple: If the object passed in is the same object as
the one in Listing 6,.
Exercises
Now, work through a couple of guided exercises to do even more with
Person and
Employee in Eclipse.
Exercise 1: 2: especially useful, but every object has one.
In this exercise, you override
toString() to make it a little
more useful.
If you suspect that Eclipse can generate a
toString() method
for you, you're correct. Go back into your Project Explorer and
right-click the
Person class, then choose Source >
Generate toString().... In the dialog box, select all
attributes and click OK. Now do the same thing for
Employee. The code generated by Eclipse for
Employee is shown in Listing 7.
Listing 7. A
toString() method generated by
Eclipse
@Override public String toString() { return "Employee [taxpayerIdentificationNumber=" + taxpayerIdentificationNumber + ", employeeNumber=" + employeeNumber + ", salary=" + salary + "]"; }
The code that Eclipse generates for
toString doesn't include
the superclass's
toString() (
Employee's
superclass being
Person). You can fix that situation.
Class members
Every object instance has variables and methods, and for each one, the
exact behavior is different, because it's based on the state of the object
instance. The variables and methods that you have on
Person
and
Employee are instance variables and methods. To
use them, you must either instantiate the class you need or have a
reference to the instance.
Classes can also have class variables and methods — known
as class members. You declare class variables with the
static keyword. The differences between class variables and
instance variables are:
- Every instance of a class shares a single copy of a class variable.
- You can call class methods on the class itself, without having an instance.
- Class methods can access only class variables.
- Instance methods can access class variables, but class methods can't access instance variables. on it. Listing 8 shows a common use of class variables.
Listing 8. 8,
retrieved a
Logger instance to write output to the console.
Notice, though, that to do so you didn't need an instance of
Logger. Instead, you referenced the
Logger
class, which is the syntax for making a class method call. As
with class variables, the
static keyword identifies
Logger (in this example) as a class method. Class methods are
also sometimes called static methods for this reason.
Now you can combine what you learned about static variables and methods to
create a static method on
Employee. You declare a
private static final variable to hold a
Logger,
which all instances share, and which is accessible by calling
getLogger() on the
Employee class. Listing 9
shows how.
Listing 9. Creating a class (or static) method
public class Employee extends Person { private static final Logger logger = Logger.getLogger(Employee.class.getName()); //. . . public static Logger getLogger() { return logger; } }
Two important things are happening in Listing 9:
- is set to
null. Run this code and you get the following output:
java.lang.NullPointerException at com.makotojava.intro.EmployeeTest.yetAnotherTest(EmployeeTest.java:49) . . .
This output is telling you that you're trying to reference an object
through a
null reference (pointer), which is a pretty serious
development error. (You probably noticed that Eclipse warns you of the
potential error with the message:
Null pointer access: The variable employee1 can only be null at this location.
Eclipse warns you about many potential development mistakes — yet
another advantage of using an IDE for Java development.)
Fortunately, you can use
try and
catch blocks
(along with a little help from
finally) to catch the
error.
Using occurred.). In general, these are direct subclasses of
java.lang.Exception.
- Unchecked exceptions (also called runtime exceptions) are not checked by the compiler. These are subclasses of
java.lang.RuntimeException.
The code in Listing 12 must declare a variable to
hold the
bufferedReader reference, and then in the
finally must close the
BufferedReader.
Alternative, more-compact syntax (available as of JDK 7) automatically
closes resources when the
try block goes out of scope.
Listing 13 shows this newer.
The application entry point
All Java applications need an entry point where the Java runtime knows to
start executing code. That entry point is the
main() method.
Domain objects — that is, objects (
Person and
Employee, for example) that are part of your application's
business domain— typically don't have
main() methods, but at least one class in every application
must.
As you know,
Person and its
Employee subclass are
conceptually part of a human-resources application. Now you'll add a new
class to the application to give it an entry point.
Creating a driver class
The purpose of a driver class (as its name implies) is to "drive"
an application. Notice that this simple driver for a human-resources
application contains a
main() method:
package com.makotojava.intro; public class HumanResourcesApplication { public static void main(String[] args) { } }
Now, create a driver class in Eclipse using the same procedure you used to
create
Person and
Employee. Name the class
HumanResourcesApplication, being sure to select the option to
add a
main() method to the class. Eclipse will generate the
class for you.
Next,); } }
Finally, launch the
HumanResourcesApplication class and watch
it run. You should see this output:. 14.
Listing 14. 14.
Defining a. However, as you'll learn in the next main
section, Interfaces, the Java language supports
implementing multiple interfaces in a single class, giving you a
workaround of sorts to single inheritance. only if you are sure
you'll, the following two declarations are functionally identical:
public class Person { public Person() { } } // Meanwhile, in Employee.java public class Employee extends Person { public Employee() { } } can invoke another constructor in the same class via the
this keyword, along with an argument list. Like
super(), the
this() call must be the first line
in the constructor, as in this example:
public class Person { private String name; public Person() { this("Some reasonable default?"); } public Person(String name) { this.name = name; } }
You see this idiom frequently. One constructor delegates to another, passing in a default value if that constructor is invoked. This technique'd. However, the superclass method is still's invoked through a reference to the subclass.
This capability also applies to variables, provided the caller has access to the variable (that is, the variable is visible to the code trying to access it). This detail can cause you no end of grief as you gain proficiency in Java programming. Eclipse provides ample warnings — for example, that you're hiding a variable from a superclass, abstract, sometimes
can't be instantiated.
The power of abstraction
Suppose that you need a method to examine the state of an
Employee object and make sure that it's valid. This need
would seem to be common to all
Employee objects, but it would
have zero potential for reuse because it would behave differently among
all potential subclasses. In that case, you declare the
validate() method
abstract (forcing all
subclasses to implement it):
public abstract class Employee extends Person { public abstract boolean validate(); }
Every direct subclass of
Employee (such as
Manager) is now required to implement the
validate() method. However, once a subclass implements path that could restrict your application. You can always refactor common behavior (which is the entire point of having abstract classes) further up the inheritance graph — and it's almost always better to refactor after you've discovered that you do need to. Eclipse has wonderful support for refactoring.
Second, as powerful as abstract classes are, resist using them. Unless your superclasses contain much common behavior and aren else the compiler gives you an error. Whatever is on the right side of the assignment must be a subclass or the same class as the thing on the left. To put it another way: a subclass is more specific in purpose than its superclass, so think of a subclass as being narrower than its superclass. And a superclass, being more general, is wider than its subclass. The rule is this, you may never make an assignment that will narrow the reference.
Now consider this example:
Manager m = new Manager(); Manager m2 = new Manager(); m = m2; // Not narrower, so okay Person p = m; // Widens, so okay Employee e = m; // Also widens Employee e = p; // Narrows, so not okay!
Although an
Employee is a
Person, it's most
definitely not a
Manager, and the compiler enforces this
distinction.
Interfaces
In this section, you begin learning about interfaces and start using them in your Java code.
Interfaces: What are they good for?
As you know from the previous section, abstract methods, by design, specify a contract— through the method name, parameter(s), and return type — but provide no reusable code. Abstract methods — defined on abstract classes — are useful when the way the behavior is implemented is likely to change from the way it's implemented in one subclass of the abstract class to another.
When you see a set of common behaviors in your application (think
java.util.List) that can be grouped together and named, but
for which two or more implementations exist, you might consider defining
that behavior with an interface— and that's why the Java
language provides this feature. However, this fairly advanced feature is
easily abused, obfuscated, and twisted into the most heinous shapes (as
I've witnessed first-hand), so use interfaces with caution.
It might be helpful to think about interfaces this way: They are like abstract classes that contain only abstract methods; they define only the contract but none of the implementation.
Defining an interface
The syntax for you want it to. Remember, a class can extend only one class. If one class extends another and implements an interface or interfaces, you list the interfaces after the extended class, like this:
public class Manager extends Employee implements BonusEligible, StockOptionRecipient { // And so on }
An interface doesn define an interface on your class, you must implement the
interface, which means that you provide a method body that doesn't implement.
Note: Subclasses of a concrete class that implements an interface do not need to provide their own implementation of that interface (because the methods on the interface have been implemented by the superclass).'s not. Why not? Because
Manager implements the
StockOptionEligible
interface, whereas (or inner class) is a class defined within another limit the functionality to the class where you need it.
Typically, you use a nested class when you need a class that's tightly coupled with the class in which it's defined. A nested class has access to the private data within its enclosing class, but this structure carries with it side effects that aren't obvious when you start working with nested classes.
Scope in nested classes
Because a nested class has scope, it'd expect the
compiler to require you to have a reference to a
Manager
object before you could reference it, right? Well, the same applies to
DirectReports, at least as it's defined in Listing 19.
To create an instance of a public nested class, you use a special version
of the
new operator. Combined with a reference to an
enclosing instance of an outer class,
new gives you a way you
to create an instance of the nested class:
public class Manager extends Employee { public Manager() { } . . . public class DirectReports { . . . } } // Meanwhile, in another method somewhere... public static void main(String[] args) { Manager manager = new Manager(); Manager.DirectReports dr = manager.new DirectReports(); }
Note on line 12 that the syntax calls for a reference to the enclosing
instance, plus a dot and the
new keyword, followed by the
class you want to create.
Static inner classes
At times, you want to create a class that you should use them
only implement abstract classes and interfaces pretty much anywhere, even in the middle of a method if necessary, and even without providing a name for the class. This capability is basically a compiler trick, but there are times when anonymous inner classes are handy to have.
Listing 20 builds the Listing 20 example, I provide implementations of two interfaces that
use anonymous inner classes. First are two separate implementations of
StockOptionEligible— one for
Employees
and one for
Persons (to obey the interface). Then comes an
implementation of
StockOptionProcessingCallback that's used
to handle processing of stock options for the
Manager
instances.
It might take time to grasp the concept of anonymous inner classes, but they're super handy. I use them all the time in my Java code. And as you progress as a Java developer, I believe you will too..
Regex pattern syntax
A regex pattern describes the structure of the string that the expression tries to find in an input string. The pattern syntax can look strange to the uninitiated, but once you understand it, you'll find it easier to decipher. Table 2 lists some of the most common regex constructs that you use in pattern strings.
Table 2, you can work through the simple example in Listing 21, using the classes in the Java Regular Expressions API.
Listing 21. Pattern matching with regex
Pattern pattern = Pattern.compile("[Aa]. 21 21 string:
a string with more than just the pattern.
If you search this string for
a.*string, you get a match if
you use
lookingAt(). But if you use
matches(),
it returns
false, because there's more to the string than
what's in the pattern.-Z][a-z]*([A-Z][a-z]*)+
And here's,'s
replace methods is
straightforward:("replacement"); Logger.getAnonymousLogger().info("After: " + result);
This code finds wiki words, as before. When the
Matcher finds
a match, it replaces the wiki word text with its replacement. When you run
the code, you can. 22 replaces each wiki word with a string that "wraps" the word.
Listing 22. Matching groups 22 code, and you get the following console output:
Before: Here is a WikiWord followed by AnotherWikiWord, then SomeWikiWord. After: Here is a blahWikiWordblah followed by blahAnotherWikiWordblah, then blahSomeWikiWordblah.
Listing 22 references the entire match by
including
$0 in the replacement string. Any portion of a
replacement string of the form
$int refers to the
group identified by the integer (so
$1 refers to group 1, and
so on). In other words,
$0 is equivalent to
matcher.group(0);.
You could accomplish the same replacement goal by using.0, the Java language had nothing to constrain this behavior, which
caused many coding mistakes. In Listing 23, for
example, everything is looking good so far. But what about accessing the
elements of the
ArrayList, which Listing 24 tries to do?
Listing 24.); } } 25 shows how, and what happens if you try
and add an object of the wrong type (line); } } 26 shows the syntax to parameterize
SimpleList.
Listing 26. Parameterizing
SimpleList
package com.makotojava.intro;:
Parameterized methods
At times, you might not want to parameterize your entire class, but only
one or two methods. In this case, you create a generic method.
Consider the example in Listing 27, where the method
formatArray is used to create a string representation of the
contents of an array.
Listing 27. A generic method
public class MyClass { // Other possible stuff... ignore... public <E> String formatArray(E[] arrayToFormat) { StringBuilder sb = new StringBuilder(); int index = 0; for (E element : arrayToFormat) { sb.append("Element "); sb.append(index++); sb.append(" => "); sb.append(element); sb.append('\n'); } return sb.toString(); } // More possible stuff.... Before
enum was introduced into the language, you would have defined
a set of constant values for a concept (say, gender) like so:
public class Person { public static final String MALE = "male"; public static final String FEMALE = "female"; public static final String OTHER = "other"; }, OTHER }
This example only scratches the surface of what you can do with
enums. In fact,
enums are much like classes, so
they can have constructors, attributes, and methods:
package com.makotojava.intro; public enum Gender { MALE("male"), FEMALE("female"), OTHER("other"); implementing"), OTHER("other"); various
sources. that it's a valid file name for your operating
system, if a resource is a file, directory, or symbolic link
- More
The main action of Java I/O is in writing to and reading from data sources, which is where streams come in.
Using streams in Java I/O
You can access files on the file system by using streams. At the lowest
level, streams enable.
Byte streams read (
InputStream and subclasses) and write
(
OutputStream and subclasses) 8-bit bytes. In other words, a
byte stream can be considered a more raw type streams in their entirety, I'll focus here on the recommended 28 is an example in reading from a
File:
Listing 29 is an example of writing to a
File:
Listing isn't
efficient, so in most cases you probably want to use buffered I/O instead.
To read from a file using buffered I/O, the code looks just like Listing 28, except that you wrap the
InputStreamReader in a
BufferedReader, as shown
in Listing 30.
Listing 30. 31.
Listing 31.:
import java.io.Serializable; public class Person implements Serializable { // etc... } 32.
Listing 32., 32, you could use a JUnit test, as shown here: 33 reads the file you've just serialized and
deserializes its contents, thereby restoring the state of the
List of
Employee objects.
Listing 33. 33, you could use a JUnit test like this one: 32 and Listing
33. = 20100515; // etc... }..
Downloadable resources
Related topics
- developerWorks Java development
- IBM developer kits
- 5 things you didn't know about Java Object Serialization
- IBM Code: Java journeys | https://www.ibm.com/developerworks/java/tutorials/j-introtojava2/index.html | CC-MAIN-2018-43 | refinedweb | 3,900 | 53.31 |
Read file in reverse order
Project Description
Before we go into technical details, a note about the license: It’s GPLv3. This practically means that if you use this module, your program needs to be GPLv3. Sorry about that.
Briefly, the following will print my_file backwards:
import sys from simpletail import ropen with ropen('my_file') as f: for line in f: sys.stdout.write(line)
It will work on Unix. It will work on Windows. On Python 2 and 3. It will work regardless what kind of line endings you have. It should work with any file encoding (but you need to specify an encoding, see below), but I’m not certain about that; if in your encoding there are multibyte characters that contain the bytes \n or \r, it will probably not work.
Reference
ropen(file, bufsize=4096, encoding=None, errors=None, newline=None, closefd=True)
ropen() returns a file object. file is usually a file name, but in Python 3 it can be anything open() accepts as a first argument (however wrapping files opened in text mode will probably not work). The file is read from the end in chunks of size bufsize. The rest of the arguments have the meaning they have in the open() built-in function of Python 3, but they will also work in Python 2, with the exception of closefd, which is ignored in Python 2.
License
Written by Antonis Christof Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/simpletail/0.1.2/ | CC-MAIN-2018-17 | refinedweb | 261 | 71.65 |
2 years, 4 months ago.
TimeOut not working properly on NUCLEO-F103RB
Hello all,
I found a problem when I use multiple TimeOuts on a Nucleo-F103RB. When I use two (or more) TimeOuts the program sometimes suddenly seems to 'stop'. I calculate the deltaTime (the time it takes to run one loop, = stopTime loop - startTime loop) which normally takes about 23 uS to complete. After 1253 loops, the deltaTime suddenly drops to 5 uS for 20 loops. After 2253, 5388 and 9388 loops the same problem occurs. It always takes exacly 20 loops to get back to the normal deltaTime.
When I include a wait or if I change the parameters of the TimeOuts the position of the drops change.
Does anybody know what can cause this drop or how it can be fixed? Here's my code:
MultipleTimeOuts
#include "mbed.h" Serial pc(USBTX, USBRX); //tx rx debug Timer timer; Timeout timer1; Timeout timer2; bool timing1 = false; bool timing2 = false; long starttime; long endtime; long deltatime; void interrupt1(){ timing1 = false; } void interrupt2(){ timing2 = false; } int main(){ timer.start(); //wait(1); while(1){ starttime = timer.read_us(); if(timing1 == false){ timer1.attach_us(&interrupt1, 300); timing1 = true;} if(timing2 == false){ timer2.attach_us(&interrupt2, 300); timing2 = true;} endtime = timer.read_us(); deltatime = endtime - starttime; pc.printf("%i\r\n", deltatime); } }
1 Answer
2 years, 4 months ago.
Hello Hein,
There are some issues with the current implementation of
Timer,
Ticker,
Timeout and
wait family of functions for STM boards that are using a 16-bit timer. See for example this link. Fortunately STM team has already a solution which is in test phase and available here. Using the new hal_tick_16.c and us_ticker_16b.c in my project fixed all the issues. I think it is worth to give it a try.
timing1 and timing2 should be volatile otherwise you could get some weird compiler optimisation issues.posted by Andy A 09 Jun 2017 | https://os.mbed.com/questions/78243/TimeOut-not-working-properly-on-NUCLEO-F/ | CC-MAIN-2019-43 | refinedweb | 320 | 68.36 |
Short Intro
I’ve compiled below? should I include ES6 modules in my next project or stick to good-old ‘require’? Mixing and matching among all of those require deep familiarity with the consequences. These rich set of tools and paradigms also encourages you to tiptoe into unexplored territory. I hope that the next bullets will inspire you to enrich your toolbox and diversify yourself.
My name is Yoni Goldberg, I’m an independent Node.js consultant, the co-author of Node.js best practices, and JavaScript testing best practices. I work with customers in US & Europe on planning, testing and hardening their apps.
Follow me: Twitter, Blog, Newsletter, Testing workshop
📗 Want to take your testing skills to the extreme? Consider visiting my comprehensive course ‘Testing Node.js & JavaScript From A To Z’
Reviewed & improved by Bruno Scheufler
1. Use TypeScript features thoughtfully
TypeScript is exploding: the amazing chart here that shows x5 increase in TypeScript PRs remove any doubt, researches tell that it prevents errors and the community is in love. Though some voices still doubt it (check out this great and well-reasoned post by Eric Elliott) it’s clear that TypeScript has won. Now what? if you look carefully under the hype, TypeScript actually brings two mutual-exclusive offerings to the table: type-safety (including better docs and intellisense) and advanced design constructs. Many teams use TypeScript for better type safety yet unintentionally, without any proper planning, also use its fancy features —generics, abstract classes, interfaces, namespaces, etc. These teams change their design style from vanilla JavaScript to fancy OOP unintentionally due to the ‘law of the instruments’ — a cognitive bias that involves using the tooling in hand whether they are the right choice for the mission or not. In other words, if ‘abstract class’ exists in the toolbox — developers will use it. If you do favor the aforementioned coding techniques— that’s fair, go with this. Just don’t change your code and design style for the wrong reasons
Examples:
- Type Inference can help in reducing TypeScript verbosity and make it look more like vanilla JavaScript
- Type aliases are an alternative simple and leaner way for defining constructs (comparing with interfaces).
- Using TypeScript for encapsulation? access modifiers are coming soon to vanilla JS
2. Modernize your testing toolbox. Ava & Jest are changing the game
Big things are happening in the testing field. According to the recent state of js survey, developers` satisfaction from testing tools increases more than any other domain. A revolution is happening on test runners as well as the good old veteran Mocha and Jasmine are losing the top for the new sophisticated kids in town Jest and Ava. Thanks to the modern approach they bring, it’s possible to test more, cover more ground and find more bugs. Why?
- Speed — modern test runners are faster thanks to the multi-process execution model. They also apply advanced optimizations like learning tests stats over time and prioritizing slow tests to run first. This is not only about test runners, but other tools also boost test speed: fake in-memory database allow testing with DB without the involvement of IO, some npm packages offer a local and in-memory version of popular cloud services. To name a few examples.
- Outstanding developer experience — modern test runners and tools are designed to accompany the coding experience and provide valuable insights. For example, should a test fail, Jest and Ava will not just report a failure rather extract the related code from the unit under test. Thanks to this, developers get much richer context which leads to a faster resolution
Some of the traditional tools were designed for CI or for occasional test execution. In times where teams deploy once a day, discovering a bug after 4 hours is not good enough. Modern tooling allows running tests, including component tests with DB, constantly even during coding. This approach allows for testing more layers and more use cases earlier and it’s called ‘shift left’ — read more about it below
Examples:
- AVA & Jest are the new sophisticated kids in town
- mongodb-memory server is amazing for testing with MongoDB server — it installs, instantiates and configures a local and real Mongo with in-memory engine
- Cypress makes E2E testing, including backend’s API related tests, a delightful experience
- aws-sdk-mock fakes many AWS services
3. Plan your ES6 modules usage strategy. See, it’s a bit tricky
The long-awaited ES6 modules were unflagged recently, so you might be tempted to use it right away. They bring great opportunities to Node land like a modern syntax for importing modules, compatibility with frontend syntax (important for package maintainer that need to support both Node and browser runtime) and asynchronous modules resolution that opens the door for top-level async-await and better tree shaking. Cool. However, there are some implications that one must be aware of before jumping on the ESM wagon: not all the supporting features are implemented yet. For example, it’s unclear yet how test doubles libraries like Sinon and Jest can ‘mock’ such modules so your wagon might break on the side of the road with smoke.
Given all of these considerations, what’s your strategy: jump straight into the ESM water and work around the issues? or use ESM with babel/TS as a safety net? maybe keep on with gold old common js ‘require’ but avoid incompatible syntax like usage of __filename, __dirname, JSON resolution, and others? there are no strict answers here but at least we strive to ask the right questions
Thanks to Gil Tayar for these great insights
Examples:
- Differences Between ES Modules and CommonJS from the official Node.js docs
- The ESM roadmap and features that are not implemented yet
- Great post on ESM syntax and status
4. Meet the latest JavaScript features that are turning green soon
I’m not a big fan of chasing for every new language feature, sometimes these shiny toys work against the code simplicity and clarify. From time to time, however, some really valuable Javascript features are presented so it’s worthwhile watching the TC39 proposal list and node.green to identify attractive new features that fit your coding style
Examples:
- Optional chaining is at stage 4 and part of Node.js 13.3 behind a flag. This one is going to catch a lot of popularity. Some love it, others don’t
- Private methods and fields are at stage 3 (active proposals) so if you’re opting for TypeScript only for encapsulation — now there is one more option to choose from
- Nullish coalescing (stage 4) will finally put a stop to our nasty habit of checking for nulls & undefined using the !variableName syntax (which also includes zero and therefore is error-prone)
- Promise.any is the latest edition to the promise.{something} family, unlike all the others (promise.all, promise.settleAll, promise.race) it will abort should any Promise resolve or reject. This is one of the final nails in the coffin of Promises helper libraries like ‘async’ and ‘BlueBird’
5. Experiment architectures outside of your comfort zone. Note how GraphQL is disrupting the traditional models
Great techniques exist in different paradigms that you can embrace without changing your architecture. Also, most companies have a variety of different apps/microservices types like data-driven search and reporting apps, others based on heavy logic and some are just streams of data. Why apply the same treatment to these different requirements? If all you have is a screwdriver, every challenge starts looking like a screw.
Ensure you’re familiar with layered architectures like n-tiers, DDD, Hexagonal/Onion/Clean. They look very different but their primary principle is smilar — isolating the domain (i.e. core data schema and business logic) from the surrounding tech (e.g. APIs, DB). Introduce yourself also to streaming style architectures which see a great increase in popularity. Then, spend some time with data-driven architectures that are best implemented nowadays with GraphQL frameworks.
Speaking of GraphQL, it’s interesting how some of its flavors disrupt the traditional separation between API and data-access layers, instead of repeating similar code and schemas twice these frameworks allow to declaratively define the entire app with one schema. This approach will greatly boost the go-to-market for data-driven apps which are not likely to embed complex logic.
Examples:
- This video by Dev Mastery about Clean Architecture is a gem. It also includes a starter example dev-mastery comments-api
- node-api-boilerplate is a great starter with DDD mindset
- Prisma server allows backend-less data-driven app
- Apollo server is GraphQL-first framework for building apps that is centered around Graph schemas
- express-graphql brings GraphQL merit without forcing to quit the comfy Express environment
6. Check out the winner of the 2019 oscar — Nest.js
After years of Express life, we need a little nest (js). With such amazing growth, you simply can’t ignore it. I would argue that Nest.js is the most remarkable thing that happened to Node.js in 2018/2019— for the first time, we have a full-fledge consensus framework like Java Spring and Python Django. Until 2018, teams without strong design skills had to architect their backends, spend a great time on plumbing and invent the wheel. Being one who engages with ~15 projects every year, believe me, I’ve seen so many types of wheels. Too many. My friend and colleague Gil Tayar funnily adapt the Anna Karenina principle to software: ‘All happy projects are alike; each unhappy project is unhappy in its own way.’
Unlike Express & co., Nest.js brings a full-fledged, batteries-included, framework (e.g. handles the data access layer, validation, etc). Its design style is highly ‘inspired’ by Angular — opinionated, TypeScript-based and embodies heavy modularization constructs. That said, it still offers great flexibility in choosing it’s sub-frameworks. Given all these goodies, I have no single doubt that teams doing their first steps with Node.js will move way faster with Nest.js rather with minimalist Express approach.
With all it’s greatness, it’s not flawless. One may doubt, is the heavy modularized Angular approach that was designed to ease the pain of huge frontend codebase suits the backend needs? aren’t we jumping too far from minimal Express to a huge and such an opinionated framework? are all of these heavy modularity features needed in a world of small Microservices? or the equivalent, isn’t it promoting monoliths (“I can easily handle 30,000 LOC in my code base”)?
At least we now have an option to choose from.
Examples:
- Nest.js official docs
- Quick ‘getting started’ example
- Quick overview of its philosophy and features
- I learned Nest.js using this course which I highly recommend (no affiliation of course)
7. Apply gradual deployment techniques like feature-flagging, canary or traffic shadowing
Have you heard about the epic Cloudflare downtime where a developer who wanted to experiment some feature in production rendered a big part of the internet down? Nothing will boost your confidence and speed than knowing that your deployment engine catches errors before your users do. A bunch of techniques will provide this magic. Each one achieves this in its own way but the overall idea is the same — serve the next version to a limited group of users and measure whether it seems stable. Going with this approach, we actually separating the deployment phase from the release phase. Some say it’s as important as testing, I suggest than anything that measures our pipeline is a TEST.
What are these techniques? Canary is the most well-known and simple. It tunes the routing so the next version is deployed and served to a group of users, starting from users are more likely to tolerate bugs (e.g. office employee, non-paying customers) and as the confidence grows it serves to more and more users. This might sound complex, but frameworks such as istio for K8S and AWS serverless handle most of the heavy lifting work. The next technique, feature flagging, is more powerful but also demands to get your hand dirty. It basically suggests wrapping a feature code with condition criteria that tell which users should benefit this new feature. Usually, it also comes with a dashboard for product managers to turn on and off features. This allows non-technical users to be part of the party and also support finer-grained advanced criteria. For example, using flags you may activate some experimental feature only for users from a specific city, on a specific machine instance that has a specific browser. One last super-interesting technique to look for is traffic shadowing which I’ll leave you to read about.
The value of these techniques is immense: unlike code-testing which demands great effort all the time, tuning your routers for canary deployment only happens once(!) and it also ‘test’ you code under realistic production environment. Learn about this fascinating world and plumb one of this technique into your pipeline
Examples:
- fflip is a minimalist and free feature flagging for Node.js
- Unleash is a rich feature flagging including a dashboard for product folks
- it’s easy to mess your code with feature flagging, read some best practices first
- Kubernetes istio greatly ease canary deployment set up
- With AWS serverless setting a canary is a breeze
- Intro to traffic shadowing
8. Shift your testing left — test more things and sooner
The shift left concept puts forward a sensible claim — the later a bug is discovered, the pricier it is to fix it. Consider a case where you discover a performance issue late on a staging environment, after short analysis it turns out that the fundamental DB data model must be changed — this is likely to incur significant code changes. Some researchers claim it might cost up to x640 times more when a bug is discovered too late on production. In plain words, the traditional model where a developer is focused on unit testing only and then weeks later the QA performs realistic E2E and advanced tests is slow and pricy. This well-known diagram brings this point home safely.
Test more things sooner, discover bugs early. How can we translate this idea into tangible development tasks? run a diversified set of tests as part of every commit and even during coding: component/api tests with real (in-memory?) DB just like you run unit tests, tests with realistic production input using dedicated property-based libraries, apply security scanners, run performance load tests and more. See below a list with dozens of tests one can run across the pipeline
Examples:
- Fast-check npm package for property-based testing allows invoking your units/API with many input permutations
- Check our framework and tools for scanning docker containers for CVEs like snyk, Trivy, Quay
- Tuning your real DB for in-memory operation without IO will make it practical to run api/component tests instantly almost like unit tests: this is how you would tune PostgreSQL (here is a ready-to-use dockerized version), mongodb-memory server will install and configure a local and real Mongo with in-memory engine.
9. Shift your testing right — test in/with production
‘Testing in production’ is a mega-trend in the testing community. It’s based on an idea called ‘shift-right’, which suggests that traditional tests on development and staging environment are less realistic and probably won’t prevent enough issues. The modern production has so many moving parts and parties, so many issues are likely to occur or get discovered only in production. Consequently, many tests must be conducted on the production environment itself for monitoring purposes but also to better test the future versions (e.g. serve some small traffic to the next version). The most straightforward production test is monitoring but many other advanced techniques exist like traffic shadowing, a/b tests (as a technical measure), load testing, tap-compare, soak testing and others.
So should we shift left or right? both. A modern approach for software delivery is not just thinking about tests rather about a pipeline. Given that many phases exist until the next version is served to the user — planning, development, deployment, release — each one is another opportunity to realize issues, stop, or build accumulating confidence. Code testing is a significant step on the pipeline, but plugging other tests into the pipeline will provide more confidence.
Examples:
- Masterpiece post: Testing in production the safe way
- My short video on traffic shadowing test with Node.js
- YouTube — Running E2E tests in production with Node.js
10. Be ready to use your new async pocket knife — worker threads
The most popular Node.js interview question might vanish soon: ‘is Node.js really single-threaded?’. As of version 11.7, we welcome a new family member in the async toolbox — worker thread. This tool, unlike any other, can address a very painful blindspot in Node. If 100% of the requests are CPU-intensive — no web framework, including Go & Java ones, can help tame this beast. However, a more popular workload is when only 1–10% of requests grabs the CPU for long time — most of the non-Node frameworks will prevent this automatically (thread per request). Node.js couldn’t — when serving 1000 req/sec, it’s enough for 1 to be CPU-intensive so all the other 999 suffer. There was no remedy to this pain, child process for examples are too slow to spin-up and can’t share memory. Good news, this is now tamable: worker threads can spin-up a dedicated event loop so the main one will remain snappy.
Now for some bad news — worker threads are not a lightweight thread that one spawn in no-time on demand. They actually duplicate the entire engine so it can become quite slow until they start running CPU-bounded requests will suffer additional delay. For this reason, consider a thread-pool (link below)
Examples:
- Quick hello-world
- An exhaustive intro to worker threads
- The official doc is quite short and beneficial for skimming through the API
- Thread pool implementation example
11. Deepen your Docker and Kubernetes understanding. It highly affects your Node.js code.
The DevOps storm means different things to different teams. For some, it is about making Dev perform also Ops work (e.g. being on-call), for others it’s more of a recommendation to plan early for production. At a minimum, it’s expected from developers to understand the production run-time as it highly affects the coding decisions and patterns. Mostly the decisions that sit on the intersection between Dev and Ops.
Few examples: it’s a well-known practice to ensure all outgoing requests are being replayed upon failures (the circuit breaker pattern), this can be done both on the infrastructure level using K8S Istio, or at the code itself using dedicated packages. Which one would you prefer and why? interesting choice, isn’t it? Let’s discuss other scenarios — K8S might kill and relocate pods, when it sends a kill signal the webserver might handle 2000 users. When a pod just crashes, they will quickly become angry 2000 users unless you implement a graceful and thoughtful shutdown. What is the grace period? well, this requires some Kubernetes learning, right? Sometimes the kill signals from K8S won’t even reach to your code if you use ‘npm start’ command, why? this requires some understanding of how Docker processes and signals are managed (the 1st link below will answer this question). One other interesting challenge is settling two contradicting things — how can test tools run within Docker containers during the pipeline but then removed before production? One last interesting example is configuring the allowed memory per container, given that v8 recently stopped limiting the heap size which will now keep growing as needed, this might interfere with K8S resource limits (common best practice) — make a decision and align the Node.js side with the K8S side
all of these challenges call you to dig deeper into the fascinating world of Docker clusters (or Serverless if you wish)
Examples:
- A masterpiece video by Bret Fisher on Node.js Docker best practices. Don’t miss this one!
- istio circuit breaker vs npm code-level circuit breaker
- Nice article on managing Node.js memory in a containerized environment by Ravali Yatham
12. Security: Learn to think like an attacker by skimming through vulnerable code examples
If you can’t think like an attacker, you can’t think like a defender. In 2020, you shouldn’t outsource the defense work to third-party companies or rely solely on static security scanners: The amount of attack types is overwhelming (The development pipeline and NPM are the latest trends). Developers training is the key — bake security DNA into yourself and your team and add a security touch to everything. A useful way to deepen your security understanding is to go through examples of vulnerable code and attack vectors. See below few example links that might greatly help
Examples:
- NodeGoat is a project that intentionally embodies security weaknesses for educational purposes. Don’t miss this doc page with attack examples
- Read my list of Node.js Security best practices which contain
13. Learn at least one: ELK or Prometheus
Monitoring is a crucial set up that should be well hardened and demands cooperation between Ops and Dev. No monitoring solution can be perfect without developers' involvement. These two popular monitoring systems, ELK and Prometheus, sound like sys admin toys but in fact, developers can learn a lot by configuring them. In any case, the mandatory activity for developers is being involved in exposing the metrics.
Ops folks know nothing about the event loop and how to monitor it (npm package does this), only you can propose and implement this important metric. Only developers can suggest the right V8 monitoring limits alerts. Developers might even write automated tests to ensure that when application errors are thrown — the right metrics are incremented. One another valuable activity is custom applicative metrics — coding some measurement of user activities can be very efficient in tracking production anomalies. Consider an e-commerce app, if the number of purchases is tracked and it suddenly drops dramatically in production — this is likely to imply some underlying issue
Examples:
- A post about first steps with Prometheus and Node.js
- Prometheus client library for Node.js — a great resource to learn about the metrics that are exposed by default
- A post about first steps with Node.js & ELK
- A comprehensive overview of ELK
- Read about the 4 monitoring ‘Golden signals’
- Read Google Site Reliability Engineering book, or at least the chapter on monitoring
14. Use machine learning as a black-box product
This bullet is targeted for machine learning (ML) newbies who work for products that don’t rely heavily on ML. If you aren’t one of those — feel free to step forward to the next bullet. So you’re like me clueless about ML, that’s fair, we intentionally chose not to build expertise on this field. Still, we can do much better if we just understand common ML needs and solutions so we consume those once a need arise. The JavaScript ML world has matured to a point where there are many stable libraries that can produce great value without intimate knowledge of the implementation. If we just understand WHAT they’re doing (+ how to configure )— we gain a special hammer to our toolbox. When this might prove to be valuable? say you sit in a meeting and the product manager mention something about organizing data (e.g. customers) into groups — suggest using cluster algorithms. Feeding the data into an adequate library might be enough to extract great insights. Often you’ll need to gain more knowledge to configure it correctly — that’s fair, hire an expert, become an expert, at least you knew where to start and structured the solution path. Does someone now ask about recommending things to the user? classify things? Find similarities between texts? predict? analyze audio or image? there is a lib for each one of those — pull out your weapon at the right moment
Obviously, better delve into the details and read the manuals. In no way, I’m suggesting a careless use of technologies. What I do propose however is that becoming familiar with the high-levels is better than knowing nothing and can build the motivation to keep exploring. Should I used ML taxonomy wrong above — please understand, I’ve just started my ML journey
Examples:
- ml.js — a swiss army knife of machine learning tools
- Brain.js specializes in neural networks, has great docs and a free video course
- Natural brings the world of NLP into Node land: text comparison and similarities, sentiment analysis, text classification and more
15. Sleep >7 hours a night. This matters far more than any technology you use and scientifically prooved to make you a better developer
This comes from Hillel Wayne and it’s one of the best tweets I’ve encountered in the last year :
your sleep quality and stress level matter far, far more than the languages you use or the practices you follow. Nothing else comes close: not type systems, not TDD, not formal methods, not ANYTHING.
It’s packed with examples and researches — I urge you to visit there and dig into those pearls of wisdom
Examples:
- Many software paradigms are not proven to be useful — TDD research here, clean architecture link. Other examples can be found within the Tweet
- Research: No clear evidence that a chosen programming language makes a different
- Research: Chronically getting less than 7 hours of sleep causes dramatic degradation on all mental tests
16. Quit Express, it’s aged and not maintained properly. Fastify and Koa are great candidates in 2020
Did you remember to wrap all your Express routes with try-catch, then move to the next() method and finally return some appropriate status to the user? If no, your process will crash without a trace. If yes, you just spent a great time on plumbing straight-forward pieces that add no value to your business. Isn’t this what frameworks are here for? Though Fastify & Koa won’t handle all the error paths for you (e.g. uncaught exceptions) they address this with a modern approach that requires less effort. They both also natively support async routes. Those are just a few examples where a modern and maintained framework could do better for you.
The last commit to the Express project was pushed somewhere 6 months ago… Since then Fastify & Koa saw dozens of builds and they keep improving. It’s frankly not appropriate for the Node.js ecosystem to rely heavily on a library that doesn’t keep in step with the times.
That said, most of the community tools and docs rely on Express. I hope to see community leaders, course makers, bloggers creating more content on its modern alternatives.
Examples:
17. Revisit these bullets from last year — some are still highly relevant
I’ve published a similar post in 2019 and many of the bullets seem important also in 2020. Here are some specific recommendations:
Examples:
- Bullet number #4 — “Plan how to utilize Async-Hooks to reach better tracing and context”
- Bullet number #11 — “Have a package update strategy. A lesson learned in 2018: updating too soon is a dangerous practice”
- Bullet number #17 — “Deepen your Linux OS understanding, focus on the anatomy of a Linux process”
- Bullet number #18 — “Dive deeper into the Node.js internals”
18. Enrich your CI with automated quality tools
Our journey for quality and safe deploys is usually centered around testing. The caveat of code-based testing (E.g. unit tests) is their price — every new functionality demands writing more testing code. This usually pays off but still painful. Some tools like linters, scanners, and static analyzers offer a different deal — for a one-time setup they will discover bugs forever. This is a great opportunity for lowering the price of building confidence, almost a free lunch. The list of tools is growing every year so keep following and enrich your CI — below I’ve included a few examples of modern tools.
Examples:
- Scan Docker containers for CVEs using tools like snyk, Trivy, Quay
- lockfile-lint will detect attempts to inject malicious dependencies using the npm lock file (e.g. edit a dependency URL within the lockfile)
- swagger-express-validator will ensure that your routes conform to the swagger schema
- eslint-plugin-import is an outstanding linter that performs dozens of checks on module and dependencies resolution. For example, it can warn when import/require is not at the beginning, disallow mutable exports with
varor
let, discoverextraneous packages that aren't declared with package.json and much more
- commitlint will enforce semantic commits which then can lead to automatic semantic versioning of Microservice and packages
- dependency-cruiser is a CLI tool that allows declaring flexible policies on allowed and disallowed dependencies. Using this you can craft custom rules like what licenses are allowed, allowed paths and more
19. Enrich your mindset, diversify your toolbox
We often surround ourselves with favorite technologies and ignore alternatives based on prejudice. Here are some typical sentences I hear in my network: ‘Functional programming is not practical’, ‘REST API is dead, ‘TDD is not for me’, ‘ORMs are evil’, ‘TypeScript is too verbose’.
These are false-dichotomies — it’s not a binary question, all these paradigms embody many different ideas, and still, we tend to pick all or ignore all. For example, Functional Programming currying and monads feel weird? that’s fair, consider other more mainstream FP ideas like pure functions. Ignoring TypeScript because OOP is not your style? maybe use only its type system and stick to vanilla JS objects and functions. Cherry-pick ideas and features, not a package.
How exactly do I plan to diversify my stack in 2020? I’ll probably use Fastify for the web layer, with a mix of REST and GraphQL. The data access layer will constitute some lightweight ‘ORM’ but only for migrations and connection pooling (no dichotomy, I’m picking the right ORM features for me). As for the DB, I plan to use a relational DB mixed with JSON columns. My coding style is based on simple and flat vanilla JavaScript objects — but I usually mix it with some classes when appropriate and keep most of my functions pure. The overall architecture style will be centered around Microservices but maybe in a monorepo — I’m not obliged to pick all the Microservice bells and whistles, right?. As of testing, I definitely want to run TDD-style iterations of refactoring for my code, but not necessarily code the tests first — I pick the TDD features that suit my style. What type of testing? mostly component tests (i.e. api) but mix this with unit testing to cover parts with heavy logic.
By no mean, I suggest that this is the best stack. It is, however, a diversified stack that mixes and matches multiple ideas from many paradigms. Obviously assemble your own stack, just don’t be afraid of tiptoeing into unexplored territory and get inspiration from many sources of wisdom.
p.s. I’m not advocating for becoming a jack of too many trades. Actually mastering some technologies is important. My point is being pragmatic and open to great ideas. Don’t be “that screwdriver guy”, enrich your mindset, diversify your toolbox
20. Get inspiration from these great 5 starter projects
Starter (boilerplate) projects are a genuine source for knowledge — just skim through the code for 10–20 min and get many ideas to embrace. I’ve packed here below some quality starters, each brings some unique approach so you enrich your mindset with new paradigms
Examples:
- node-api-boilerplate is a great showcase for DDD with an application layer that demonstrates organizing code by feature
- dev-mastery comments-api is an excellent translation of clean architecture to Node.js and it comes with this super explainer video
- Typescript-starter won’t teach you any architecture concepts but a nice showcase for TypeScript set up with modern libraries and great docs
- nodejs-api-starter is the starter for those who seek a real-world GraphQL implementation including errors and auth
- bulletproof-nodejs is a well-known starter that uses the 3-tier folder structure which is my personal and recommended way of structuring a Node.js app
📗 Liked the content here and want to get 10+ hours course on Node.js quality and testing? Visit my online course ‘Testing Node.js & JavaScript From A To Z’
Thank You. Other articles you might like
- 23 Node.js security best practices
- 45 JavaScript testing best Practice
- 85 Node.js best practices
- My testing workshop
⭐ Want more? follow me on Twitter⭐ | https://yonigoldberg.medium.com/20-ways-to-become-a-better-node-js-developer-in-2020-d6bd73fcf424 | CC-MAIN-2021-21 | refinedweb | 5,487 | 52.9 |
Introduction
In this lesson, we will learn how to drive an active buzzer with a PNP transistor to make sounds.
Experimental Conditions
– 1*Raspberry Pi
– 1*Breadboard
– 1*Network cable (or USB wireless network adapter)
– 1*Buzzer (Active)
– 1*NPN transistor (8050)
– 1*Resistor (1KΩ)
– Jumper wires
Experimental Principle experiment,.
Experimental Procedures
Step 1: Connect the circuit as shown in the following diagram (Pay attention to the positive and negative poles of the buzzer)
Step 2: Edit and save the code with vim (see path/Rpi_UniversalStartKit/05_beep/beep.c)
Step 3: Compile the code
gcc beep.c -lwiringPi
Step 4: Run the program
./a.out
Now, you should hear the buzzer make sounds.
Further Exploration
If you have a passive buzzer in hand, you can replace the active buzzer with it. So you can make it sound “do re mi fa so la si do” through programming as long as you have some programming foundation and enough patience.
beep.c
#include <wiringPi.h> #include <stdio.h> #define BEEP 0 int main(void) { if(wiringPiSetup() == -1){ printf("setup wiringPi failed !"); return 1; } pinMode(BEEP, OUTPUT); while(1){ digitalWrite(BEEP, !digitalRead(BEEP)); delay(1000); } return 0; }
Python Code
#!/usr/bin/env python import RPi.GPIO as GPIO import time BeepPin = 11 # pin11 def setup(): GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location GPIO.setup(BeepPin, GPIO.OUT) # Set BeepPin's mode is output GPIO.output(BeepPin, GPIO.HIGH) # Set BeepPin high(+3.3V) to off() | https://learn.sunfounder.com/lesson-5-buzzer-7/ | CC-MAIN-2021-39 | refinedweb | 244 | 60.51 |
simark added a comment. I think I managed to make some tests by using the `MockCompilationDatabase`. Basically with some code like:
#ifndef MACRO static void func () {} // 1 #else static void func () {} // 2 #endif and these steps: 1. Server.addDocument(...) 2. Server.findDefinitions (assert that it returns definition 1) 3. CDB.ExtraClangFlags.push_back("-DMACRO=1") 4. Server.reparseOpenedFiles() 5. Server.findDefinitions (assert that it returns definition 2) Right now that test fails, but it's not clear to me whether it's because the test is wrong or there's really a bug in there. I'll upload a work-in-progress version. ================ Comment at: clangd/ClangdServer.cpp:541 +std::vector<std::future<void>> +ClangdServer::reparseOpenedFiles() { ---------------- ilya-biryukov wrote: > We're not returning futures from `forceReparse` anymore, this function has to > be updated accordingly. Indeed, I found this by rebasing. Repository: rCTE Clang Tools Extra _______________________________________________ cfe-commits mailing list cfe-commits@lists.llvm.org | https://www.mail-archive.com/cfe-commits@lists.llvm.org/msg82780.html | CC-MAIN-2018-26 | refinedweb | 154 | 50.33 |
Let's make our
react-native app work in the browser, the right way.
This tutorial was last tested on
react-native@0.61.x. If you are using a different version, some steps might need a little tweak
The code from this tutorial is available on GitHub: brunolemos/react-native-web-monorepo
You can fork it and use to start new projects with code sharing 🎉
Why am I writing this?
Hi 👋 I'm Bruno Lemos. I recently launched a project called DevHub - TweetDeck for GitHub and one of the things that caught people's attention was the fact that it is an app made by a single developer and available on 6 platforms: Web (react-native-web), iOS (
react native), Android (
react native), macOS, Windows and Linux (
electron, for now), with almost 100% code sharing between them. It even shares some code with the server! This is something that would require a team of 3+ until a couple years ago.
Since then, I've received dozens of tweets and private messages asking how to achieve the same and in this tutorial I'll walk you through it.
What's
react-native-web?
If you are not familiar with react-native-web, it's a lib by Necolas (ex Twitter engineer) to make your
React Native code render in the browser. Roughly speaking, you will write
<View /> and it will render
<div />, making sure all styles render the exact same thing. It does more than that, but let's keep it simple.
The new Twitter was created using this technology and it's awesome.
If you already know
react-native, you don't need to learn any new syntax. It's the same API.
Summary
- Starting a new
React Nativeproject
- Turning our folder structure into a monorepo
- Making
react-nativework in a monorepo
- Sharing code between our monorepo packages
- Creating a new web project using
create-react-appand
react-native-web
- Making
CRAwork inside our
monorepowith code sharing
- ???
- Profit
Step-by-step tutorial
Starting a new
React Native project
$ react-native init myprojectname
$ cd myprojectname
$ git init && git add . -A && git commit -m "Initial commit"
Note: It's much easier to create a cross platform app from scratch than trying to port an existing mobile-only (or even harder: web-only) project, since they may be using lot's of platform specific dependencies.
EDIT: If you use expo, it seems they will soon have built in support for web!
Turning our folder structure into a monorepo
Monorepo means having multiple packages in a single repository so you can easily share code between them. It's a bit less trivial than it sounds because both
react-native and
create-react-app require some work to support monorepo projects. But hey, at least it's possible!
We'll use a feature called
Yarn Workspaces for that.
Requirements: Node.js, Yarn and React Native.
- Make sure you are at the project root folder
$ rm yarn.lock && rm -rf node_modules
$ mkdir -p packages/components/src packages/mobile packages/web
- Move all the files (except
.git) to the
packages/mobilefolder
- Edit the
namefield on
packages/mobile/package.jsonfrom
packagenameto
mobile
- Create this
package.jsonat the root directory to enable
Yarn Workspaces:
{ "name": "myprojectname", "private": true, "workspaces": { "packages": [ "packages/*" ], "nohoist": [] } "dependencies": { "react-native": "0.61.3" } }
- Create a
.gitignoreat the root directory:
.DS_Store .vscode node_modules/ yarn-error.log
$ yarn
Making react-native work in a monorepo
Check where
react-nativegot installed. If it was at
/node_modules/react-native, all right. If it was at
/packages/mobile/node_modules/react-native, something is wrong. Make sure you have the latest versions of
nodeand
yarn. Also make sure to use the exact same version of dependencies between the monorepo packages, e.g.
"react": "16.11.0"on both
mobileand
components, not a different version between them.
Open your favorite editor and use the
Search & Replacefeature to replace all occurrences of
node_modules/react-native/with
../../node_modules/react-native/.
For react-native <= 0.59, open
packages/mobile/package.json. Your
startscript currently ends in
/cli.js start. Append this to the end:
--projectRoot ../../.
Open
packages./mobile/metro.config.jsand set the
projectRootfield on it as well so it looks like this:
const path = require('path') module.exports = { projectRoot: path.resolve(__dirname, '../../'), transformer: { getTransformOptions: async () => ({ transform: { experimentalImportSupport: false, inlineRequires: false, }, }), }, }
- [Workaround] You currently need to add the
react-nativedependency to the root
package.jsonto be able to bundle the JS:
"dependencies": { "react-native": "0.61.3" },
iOS changes
$ open packages/mobile/ios/myprojectname.xcodeproj/
- Open
AppDelegate.m, find
jsBundleURLForBundleRoot:@"index"and replace
indexwith
packages/mobile/index
- Still inside Xcode, click on your project name on the left, and then go to
Build Phases>
Bundle React Native code and Images. Replace its content with this:
export NODE_BINARY=node export EXTRA_PACKAGER_ARGS="--entry-file packages/mobile/index.js" ../../../node_modules/react-native/scripts/react-native-xcode.sh
$ yarn workspace mobile start
You can now run the iOS app! 💙 Choose one iPhone emulator and press the "Run" triangle button inside Xcode.
Android changes
$ studio packages/mobile/android/
- Open
packages/mobile/android/app/build.gradle. Search for the text
project.ext.react = [...]. Edit it so it looks like this:
project.ext.react = [ entryFile: "packages/mobile/index.js", root: "../../../../" ]
- Android Studio will show a Sync Now popup. Click on it.
- Open
packages/mobile/android/app/src/main/java/com/myprojectname/MainApplication.java. Search for the
getJSMainModuleNamemethod. Replace
indexwith
packages/mobile/index, so it looks like this:
@Override protected String getJSMainModuleName() { return "packages/mobile/index"; }
If you get the
Cannot get property 'packageName' on null objecterror, try disabling auto linking
You can now run the Android app! 💙 Press the "Run" green triangle button inside Android Studio and choose the emulator or device.
Sharing code between our monorepo packages
We've created lots of folders in our monorepo, but only used
mobile so far. Let's prepare our codebase for code sharing and then move some files to the
components package, so it can be reused by
mobile,
web and any other platform we decide to support in the future (e.g.:
desktop,
server, etc.).
- Create the file
packages/components/package.jsonwith the following contents:
{ "name": "components", "version": "0.0.1", "private": true }
[optional] If you decide to support more platforms in the future, you'll do the same thing for them: Create a
packages/core/package.json,
packages/desktop/package.json,
packages/server/package.json, etc. The name field must be unique for each one.
Open
packages/mobile/package.json. Add all the monorepo packages that you are using as dependencies. In this tutorial,
mobileis only using the
componentspackage:
"dependencies": { "components": "0.0.1", ... }
- Stop the react-native packager if it's running
$ yarn
$ mv packages/mobile/App.js packages/components/src/
- Open
packages/mobile/index.js. Replace
import App from './App'with
import App from 'components/src/App'. This is the magic working right here. One package now have access to the others!
- Edit
packages/components/src/App.js, replace
Welcome to React Native!with
Welcome to React Native monorepo!so we know we are rendering the correct file.
$ yarn workspace mobile start
Yay! You can now refresh the running iOS/Android apps and see our screen that's coming from our shared components package. 🎉
$ git add . -A && git commit -m "Monorepo"
Web project
Note: You can reuse up to 100% of the code, but that doesn't mean you should. It's recommended to have some differences between platforms to make them feel more natural to the user. To do that, you can create platform-specific files ending with
.web.js,
.ios.js,
.android.jsor
.native.js. See example.
Creating a new web project using CRA and react-native-web
$ cd packages/
$ npx create-react-app web
$ cd ./web(stay inside this folder for the next steps)
$ rm src/*(or manually delete all files inside
packages/web/src)
- Make sure the dependencies inside
package.jsonare the exact same between all monorepo packages. For example, update the "react" version to "16.9.0" (or any other version) on both
weband
mobilepackages.
$ yarn add react-native-web react-art
$ yarn add --dev babel-plugin-react-native-web
- Create the file
packages/web/src/index.jswith the following contents:
import { AppRegistry } from 'react-native' import App from 'components/src/App' AppRegistry.registerComponent('myprojectname', () => App) AppRegistry.runApplication('myprojectname', { rootTag: document.getElementById('root'), })
Note: when we import from
react-nativeinside a
create-react-appproject, its
webpackconfig automatically alias it to
react-native-webfor us.
- Create the file
packages/web/public/index.csswith the following contents:
html, body, #root, #root > div { width: 100%; height: 100%; } body { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }
- Edit
packages/web/public/index.htmlto include our CSS before closing the
headtag:
... <title>React App</title> <link rel="stylesheet" href="%PUBLIC_URL%/index.css" /> </head>
Making CRA work inside our monorepo with code sharing
CRA doesn't build files outside the
src folder by default. We need to make it do it, so it can understand the code from our monorepo packages, which contains JSX and other non-pure-JS code.
- Stay inside
packages/web/for the next steps
- Create a
.envfile (
packages/web/.env) with the following content:
SKIP_PREFLIGHT_CHECK=true
$ yarn add --dev react-app-rewired
- Replace the scripts inside
packages/web/package.jsonwith this:
"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-app-rewired eject" },
- Create the
packages/web/config-overrides.jsfile with the following contents:
const fs = require('fs') const path = require('path') const webpack = require('webpack') const appDirectory = fs.realpathSync(process.cwd()) const resolveApp = relativePath => path.resolve(appDirectory, relativePath) // our packages that will now be included in the CRA build step const appIncludes = [ resolveApp('src'), resolveApp('../components/src'), ] module.exports = function override(config, env) { // allow importing from outside of src folder config.resolve.plugins = config.resolve.plugins.filter( plugin => plugin.constructor.name !== 'ModuleScopePlugin' ) config.module.rules[0].include = appIncludes config.module.rules[1] = null config.module.rules[2].oneOf[1].include = appIncludes config.module.rules[2].oneOf[1].options.plugins = [ require.resolve('babel-plugin-react-native-web'), ].concat(config.module.rules[2].oneOf[1].options.plugins) config.module.rules = config.module.rules.filter(Boolean) config.plugins.push( new webpack.DefinePlugin({ __DEV__: env !== 'production' }) ) return config }
The code above overrides some
create-react-app's
webpackconfig so it includes our monorepo packages in CRA's build step
$ git add . -A && git commit -m "Web project"
That's it! You can now run
yarn start inside
packages/web (or
yarn workspace web start at the root directory) to start the web project, sharing code with our
react-native
mobile project! 🎉
Some gotchas
react-native-websupports most of the
react-nativeAPI, but a few pieces are missing like
Alert,
Modal,
RefreshControland
WebView;
- If you come across a dependency that doesn't work well with the monorepo structure, you can add it to the nohoist list;
Some tips
- Navigation may be a bit of a challenge; you can use something like react-navigation which recently added web support or you can try using two different navigators between and mobile, in case you want the best of both worlds by compromising some code sharing;
- If you plan sharing code with the server, I recommend creating a
corepackage that only contain logic and helper functions (no UI-related code);
- For Next.js, you can check their official example with react-native-web
- For native windows, you can try react-native-windows;
- For native macOS, you can the new Apple Project Catalyst, but support for it is not 100% there yet (see my tweet);
- To install new dependencies, use the command
yarn workspace components add xxxfrom the root directory. To run a script from a package, run
yarn workspace web start, for example; To run a script from all packages, run
yarn workspaces run scriptname;
Thanks for reading! 💙
If you like react, consider following me here on Dev.to and on Twitter.
Links
- Source code: react-native-web-monorepo
- DevHub: devhubapp/devhub (production app using this structure + Desktop + TypeScript)
- Twitter: @brunolemos
Posted on by:
Bruno Lemos
Open Source contributor. Software Engineer mostly using React Native, TypeScript, Redux & GraphQL. 💙
Discussion
HELP! something changed and i cannot replicate this tutorial anymore. i cannot get past the first time you are testing android studio. I remember something like --version react-native@next that is now missing from this tutorial. and now i cannot replicate it at all some one please help.
this is now the 7th time im following the instructions and i get this error first time i try test in the android simulator after trying to create monorepo
Unable to resolve module `./packages/mobile/index
Hi, I updated the tutorial with the latest changes from
react-native@0.59, search for
projectRootto see the updated step involving the file
metro.config.js.
thank you so much for the new changes in the tutorial. i made the changes to the metro.config.js just like you suggested and i can now run it on android. i will continue with the rest of the tutorial in the morning.
Hey Bruno how are you?
Im still running into a issue. Soon as i complete the web section of the tutorial. my mono repo breaks for mobile. it installs all the modules in packages/mobile/node-modules instead of root/node_modules.
Thus when I run packages/mobile/yarn start i get the following error
"Error: Cannot find module 'E:\2019_PROJECTS\moco-messenger-project\code\repo\test\node_modules\react-native\local-cli\cli.js'"
I dont understand how the web project is affecting the mobile project. Please assist.
kind regards
Make sure you have the correct content inside the root
package.jsonand you used
yarnat the root directory to install the dependencies, not inside each package neither
npminstead of
yarn.
Compare your code with the repository to see if anything is different: github.com/brunolemos/react-native...
hey bruno,
I just did like you said, I even upgraded react-native to v0.59.0 stable. yet still when i run yarn in the root it still installs packages/mobile/node-modules and not in root/node_modules.
how can i compare an entire project with difference in vs code? are you sure there isnt a step missing? I have tried 3 times now following your exact instructions.
Do you have the latest version of nodejs and yarn? How is your root package.json?
I just checked on my computer, im running yarn 1.130 and node v10.0.0 i believe those are the latest versions.
my root package.json file looks exactly like yours.
{
"name": "myprojectname",
"version": "0.0.1",
"private": true,
"workspaces": {
"packages": [
"packages/*"
]
}
}
like i said im extremely confused becasue i dont understand why the monorepo breaks when i add the web
i just downloaded your project at
github.com/brunolemos/react-native... and when i run yarn in the root it is also installing the packages in the wrong places.
Hey everyone, I downloaded the project, followed the updated tutorial and ran into the same exact issue. I got
/mobilerunning again by updating the relative filepath in its package.json to the react-native-cli:
good luck!
Hey, you both were right! React Native started getting installed inside
packages/mobile/node_modules, which is wrong. Changing the path is not the right solution though.
I investigated and you need to make sure all your dependencies have the exact same version between the monorepo packages. For example, change your
"react"dependency inside the
mobileand
web's
package.jsonto the exact same version (e.g.
16.8.4).
This will make react-native get installed in the root
node_modulesagain and also prevent multiple instances of react being installed in the same project, which would cause all kinds of bugs.
Updated the tutorial and also the repository: github.com/brunolemos/react-native...
Hi Bruno,
How to use 3rd lib, I want to add
react-native-elementpackage.
It's work well on mobile, but when I run web app, it's error below:
Here's what I added to
config-override.json
packages/web
In future, I will add react-navigation and some other packages.
Please help, many thanks!
Did you make it work?
I haven't tried your code but yes, changing
config-override.jscorrectly should be enough.
Was anyone able to add react-navigation to the project? I got react-native-elements working by following the above comment.
Here's a working example for React-Navigation with web :
github.com/react-native-elements/r...
Thank for documenting all this work thoroughly.
As a React-Native noob, this guide was very easy to follow along ! Cheers!
I got react-navigation's drawer working on the web.
The following is my config-override.js
thanks for the input
i am facing similar issue while using GoogleSigninButton from react-native-google-signin.
i tried adding require.resolve('@babel/plugin-proposal-class-properties') as you suggested below.
also tried to update babel.config.js with the following, didnt worked as well...
module.exports = {
plugins: [
[
'@babel/plugin-proposal-decorators',
{
legacy: true,
},
],
[
'@babel/plugin-proposal-class-properties',
{
loose: true,
},
],
'@babel/plugin-syntax-dynamic-import',
'@babel/plugin-transform-regenerator',
[
'@babel/plugin-transform-runtime',
{
helpers: false,
regenerator: true,
},
],
],
presets: ['@babel/preset-flow', 'module:metro-react-native-babel-preset'],
}
also tried with loose: true
require.resolve('@babel/plugin-proposal-class-properties', {
loose: true,
}),
any suggestion please?
thanks for you time.
Hi Oz, were you able to make it run? Did you try with a compatible release (any before 0.60)?
Hi Nishant,
Unfortunately I was not able to solve it.
I am not sure about earlier versions but I went over many possible suggestions, none of them worked...
Any additional idea that I can try?
Thanks for the reply
Use this config to fix the issue
Add the above code before the
return configline
Thanks Rajendran
i tried adding the above as part of config-overrides.js
it didn't helped.
BTW, i`ve executed 'sudo yarn add @react-native-community/google-signin'
Under the folder 'react-native-web-monorepo/packages/components'
Is that the right location?
Thanks, Oz
An update...
i had to add two more dev dependencies under the web module.
sudo yarn add --dev babel-loader
sudo yarn add --dev @babel/preset-flow
now i am getting different error:
/react-native-web-monorepo/node_modules/@react-native-community/google-signin/src/GoogleSigninButton.js
Attempted import error: 'requireNativeComponent' is not exported from 'react-native'.
With the react-native-version 0.60.4, I have some problems with libhermes.
When starting the android-app, it crashes and I always get the message: E/SoLoader: couldn't find DSO to load: libhermes.so. Any suggestions what to do?
Edit: Fixed my problem. You have to enable hermes, so that it looks like this in your build.gradle in app:
project.ext.react = [
entryFile: "packages/mobile/index.js",
root: "../../../../",
enableHermes: true, // clean and rebuild if changing
]
This works for me thanks!
You can run debug session from vscode with React Native Tools extension. But with monorepo its little hacky... btw, read-native run-its --project-path "./packages/mobile/ios" also work
I setup only iOS project with macos: you need to specify "runArguments": ["--project-path", "./packages/mobile/ios"] in debug task in launch.json and symlink with command:
~if somebody already setup android debug, please ping me~
Update:
in vscode task for android add
Thanks for sharing!
Hi Bruno, thanks for the awesome detailed tutorial with all the updates. And i can see you are very active in comments also which is awesome!
Its really nice to see react's progress towards PWA and cross platform portability.
I am following this tutorial to convert our old add(on Rn 0.59) over to react-native web. I followed this tutorial and setup everything up.
Than i copied the dependencies from our mobile repo's package json to packages/components/package.json. And all other code respectively in src. Idea was to get everything running on ios in this monorepo setup and than go from there to fix whatever needs to be fixed for web.
But i am getting some errors like first i got:
bundling failed: Error: Unable to resolve module
pathfrom
/Users/..../projec/node_modules/react-native-dotenv/index.js: Module
pathdoes not exist in the Haste module map
Fixed it by adding
pathexplicitly in dev-dependencies. Than started getting am not very experienced in react and react-native, i am mainly on Ruby on Rails, so maybe this is something basic which i am getting wrong.
I found: stackoverflow.com/a/39046690/4738391 which suggests omething wrong with node environment or something. But i am a bit confused, i mean i can add these dependencies etc but it should work out of the box for mobile, as it was working fine in previous repo.
Any help will be greatly appreciated. Thanks.
After cache clean and everything, second error changed to: was running into the same issue and I think I figured out the cause of the problem. I unfortunately don't know how to fix it. It seems to be related to react-native-cli not being able to locate the metro and babel configs because it's being run from the root of the repository.
Since they aren't found, when the bundler comes across react-native-dotenv within a source file it will actually import the source file rather than using the replacement provided by the babel plugin.
This was a stupid error, i had forgot to add
'module:react-native-dotenv'in my babel config presets. Adding it solved the problem and i got my mobile app compiled. There were some imports fixes etc in scode needed to be done to run app successfully. But that is done.
But now next errors(on web), i posted this SO question: stackoverflow.com/questions/571953...
If i can get any help, would be great.
Please remove all node_modules folders and .lock files from your project, clear all caches (xcode, —reset-cache, etc), and try following the steps again. Maybe you missed something.
You shouldn’t remove the dependencies from mobile. Check this repo source code and commit diffs: github.com/brunolemos/react-native...
After running yarn to install dependencies, check the contents of packages/mobile/node_modules, and let me know which folders it has. It shouldn’t have any, all should be in the root node_modules.
If nothing works, maybe they released a new version of the cli that broke something, in that case you can use a previous version or investigate the change.
I think i was not clear in my comment, actually it did work with barebone setup as described in this post. It was working perfectly, than i started exporting my mobile code, that's when it exploded.
I wanted to just have mobile app running as it is in this architecture. Than move un-convertable code to mobile and write replacement code for only those in web. But my mobile app is not running with these errors.
I did all the cache clear and everything but same issue. mobile repo's node_modules folder have 2 folder, .bin and metro-react-native-babel-preset.
I am pretty sure it is some of my mobile dependency. I don't know if i should share the package json etc and everything here. It will just get annoyingly long here.
Let me know if i should share that here, or i can reach you through some other medium.
I do understand this blog post is like THE go to blog right now for new projects which want to take this route. but porting old projects is a lot more messy. If i do succeed in porting my app on this architecture and support web, i will leave pointers and can also write an extension of this blog post.
Really great stuff, we learn a lot!
Here is what we wrote on somewhat the same topic.
reily.app/posts/2019-02-25/firebas...
It was too much trouble to set up both Android, iOS and their native dependencies in the mono repo structure.
So we decided to just
nohoisteverything. T_T
Nice, thanks for the mention in the article!
Were you able to share code between web and mobile using nohoist? I've had problems with this approach in the past but I don't remember exactly why. It has some downsides but it's definitely much simpler to setup. Everything working well for you this way?
No, sry for taking so long to reply.
Our yarn workspace is just set up to include app / backend / website
And they do not share components.
The problem is that metro does not support symbol links. Which is what yarn workspace uses.
github.com/facebook/metro/issues/1
throws error error: unknown option `--projectRoot'
On modifying
--projectRoot
to
--projectRoots
I get following error
Loading dependency graph...jest-haste-map: Watchman crawl failed. Retrying once with node crawler.
You mean when trying to use jest? If not please check the repository to see what you made differently.
Sorry, I modified my comment. I am getting an error with --projectRoot. I was trying on my own repo. I'll be cloning your repo and then let you know if the problem persists.
I'm using the unreleased react-native 0.59 in this tutorial, some dependencies got a major bump so maybe there are some differences if you are using an older version.
did you find an alternative for --projectRoot please ?
Number of issues here:
Changing
jsBundleURLForBundleRoot:@"index"to
jsBundleURLForBundleRoot:@"packages/mobile/index"leads to resolution errors
Leaving it as it is, leads to
@babel/runtime/helpers/interopRequireDefault does not exist in the Haste module map. It looks like the packages/mobile/index reference is the way to go but that the react-native command uses packages/mobile as the ref location instead of the project root. From the root I tried two commands (RN 0.59):
mobile: start => ../../node_modules/.bin/react-native start --reset-cache
root: start => cd ./packages/mobile && yarn start
root: start => yarn workspace mobile start
In both cases, I get "Unable to resolve module
./packages/mobile/indexfrom
/Users/me/projects/rnw/packages/mobile/.
[...]
`Indeed, none of these files exist:
/Users/me/projects/rnw/packages/mobile/packages/mobile/index
Notice the duplicate packages/mobile reference
Ok, I identified the problem. The
packages/mobile/metro.config.jsis not processed. The projectRoot remains
packages/mobileinstead of ``
Hi,
I'm facing the same problem. Did you manage to solve why the
metro.config.jswasn't processed?
Current solution is to set
--projectRoot ../../at the
package.jsonstart script instead of
metro.config.js, like it used to be before. Not sure if it's a bug or not.
Having some troubles getting react-native-web hoisted and getting everything to run. It insists on staying inside the web/node_modules together with
fbjsand
react. I do have some nohoist packages that are linked in the mobile project. I verified all the version numbers. They seem to be aligned
Tried various cleaning actions. I'm getting errors from hoisted elements not being able to find
react-native-webshouldn't
metro-react-native-babel-presetbe implemented as a preset in the web project? This seems to be indicated in
react-native-webexamples
You need to use the exact same version of react between all package.json that have it.
Hey, thanks for your awesome tutorial. Just a quick question, how can we host the web version of the app? Cause it seem like it share the file inside the
packages/component/srcfolder. I using Docker, is it mean that we need to add all files into the server?
The web package has a
buildcommand, and the result goes to the
packages/web/distfolder. You should deploy only the
distfolder.
I see.. thanks bro.. thats help a lot
Hi Bruno,
Great tutorial. Thanks for sharing.
Is it possible to maintain the each platform code in 3 different repo. Already I am having iOS and Android project. Now i would like to add some modules in react_native and integrate in iOS and Android. The thing is when the iOS and Android are inside the react-native root repo that is working fine. Linking also happening. But when I separate the iOS folder and when try to install the Pod i am getting issue as "cannot find module react_native/cli" in use_native_modules.
Kindly help me.
Thanks Bruno for this awesome post!! It was the only way I was able to make react-native work within a monorepo structure.
Currently I am working on a web + ios + tvos app and I was wondering how should I configure the tvos app since it react-native relies on npm:react-native-tvos@0.62.2-0. Following your tutorial I have:
1) Added 'react-native' and 'react-native/**' into tv package.json noHoist in order to get the react-native stored within the tv package and not use the ios hoisted one.
2) Use your metro.config.js configuration but also added the extraNodeModules in order to override the react-native alias to use the tv package one:
3) Change the AppDelegate.m file with your configuration
4) Within the
Bundle React Native code and Imagessection I have added the
EXTRA_PACKAGER_ARGSbut kept the react-native path as it is in order to use the tv package one:
Is this okay? Am I missing something else?
Thank you very much, your post is awesome <3!
Hello Bruno, awesome tutorial as I mentioned!
I have another question though, and it's related to builds. I've set the build phase as Release (so I can run it without a server) but I get an error in Xcode:
File /Users/--/Library/Developer/Xcode/DerivedData/project-name/Build/Products/Release-iphoneos/project-name.app/main.jsbundle does not exist. This must be a bug with'
Is there anything special I need to set here to get Xcode to build it?
No, this error is unrelated to this tutorial. Try cleaning the caches, e.g. Product > Clean and yarn start --reset-cache.
Thank you cheers! I had thought it was something related to the workspace edits. Turns out there's an issue in react-native about github.com/facebook/react-native/i....
So how did you fix it? I have the same issue. The GitHub issue link you provided is not working for me :-/
Thanks for the post! I have been able to get it going without any problems using the outlined steps.
I am facing problems however when i try to install 3rd party dependencies after getting the initial setup going. It will be great if the post could be updated with steps on how to install dependencies post setup.
For example i wanted to add
react-native-gesture-handlerand a few other native libraries but somehow i keep getting some issue or the other. I tried
yarn workspace components add react-native-gesture-handlerand it installs but i am unable to use it since i get IDE errors about some constants not being found. Similar issues with other libraries as well. Auto-linking somehow doesn't seem to reflect.
Should
jettifierbe installed and added in the
post-installof
package.json(and if so which
package.json- root or the ones inside the packages) if running commands like
yarn workspace mobile start? Basically some tips on how to add 3rd party libraries for both mobile and web will really help. Thanks again for the post - its my first attempt at a monorepo and this post really helped iron out all my initial doubts but i am also obviously making some newbie/rookie mistakes so there are some stumbling blocks to really get started with it.
Ok. so with a few more attempts i got it going for a critical dependency in my packages. I am using the versatile
Navigationrouter (github.com/grahammendick/navigation) for all the routing requirements in all my packages, across all the router's supported platforms (which is basically everything web, mobile, native etc).
After following all the steps in the post i initially installed the router into my equivalent of the
componentspackage. I got it to work for the web but, for the
react-nativeimplementation, the navigation router has native code for
Androidand
IoSand somehow it wasn't getting auto-linked. The solution was to simply install it to my equivalent of the
mobilepackage and everything seems good! im still not sure of the
jettiferpost-install step but it should not be an issue i think.
Thanks a lot for this great tutorial.
i`ve probably missing it in the comments but i am not sure what pakage.json i should use for adding additional dependencies.
should i only update the root /package.json
or individually also
in addition, only yarn should be used?
Thanks again.
Yes only yarn because npm doesn’t have the “workspaces” feature.
You’ll add the dependencies in the package that’s using them. Most of it will probably be in the components. Don’t add at the root unless it’s things like lint etc.
Sir, will
createBrowserApp(switchNavigator, { history: 'browser' })work when I host a React Native Web app on GitHub Pages to have such these URLs:
Is it possible on GitHub Pages with React Native Web?
I recently worked on a project which used
monorepo. It was my first introduction to it. I must say, I was not impressed. But hear me out. I've worked in the mobile app industry for over 10 years. I've seen architectures come and go.
Conceptually, I understand the use case for implementing such a design. In practice, I found it unintuitive, incredibly confusing, and slowed my project onboarding process to a crawl. I had six weeks to perform the job for which I was hired. The first week was spent wrapping my head around how to simply walk through the workflows. That cost the client a lot of money and reduced my available billable time by 20%. Imagine what would happen if the client had to onboard a less-experienced dev.
To be fair, there are a lot of unknowns here. It was my first hands-on with the design. Maybe the client's architect built it incorrectly? Would my experience have improved had the repo been better documented, i.e. had any doc at all? I don't really know.
I'm off that project and on my way to others. I will withhold judgment for now because this project could've been a fluke. I just wanted to interject my experience. For any non-trivial project, it's important for readers to remember that the business drives technology decisions. If a monorepo design pattern solves the particular business requirement, then I hope this tutorial helps you jumpstart your project.
Hi man, absolutely amazing tutorial, my dev team managed to get it up an running in no time.
However, we are facing two problems, one is related to babel plugins, no matter what i did, i could not add the @babel/plugin-transform-react-jsx, therefore the web package crashes:
The other problem comes with
react-native-vector-icons: ^7.0.0, we added the:
but we could not get them to render in android, instead it shows the crossed box, here is how we implemented it:
Hello Bruno,
1.) Now that Expo for Web was released, what would you recommend?
To setup a monorepo for Mobile and Web packages or to use Expo for Web?
There's also a React Native Web CLI called
create-react-native-web-app.
2.) And also could you give some guide how to setup Next.js as a package of this monorepo? Upon running
yarn create next-app --example with-react-native-web next, here's the response:
Thanks for any response!
Expo has it's own set of limitations, e.g. I've been using hooks in production since november 2018 and it only arrived in expo may 2019. If you are ok using expo go for it! They seem to be doing great progress.
About next, I don't know what the issue is, try creating the project separately and copy pasting the folder into the monorepo. Otherwise open an issue with them about monorepo support.
Hi,
I downloaded the repo, I am able to run the web app, but I have issue with ios
Can you tell me why I am getting the below issue, I am trying to do pod install inside my ios folder
aal003110384:ios reerer89989823$ pod install
[!] Invalid
Podfilefile: cannot load such file -- /Users/reerer89989823/Desktop/codebase/Shipment/react-native-web-monorepo-master/packages/mobile/node_modules/@react-native-community/cli-platform-ios/native_modules.
# from /Users/reerer89989823/Desktop/codebase/Shipment/react-native-web-monorepo-master/packages/mobile/ios/Podfile:2
# -------------------------------------------
# platform :ios, '9.0'
I want to discuss something we are facing after getting a great kickstart from this post. That is responsiveness problem.
We have made significant progress in our journey of converting existing RN apps to RNW. In-fact i am now writing a series of articles on my experience, first one was written last weekend and i plan on writing next this weekend. Here is the first part:
medium.com/@ziaulrehman/part-1-con...
For my use case, i am using a similar approach to this library: github.com/calinortan/react-getscreen it basically adds event handlers which trigger a state change hence re-render whenever screen size crosses one of pre-defined(configurable) widths.
This allows us to add conditional styles etc on some elements, or even hide/show some elements conditionally. This along with Platform.OS === 'web' is basically all we are doing for now. It doesn't look very clean but it works and gives us responsive design.
What techniques have you used(if any) for this? What worked best? And what would you suggest. Thanks.
I have a custom hook that checks the app dimensions and returns if it’s small/medium/large: github.com/devhubapp/devhub/blob/m...
Besides that, make sure to always use flexbox and percentages where makes sense, not fixed widths in pixels.
Yeah similar approach with HOC for class components. I actually just released a small RN component for this(actually my first npm package). npmjs.com/package/react-native-get...
When I use "yarn start", my web app works pretty much exactly the way it should. If I use "yarn build", and then "serve -s build", however, it gives me an error for createBrowserApp:
AppNavigator.ts:99 is:
react-navigation, @react-navigation, react-native-gesture-handler, react-native-reanimated, react-native-screens, react-navigation-stack, and @react-navigation/web are all in my main project's package.json, and "brought over" via
I can't figure out why it works via "yarn start", but not on "yarn build". I've spent a while searching, and I can't seem to find an answer. Anyone have any ideas?
Hello,
Thank you so much for the article.
I have pulled down your repo, installed the deps and ran it. Metro bundler runs well but I do not see anything on the emulators.
Is there a step that I am missing?
Thanks
Siya
To run the mobile apps you can open Xcode/Android Studio and press the Run button.
Yeah, I realised that is how you were running it. I am a fan of the terminal, so I prefer that way. But for some reason I thought that running the bundler would mount the project into the emulator. Thank you so much for the article, I found it very helpful.
How did you configure auto reloading?
Thanks
Olá bruno, baixei a versão mais recente do monorepo, mas está dando esse erro,
sabe dizer porque? e como resolver?
[1] error: bundling failed: Error: Unable to resolve module
../../../commons/reducers/from
E:\sistemasagv\appwmsmobile\app-rf\packages\components\src\screen-mobile\Reducer\index.js: The module
../../../commons/reducers/could not be found from
E:\sistemasagv\a. Indeed, none of these files exist:
ppwmsmobile\app-rf\packages\components\src\screen-mobile\Reducer\index.js
[1] *
E:\sistemasagv\appwmsmobile\app-rf\packages\components\commons\reducers(.native||.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)
[1] *
E:\sistemasagv\appwmsmobile\app-rf\packages\components\commons\reducers\index(.native||.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)
[1] at ModuleResolver.resolveDependency (E:\sistemasagv\appwmsmobile\app-rf\node_modules\metro\src\node-haste\DependencyGraph\ModuleResolution.js:163:15)
[1] at ResolutionRequest.resolveDependency (E:\sistemasagv\appwmsmobile\app-rf\node_modules\metro\src\node-haste\DependencyGraph\ResolutionRequest.js:52:18)
[1] at DependencyGraph.resolveDependency (E:\sistemasagv\appwmsmobile\app-rf\node_modules\metro\src\node-haste\DependencyGraph.js:283:16)
[1] at Object.resolve (E:\sistemasagv\appwmsmobile\app-rf\node_modules\metro\src\lib\transformHelpers.js:261:42)
[1] at dependencies.map.result (E:\sistemasagv\appwmsmobile\app-rf\node_modules\metro\src\DeltaBundler\traverseDependencies.js:399:31)
[1] at Array.map ()
[1] at resolveDependencies (E:\sistemasagv\appwmsmobile\app-rf\node_modules\metro\src\DeltaBundler\traverseDependencies.js:396:18)
[1] at E:\sistemasagv\appwmsmobile\app-rf\node_modules\metro\src\DeltaBundler\traverseDependencies.js:269:33
[1] at Generator.next ()
at asyncGeneratorStep (E:\sistemasagv\appwmsmobile\app-rf\node_modules\metro\src\DeltaBundler\traverseDependencies.js:87:24)
I tried to set up monorepo 2-3 months ago. Faced lots of errors with React Native. I have been searching for any decent material. I always suspected issue to be of old articles as the dependencies have changed. So the steps stated in the article or video were always not working for me.
I faced same stuff with your article. Tried it almost a year after you writing it.
I faced stackoverflow.com/questions/473994... issues everytime I tried to run the mobile app. This particular issue was extremely nasty github.com/facebook/react-native/i.... I never hated another library so much as React Native because of all this shit. Or some other module not popping up. I managed to get mobile app work only just once. But I couldn't get it to work when I imported the app from Components package. So I felt somehow my monorepo was not at all working. Almost all the stack overflow or github issues stated only few repeated solutions like clear cache, delete node_modules are re run it. In my scenario situation seemed to be deteoriating. Atleast mobile app was connecting to simulator, then after trying out these solutions it started giving the error of Metro server of not being up and running. Which didn't make sense simulator was able to make call metro server.
Then I thought atleast web would work but it didn't either it always gave me this error -
Module not found: Can't resolve 'react-native/Libraries/NewAppScreen. Because App.js in components package was using this library in updated version of React-Native CLI. I followed all the steps diligently I even found some more steps were required as well.
I don't know how you managed to get it to work. I really envy that but I have wasted too much time to just get the infrastructure setup managed to do total zero work. I worry if I try to integrate other libraries I'll face the same issues.
Just remove all the dummy components from
react-native/Libraries/NewAppScreen.on the app.js screen. It will then work
Hi, after going through the steps listed under "ios changes" above, when i run "yarn workspace mobile start" it does launch the app in the simulator but i get a red screen with error (attaching image). Please help
Bruno, this is a great tutorial. I have been able to successfully migrate an existing react native project to the mono repository and can run and compile the mobile app for android. However, I am having issues building the web portion of the project. Any tips on how to debug? I am getting the project to start to compile but get in error Attempted import error: 'initStore' is not exported from '../store'. I have altered the index.js for web to pull in the components package.
Thanks
Is it possible to incrementally add rnw to an existing project?
The current project set up is a 3 package monorepo with redux being the only code that is shared. The goal is to share more code so I’m thinking to create a 4th package that only contains react native web components and is imported by the react and react native packages. Do you see any issues with this approach or pieces not working?
I have implemented react-navigation-drawer in my project. Just using two menu items there
( HomeScreen & ProfileScreen )
react-navigation-drawer issue link
The drawer not closing automatically on the browser ... but on mobile it works fine.
Can you please give me any reference where i can separate the style of web and mobile?
Hey, I'm looking at your articles(very comprehensive), among others, and trying to understand the need to add CRA to the stack, here. Would using
react-nativeand
react-native-webnot do the trick?
Also, changing the
importstatements in node_modules means you check in your node_modules? Or you make the edits every time you yarn install? (or, i missed smth with yarn workspaces 🤔?)
Thanks for your time and for the article!
CRA makes things easier, but it is not required.
It doesn't make any change inside node_modules, only on normal project files. | https://dev.to/brunolemos/tutorial-100-code-sharing-between-ios-android--web-using-react-native-web-andmonorepo-4pej | CC-MAIN-2020-40 | refinedweb | 7,608 | 50.53 |
Lazy computation directed acyclic graph builder
Project description
Pyflow is a light weight library that lets the user construct a directed acyclic computation graph (DAG) that evaluates lazily. It can cache intermediate results, only compute the parts of the graph that has data dependency, and immediately release memory of data whose dependecy is no longer required. Pyflow is simple and light, built purely on Python, using the weak references for memory management and doubly linked list for DAG construction.
Unlike computation graph based engines such as Dask or PySpark, Pyflow is not meant to be a parallel data processor, or to change the way computation resources are used. Instead, it is meant to be a light weight tool for code organization in the form of DAG and for graph visualization that can be used on top of Dask or PySpark.
Install
pip install pyflow-viz
Getting started
Let’s construct a simple computation graph: (Note the similarity of API to that of Keras functional API!)
from pyflow import GraphBuilder def adding(a, b): return a + b G = GraphBuilder() a1 = G.add(adding)(2, 2) # you add methods with `add` instance method. a2 = G.add(adding)(3, a1) a3 = G.add(adding)(a1, a2)
At this point, no evaluation has occurred. The outputs a1, a2, and a3 are DataNode objects. The methods that we just added are OperationNode objects of the DAG.
You can easily visualize the resulting DAG using view method:
G.view()
The default setting of the view method will only visualize the operation nodes. But view can do much more, as we will learn shortly.
You can execute the computation graph by invoking the run method:
G.run() # will run all the operation nodes
You can pass in data nodes to get the desired results back this way:
a1_result, a3_result = G.run(a1, a3) # will run all the operation nodes, and return the result data values of a1, a3
But what if you don’t want to run every method in the DAG? There is run_only method for that, which we will learn shortly.
A couple notes:
- The API was inspired by that of the Keras functional API
- For demo, we are using a simple method of adding two integers, but the input method can be any python function, including instance methods, with arbitrary inputs such as numpy array, pandas dataframe or Spark dataframe.
Multi-output methods
What if we have a python function with multiple outputs? Due to dynamic nature of python, it is impossible to determine the number of outputs before the function is actually ran. In such a case, you must specify the number of outputs by n_out argument. Otherwise, Pyflow will deem the output to be a single output whose value is a list of multiple elements. Here is an example of how to do use n_out parameter to create multiple child output nodes:
from pyflow import GraphBuilder def adding(a, b): return a + b def multi_output_method(a, b): return a+1, b+1 G = GraphBuilder() a1 = G.add(adding)(2, 2) a2, b2 = G.add(multi_output_method, n_out=2)(a1, 2) # n_out argument! a3 = G.add(adding)(a2, 3) a4 = G.add(adding)(b2, a1) G.view()
Visualizing data flow
The view function actually has the ability to summarize the DAG by only showing the user the OperationNodes, which it does by default. We can override this default setting by using the summary parameter of the function:
G.view(summary=False)
With the summary functionality turned off, the complete DAG visualization will includes DataNodes as well as the OperationNodes. You may be wondering what the extra records with (1, ) written inside are. They signal the data persistence. We will discuss what this is, and how this works, in greater detail later.
But that graph image is a little too big. We can shrink the gap between the nodes with handy the gap parameter:
G.view(summary=False, gap=0.2) # the default value is 0.415
Styling your DAG
Pyflow lets the user customize the DAG visuals to a certain degree, with more to come in the future. Let’s take a look at some examples. G = GraphBuilder() df1 = G.add(query_dataframe_A)() df2 = G.add(query_dataframe_B)() new_df1 = G.add(product_transform)(df1) new_df2 = G.add(product_transform)(df2) dfa, dfb = G.add(split_transform, n_out=2)(new_df2) joined_df = G.add(join_transform)(new_df1, dfa) G.view()
But since at a conceptual level, queries are similarly progenitors of new data, perhaps we want to put them side by side on top, and position is controlled by rank parameter. Also, since these are probably coming from some data storage, we might want to style their nodes accordingly, with different color..view()
But then we might want to make the DAG a little shorter, especially if we are to add more and more intermediate steps. We can control more detailed aesthetics with graph_attributes (the gap is simply the short cut parameter for this!):
graph_attributes = {'graph_ranksep': 0.25} G.view(graph_attributes=graph_attributes)
You can take a look and play around with the rest of the configurations:
G.graph_attributes # the default settings are found at: G.default_graph_attributes # 'data_node_fontsize': 10, # 'data_node_shape': 'box', # 'data_node_color': None, # 'op_node_fontsize': 12, # 'op_node_shape': 'box', # 'op_node_color': 'white', # 'graph_ranksep': 0.475, # 'graph_node_fontsize': 12.85, # 'graph_node_shape': 'box3d', # 'graph_node_color': 'white', # 'graph_node_shapesize': 0.574, # 'persist_record_shape': True
Finally, you can set the alias of the nodes by passing in method_alias and/or output_alias in the add method. The method_alias will set the alias of the operation node being added, and output_alias will set the alias of the child data node of that operation node.
G = GraphBuilder() dfa = G.add(query_dataframe_A, rank=0, shape='cylinder', color='lightblue', output_alias='df_A')() dfb = G.add(query_dataframe_B, rank=0, shape='cylinder', color='lightblue', output_alias='df_B')() dfa1 = G.add(product_transform)(dfa) dfb1 = G.add(product_transform)(dfb) # note the list of alias for n_out = 2 dfa, dfb = G.add(split_transform, n_out=2, output_alias=['first_out', 'second_out'])(dfa1) joined_df = G.add(join_transform, output_alias='final_data')(dfb1, dfa) graph_attributes = {'graph_ranksep': 0.25} G.view(summary=False, graph_attributes=graph_attributes)
The default alias for operation node is the String name of the method being passed in, and the default alias for data node is simply “data”. We do not include the example of setting method_alias to discourage its use. Setting method alias different from the method name will make look up of graph node in the code base very difficult.
No output methods
Often when we are processing data, we will end up doing something with that data, whether it is to upload it somewhere, save it somewhere, or use pass it to a model, etc. In those cases, we do not expect any return data.
# this method does not have return statement def save_data(data): # save the data somewhere # no return statement needed pass
Pyflow will create graph accordingly, such that the outputless operation node is a leaf node. def save_data(data): # save the data somewhere # no return statement needed pass.add(save_data)(dfb) G.add(save_data)(joined_df) graph_attributes = {'graph_ranksep': 0.25} G.view(summary=False, graph_attributes=graph_attributes)
This is a more realistic shape of the DAG in the actual use case of data preprocessing.
Executing parts of graph
The run method will execute all nodes in the graph, but what if you don’t want to run every node in the graph to save yourself time? Let’s look at an example:
from pyflow import GraphBuilder def query_dataA(): return 1 def query_dataB(): return 2 def query_dataC(): return 3 def transform_dataA(a): return a def transform_dataB(a): return a def transform_dataC(a): return a def join_dataAB(a, b): return a + b def save_dataAB(ab): pass def join_dataC(a, c): return a + c G = GraphBuilder() a = G.add(query_dataA, rank=0)() b = G.add(query_dataB, rank=0)() c = G.add(query_dataC, rank=0)() a = G.add(transform_dataA)(a) b = G.add(transform_dataB)(b) c = G.add(transform_dataC)(c) ab = G.add(join_dataAB)(a, b) G.add(save_dataAB)(ab) abc = G.add(join_dataC)(ab, c) G.view(gap=0.25)
From the above graph, let’s say you want to test the transform_dataA method. For this purpose, you only need to run query_dataA and transform_dataA. In such a case, you can use the run_only method, instead of run method, which will execute every node in the graph:
a_result = G.run_only(a) # 1
When you invoke the run_only method, Pyflow will only execute parts of the graph that has the data dependency to the asked node.
This time, let’s say you are testing the save_dataAB method. But this node does not have data node that we can use to pass into the run_only method. That’s why you can also pass in the string of the node names into the run_only method:
a_result = G.run_only(a, 'save_dataAB')
In the above code, only the result for a node is returned because save_dataAB does not have a return statement.
Visualizing computation dependency
Pyflow will only execute parts of the graph that has data dependency. We can visualize this dependency with view_dependency method. We will use the same graph from the previous example:
G.view_dependency('save_dataAB')
You can pass in several arguments, just as you can with run_only method for execution:
G.view_dependency('save_dataAB', c)
This method also supports other parameters of view method:
G.view_dependency('save_dataAB', c, summary=False, gap=0.2)
Grafting graphs together
When the computation graph becomes too big, the size of the visualized graph can actually end up becoming a hinderance to clean data flow documentation. Not only that, we could also benefit at the conceptual code organization level, if we had the ability to define multiple graphs and combine them together flexibly. I.e. we could treat a graph as if it was just another operation node. As of version 0.7, we can do this. Let’s look at an example:
from pyflow import GraphBuilder def adding(a, b): return a+b G = GraphBuilder(alias='First Graph') # notice alias at graph level! a1 = G.add(adding)(1, 2) a2 = G.add(adding)(a1, 2) a3 = G.add(adding, output_alias='leaving!')(a1, a2) G.view()
Let’s look at the unsummarized version to take notice of the output_alias of the last data node:
# let's make it a little shorter with ranksep parameter we talked about earlier! G.view(summary=False, graph_attributes={'graph_ranksep': 0.3})
In the above code, we have created one graph. But we can create another graph, and graft the First Graph graph to the new graph:
H = GraphBuilder(alias='Second Graph') b1 = H.add(adding)(1, 3) b2 = H.add(adding)(b1, a3) b3 = H.add(adding)(b1, b2) H.view(summary=False) # notice that the output_alias from previous graph is also preserved!
As you can see, the previous graph is now summarized into a box. You can combine as many graphs in this way as you want. Despite this visual effect, b3 is now part of one single big combined computation graph. Therefore, calling b3.get() will trigger computations in nodes that belong to both G and H as long as they are needed. As far as computation is concerned, you just have one big graph.
Saving your DAG image
You can easily save your DAG image by invoking save_view method, which returns the file path of the saved image:
G.save_view()
The save_view method also has summary boolean parameter. You can also set the file name and file path by passing in dirpath and filename parameter. They default to current working directory and “digraph” respectively. You can also set the file format as png or pdf by setting fileformat parameter. The default is png.
HTML documentation of DAG
With the visualization of the DAG, we can see the input-output relations among the functions, but it alone does not tell what each of the function does. But you can create a single HTML documentation that tells the complete semantic story of the DAG, using document method:
from pyflow import document document(G) # or document(G, H, I) etc if you have more than one graph
Doing so will create a static HTML file that displays the DAG image as well as the docstrings of each of the functions that goes into the DAG on the right side, which you can scroll through.
from pyflow import GraphBuilder from pyflow import document def methodA(elem): """Some descriptions of the methodA Parameter --------- elem : int """ return elem def methodB(elem): """Some descriptions of the methodB Parameter --------- elem : int """ return elem def methodC(elem): """Some descriptions of the methodC Parameter --------- elem : int """ return elem G = GraphBuilder() a = G.add(methodA)(3) b = G.add(methodB)(a) c = G.add(methodC)(b) document(G)
This code will produce the following HTML file:
Memory persistance with Pyflow
You have the option of either persisting all of the intermediate results, or persisting part of the intermediate results.
To persist all intermediate results, use persist parameter at GraphBuilder level:
from pyflow import GraphBuilder G = GraphBuilder(persist=True) # set persist to True a1 = G.add(adding)(1, 2) a2, a3 = G.add(return2, n_out=2)(a1, 3) a4 = G.add(adding)(a1, 5) a5 = G.add(adding)(a4, a3) a5.get()
With persist enabled, after running a5.get(), when you try to run a4.get(), the graph will not recompute anything because a4 node result will have been cached in memory. The persist is turned off by default, as it is assumed that the user of the pyflow will process large amounts of data.
To persist parts of the data, you can specify the persist parameter at add level:
from pyflow import GraphBuilder G = GraphBuilder(persist=False) # default value a1 = G.add(adding)(1, 2) a2, a3 = G.add(return2, n_out=2)(a1, 3) a4 = G.add(adding, persist=True)(a1, 5) # persist here a5 = G.add(adding)(a4, a3) a5.get()
Then, when you run a4.get() it will not rerun the computation as a4 result has been cached in memory although all other intermediate results will have been released.
At last, we can understand the difference between run() and run(a1, a3). Even if you don’t persist anything, either at the graph level or the node level, by passing in the a1, a3, the graph will automatically persist their data for you, and return the persisted data by internally invoking get() on the nodes a1, a3. The rest of data nodes are subject to the same immediate memory release mechanism.
In terms of the codes, these two are equivalent:
# run() with arguments: from pyflow import GraphBuilder G = GraphBuilder() a1 = G.add(adding)(1, 2) a2 = G.add(adding)(a1, 3) a3 = G.add(adding)(a2, a1) a1_val, a3_val = G.run(a1, a3) # run() without arguments: G = GraphBuilder() a1 = G.add(adding, persist=True)(1, 2) a2 = G.add(adding)(a1, 3) a3 = G.add(adding)(a2, a1) G.run() a1_val = a1.get() a3_val = a3.get()
Also, when you persist certain nodes, this persistence request will manifest in the graph by an empty record box:
from pyflow import GraphBuilder G = GraphBuilder() a1 = G.add(adding)(1, 2) a2 = G.add(adding)(a1, 3) a3 = G.add(adding)(a2, a1) G.view()
The empty box signifies that the graph is requested to persist that data, but it does not yet hold that data because it has not yet been executed. But once you run the graph, the empty record slot will be filled by the dimensionality of the resulting data. Currently it supports PySpark dataframe, numpy array, and pandas dataframe. All other data will have a default dimension of (1, ).
G.run()
Now, of course, it is not the method that is being persisted but the resulting data of that op node. You can see this when you visualize the DAG with summary=False:
G.run(summary=False)
Some notes:
- The op node with record box is a short hand way of conveying the message that the child data node of that op node will be persisted.
- The raw data are automatically persisted, which is why you see the dimensionality information in the record box. This is because the raw user data inputs cannot be recomputed from the graph alone. But this will not be visible when summary=True, because the op node will only show the record box for persisted child data node, and user supplied inputs will always be parent data node.
- Although this is not made explicitly visible, the final leaf data node are always persisted when run method is invoked. But this will not be explicitly shown in the graph unless the user manually supplies persist flag at the add method invocation.
- Lastly, the persist flag is interoperable with Spark when PySpark dataframe is the data type. This means, when you persist the data using the DAG, if the underlying data is a PySpark dataframe, the Pyflow will persist the dataframe for you. However, unpersisting is not done by the Pyflow. If you want to unpersist a dataframe, do so manually.
Computation and memory efficiency of Pyflow (OUTDATED)
When you invoke get method, pyflow will only then evaluate, and it will evaluate only the parts of the graph that is needed to be evaluated. Also, as soon as an intermediate result has no dependency, it will automatically release the memory back to the operating system. Let’s take a tour of the computation process to better understand this mechanism by turning on verbose parameter.
from pyflow import GraphBuilder def adding(a, b): return a + b def multi_output_method(a, b): return a+1, b+1 G = GraphBuilder(verbose=True) # set verbose to True a1 = G.add(adding)(1, 2) a2, a3 = G.add(return2, n_out=2)(a1, 3) a4 = G.add(adding)(a1, 5) a5 = G.add(adding)(a4, a3) a5.get()
With verbose=True, along with the final output, pyflow will also produce the following standard output:
computing for data_12 adding_11 activated! adding_8 activated! adding_0 activated! return2_4 activated! computing for data_10 computing for data_3 running adding_0 adding_0 deactivated! running adding_8 data_3 still needed at return2_4 adding_8 deactivated! computing for data_7 running return2_4 data_3 released! return2_4 deactivated! running adding_11 data_10 released! data_7 released! adding_11 deactivated!
Let’s take the tour of this process by looking at the graph. Notice that in verbose mode, the graph will actually print out the uid’s of the nodes not just their aliases (more on setting alias later!)
As pyflow tries to compute data_12, it will first activate all the OperationNodes that is needed for the computation, in our case, those are adding_11, adding_8, adding_0, return2_4. It will then follow the lineage of the graph to work on intermediate results needed to proceed down the graph. Notice that as the computation proceeds, the OperationNodes that were activated are deactivated. When it gets to data_3, notice that it is needed at both adding_8 and return2_4. Thus, once it completes adding_8, it cannot yet release the memory from data_3: data_3 still needed at return2_4. But as soon as return2_4 is ran, it releases data_3 from memory, as it is not needed anymore: data_3 released!. The DataNodes with raw inputs such as integers are not released since there is no way for the graph to reconstruct them.
By the same token, if you were to run the graph from middle, say, at a4:
a4.get()
You will see:
computing for data_10 adding_8 activated! adding_0 activated! computing for data_3 running adding_0 adding_0 deactivated! running adding_8 data_3 released! adding_8 deactivated!
In this case, since return2_4 is not activated, the data_3 does not consider its presence in deciding release of memory.
On the other hand, run method will activate all operation nodes. This will make sure that even the operation nodes that do not have children are ran. However, the immediate memory release mechanism still applies to run method, unless otherwise specified. Refer below.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/pyflow-viz/ | CC-MAIN-2021-21 | refinedweb | 3,326 | 57.47 |
Results 1 to 4 of 4
Symbolic mathematics in Javascript
Alright. Resident moderator Alex Vincent has been after a "toMathML()" method for a while now it seems. So I told him, "Alright, no biggie."
. Now I gotta deliver.
Content MathML 2.0 is essentially Polish Notation, but in XML. You can directly convert infix expressions (Algebraic notation) to prefix (Polish), however I decided to take a different route and implemented my own algorithm for directly converting an infix expression into an expression tree. And from the tree, I can dynamically evaluate it recursively, pre-order traverse it, post-order traverse it, in-order traverse it, and generate MathML like nothing.
So, if you're using Mozilla, check it out here:
The algorithm works fine in any JS-capable browser, however I use DOM2 namespaced node-creation methods that only Mozilla supports for MathML generation. Presentation MathML output will come as soon as I hook up the XSLT stylesheet. Also, support for unary operators and functions (like sin, cos, log), etc will come as soon as I replace the binary tree data structure with an n-ary tree data structure.
You can try this simple example to type in the algebraic input box:
y = 5*x + 2
It's all part of a much bigger plan, so the lack of a UI right now isn't a concern. (The "test.xhtml" filename implies that it is a test page.) I just thought the script might be educational to anyone interested in real computer science and using Javascript to implement and utilize abstract data types.
Oh, and I noticed that I didn't explain the reason why I included "symbolic" in the title... by creating an expression tree, it becomes trivial to perform operations symbolically on it. Differentiation of an expression tree, for example, is exceedingly easy.
Alright - to please Mr. Vincent, here is a zip with everything:
Last edited by jkd; 08-16-2003 at 04:23 AM.
- Join Date
- Sep 2011
- 2
- Thanks
- 0
- Thanked 0 Times in 0 Posts
I get a 404 error when attempting to connect to the links above.
I had searched here, first, for a few libraries, and not finding anything I felt I could use started my own.
It's located here on GitHub:
And, hopefully, will not be going anywhere as long as GitHub is around.
Presently, it handles: addition, subtraction, multiplication, division, exponents, parentheticals, simple differentials (with and without product rule).
I would be very grateful for contributions to the baseline, if anyone would be so inclined.
- Join Date
- Oct 2011
- 1
- Thanks
- 0
- Thanked 0 Times in 0 Posts
i get this:
Not Found
The requested URL /math/test.xhtml was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
- Join Date
- Sep 2013
- 2
- Thanks
- 0
- Thanked 0 Times in 0 Posts
I also needed a symbolic parser in javascript so I decided to roll my own. It can use some polishing and maybe some more testing. At present it parses symbolically and can do derivatives. You can get an idea of how it works at and the code can be found at. The math is rendered with mathquill. Hope this helps. | https://www.codingforums.com/post-a-javascript/24858-symbolic-mathematics-javascript.html | CC-MAIN-2018-05 | refinedweb | 546 | 63.7 |
BUILD.bazel
Here, you'll prepare a build target, that your host code will make use of.
Start by preparing a
sapi_library() target in your
BUILD.bazel file.
For reference, you can take a peek at a working example from the zlib example.
load( "//sandboxed_api/tools/generator:sapi_generator.bzl", "sapi_library", ) sapi_library( name = "zlib-sapi", srcs = [], # Extra code compiled with the SAPI library hdrs = [] # Leave empty if embedded SAPI libraries are used, and the # default sandbox policy is sufficient. embed = True, # This is the default functions = [ "deflateInit_", "deflate", "deflateEnd", ], lib = "@zlib//:zlibonly", lib_name = "Zlib", namespace = "sapi::zlib", )
name- name for your SAPI target
srcs- any additional sources that you'd like to include with your Sandboxed API library - typically, it's not necessary, unless you want to provide your SAPI Library sandbox definition in a .cc file, and not in the
sandbox.hfile.
hdrs- as with
srcs. Typically your sandbox definition (sandbox.h) should go here, or empty, if embedded SAPI library is used, and the default sandbox policy is sufficient.
functions- a list of functions that you'd like to use in your host code. Leaving this list empty will try to export and wrap all functions found in the library.
embed- whether the SAPI library should be embedded inside host code, so the SAPI Sandbox can be initialized with the
::sapi::Sandbox::Sandbox(FileToc*)constructor. This is the default.
lib- (mandatory) the library target you want to sandbox and expose to the host code.
lib_name- (mandatory) name of the object which is proxying your library functions from the
functionslist. You will call functions from the sandboxed library via this object.
input_files- list of source files, which SAPI interface generator should scan for library's function declarations. Library's exported headers are always scanned, so
input_filescan usually be left empty.
namespace- a C++ namespace identifier to place API object defined in
lib_nameinto. Defaults to
sapigen.
deps**- a list of any additional dependency targets to add. Typically not necessary.
header- name of the header file to use instead of the generated one. Do not use if you want to auto-generate the code.
sapi_library() Rule Targets
For the above definition,
sapi_library() build rule provides the following
targets:
zlib-sapi- sandboxed library, substitiution for normal cc_library; consists of
zlib_sapi.binand sandbox dependencies
zlib-sapi.interface- generated library interface
zlib-sapi.embed-
cc_embed_data()target used to embed sandboxee in the binary. See
bazel/embed_data.bzl.
zlib-sapi.bin- sandboxee binary, consists of small communication stub and the library that is being sandboxed.
Interface Generation
zlib-sapi target creates target library with small communication stub
wrapped in Sandbox2. To be able to use the stub and code
within the sanbox, you should generate the interface file.
There are two options:
- Add dependency on
zlib-sapi.interface. This will auto-generate a header that you can include in your code - the header name is of the form:
TARGET_NAME
.sapi.h.
- Run
bazel build TARGET_NAME.interface, save generated header in your project and include it in the code. You will also need to add the
headerargument to the
sapi_library()rule to indicate that you will skip code generation.
Sandbox Description (
sandbox.h)
In this step you will prepare the sandbox definition file (typically named
sandbox.h) for your library.
The goal of this is to tell the SAPI code where the sandboxed library can be found, and how it should be contained.
At first, you should tell the SAPI code what your sandboxed library should be allowed to do in terms of security policies and other process constraints. In order to do that, you will have to implement and instantiate an object based on the ::sapi::Sandbox class.
This object will also specify where your SAPI Library can be found and how it should be executed (though you can depend on default settings).
A working example of such SAPI object definition file can be found here.
In order to familiarize yourself with the Sandbox2 policies, you might want to take a look at the Sandbox2 documenation. | https://developers.google.com/sandboxed-api/docs/library | CC-MAIN-2021-21 | refinedweb | 670 | 57.37 |
This action might not be possible to undo. Are you sure you want to continue?
05/01/2011
text
original
#
Rob Miles
Edition 2.0 July 2010 2010 Department of Computer Science, The University of Hull.
ii
uk Email: rob@robmiles.dcs. No reproduction.com and I will take a look.com If you find a mistake in the text please report the error to foundamistake@robmiles.com Blog: www. Edition 2.hull. Cottingham Road HULL HU6 7RX UK Department:. copy or transmission of this publication may be made without written permission. The author can be contacted at: The Department of Computer Science.0 Wednesday.robmiles. 28 July 2010 iii .All rights reserved. Robert Blackburn Building The University of Hull.
.
ac.dcs. Reading the notes These notes are written to be read straight through. and this can be confusing. the easiest to use etc. These are based on real programming experience and are to be taken seriously. the fastest. Not because they are stupid. Rob Miles rob@robmiles. The bad news about learning to program is that you get hit with a lot of ideas and concepts at around the same time when you start.9.com www. And you have to work hard at it.hull. Programming is not rocket science it is. If you have any comments on how the notes can be made even better (although I of course consider this highly unlikely) then feel free to get in touch Above all. enjoy programming. However. do not worry. Persistence – writing programs is hard work. In this book I'm going to give you a smattering of the C# programming language. don't get too persistent. If you haven't solved a programming problem in 30 minutes you should call time out and seek help. And remember that in many cases there is no best solution. Font. and programming. Figuring out how somebody else did the job is a great starting point for your solution.com www. programming. There are also bits written in a Posh These are really important and should be learnt by heart.robmiles. If you have not programmed before. well. We will cover what to do when it all goes wrong later in section 5. just ones which are better in a particular context. The website for the book is at. The principle reason why most folks don't make it as programmers is that they give up.com C# Programming © Rob Miles 2010 5 . and then referred to afterwards. Staying up all night trying to sort out a problem is not a good plan. It is worth it just for the jokes and you may actually learn something. If you have programmed before I'd be grateful if you'd still read the text.Introduction Welcome Introduction Welcome Welcome to the Wonderful World of Rob Miles™. You can learn a lot from studying code which other folk have created. They contain a number of Programming Points. puns. This is a world of bad jokes. i. Or at least walk away from the problem and come back to it. It just makes you all irritable in the morning. The keys to learning programming are: Practice – do a lot of programming and force yourself to think about things from a problem solving point of view Study – look at programs written by other people.e.uk Getting a copy of the notes These notes are made freely available to Computer Science students at the University of Hull. the smallest.csharpcourse.
2 Hardware and Software If you ever buy a computer you are not just getting a box which hums. we are going to consider computers. The business of using a computer is often called programming. You will discover what you should do when starting to write a program. A better way is to describe it as: A device which processes information according to instructions it has been given. particularly amongst those who then try to program a fridge.1. a keen desire to process words with a computer should not result in you writing a word processor! However. The instructions you give to the computer are often called a program. Before we can look at the fun packed business of programming though it is worth looking at some computer terminology: 1. C# Programming © Rob Miles 2010 6 . A programmer has a masochistic desire to tinker with the innards of the machine. can lead to significant amounts of confusion. we are going to learn how to program as well as use a computer. to be useful. and further because there are people willing to pay you to do it. Software is what makes the machine tick.Computers and Programs Computers 1 Computers and Programs In this chapter you are going to find out what a computer is and get an understanding of the way that a computer program tells the computer what to do.e. One of the golden rules is that you never write your own program if there is already one available. Hardware is the impressive pile of lights and switches in the corner that the salesman sold you. We must therefore make a distinction between users and programmers. 1.1. which can run programs. while technically correct. If a computer has a soul it keeps it in its software. 1. Most people do not write programs. Finally you will take a look at programming in general and the C# language in particular. must also have sufficient built-in intelligence to understand simple commands to do things. The box. Software uses the physical ability of the hardware. because it sets the context in which all the issues of programming itself are placed.1 Computers Before we consider programming.1 An Introduction to Computers Qn: Why does a bee hum? Ans: Because it doesn't know the words! One way of describing a computer is as an electric box which hums. This is not what most people do with computers. This. and it stops working when immersed in a bucket of water. Hardware is the physical side of the system. This general definition rules out fridges but is not exhaustive. This is an important thing to do. They use programs written by other people. A user has a job which he or she finds easier to do on a computer running the appropriate program. to ensure that you achieve a ―happy ending‖ for you and your customer. because you will often want to do things with computers which have not been done before. Essentially if you can kick it. At this point we must draw a distinction between the software of a computer system and the hardware. it is hardware. However for our purposes it will do. i.
some processing is performed. A computer program tells the computer what to do with the information coming in. ones you have written and ones from other people.608 in your account! Data Processing Computers are data processors. 1. Information is the interpretation of the data by people to mean something. Strictly speaking computers process data..Computers and Programs Computers do something useful. It looks after all the information held on the computer and provides lots of commands to allow you to manage things. they do something with it. Put duff data into a computer and it will do equally useless things. C# Programming © Rob Miles 2010 7 . humans work on information. All computers are sold with some software. It is called software because it has no physical existence and it is comparatively easy to change. Windows 7 is an operating system. something is put in one end. It also lets you run programs.3 Data and Information People use the words data and information interchangeably. They seem to think that one means the other. I regard data and information as two different things: Data is the collection of ons and offs which computers store and manipulate. The Operating System makes the machine usable. So why am I being so pedantic? Because it is vital to remember that a computer does not "know" what the data it is processing actually means.1. As far as the computer is concerned data is just stuff coming in which has to be manipulated in some way... as well as a useful thing to blame. A program is unaware of the data it is processing in the same way that a sausage machine is unaware of what meat is. and then generate further information. A computer program is just a sequence of instructions which tell a computer what to do with the data coming in and what form the data sent out will have. The software which comes with a computer is often called its Operating System. Information is fed into them.. An example. Remember this when you get a bank statement which says that you have £8. and something comes out of the other end: Data Computer Data This makes a computer a very good "mistake amplifier".. You will have to learn to talk to an operating system so that you can create your C# programs and get them to go. It gives computer programs a platform on which they can execute. Put a bicycle into a sausage machine and it will try to make sausages out of it. As far as the computer is concerned data is just patterns of bits. Software is the voice which says "Computer Running" in a Star Trek film. Without it they would just be a novel and highly expensive heating system.388. A computer works on data in the same way that a sausage machine works on meat. It is only us people who actually give meaning to the data (see above). it is the user who gives meaning to these patterns.
which you might think is entirely reading and writing numbers. Games Console: A computer is taking instructions from the controllers and using them to manage the artificial world that it is creating for the person playing the game. oxygen content of the air. Programming is a black art. 4. you will press a switch to tell a computer to make it work. These embedded systems will make computer users of everybody. 2. The power and capacity of modern computers makes this less of an issue than in the past. followed by a long description of the double glazing that they have just had fitted.Computers and Programs Programs and Programming Note that the data processing side of computers. Most reasonably complex devices contain data processing components to optimise their performance and some exist only because we can build in intelligence. "That's interesting". In this case a defect in the program could result in illness or even death (note that I don't think that doctors actually do this – but you never know. These are the traditional uses of computers. to optimise the performance of the engine. You must make sure that the code you write will actually fit in the target machine and operate at a reasonable speed. timing of the spark etc. For example a doctor may use a spread sheet to calculate doses of drugs for patients. and we will have to make sure that they are not even aware that there is a computer in there! You should also remember that seemingly innocuous programs can have life threatening possibilities.) Programmer’s Point: At the bottom there is always hardware It is important that you remember your programs are actually executed by a piece of hardware which has physical limitations. You will not press a switch to make something work. processing this data and producing a display which tells you the time. It is important to think of business of data processing as much more than working out the company payroll. as software writers are moving. A blank stare. C# Programming © Rob Miles 2010 8 . Tell people that you program computers and you will get one of the following responses: 1. As software engineers it is inevitable that a great deal of our time will be spent fitting data processing components into other devices to drive them. Car: A micro-computer in the engine is taking information from sensors telling it the current engine speed. Note that this "raises the stakes" in that the consequences of software failing could be very damaging. CD Player: A computer is taking a signal from the disk and converting it into the sound that you want to hear. It is into this world that we. Asked to solve every computer problem that they have ever had. It is the kind of thing that you grudgingly admit to doing at night with the blinds drawn and nobody watching. examples of typical data processing applications are: Digital Watch: A micro-computer in your watch is taking pulses from a crystal and requests from buttons. reading in numbers and printing out results. setting of the accelerator etc and producing voltages out which control the setting of the carburettor. Note that some of these data processing applications are merely applying technology to existing devices to improve the way they work. I will mention them when appropriate. 1. but you should still be aware of these aspects. is much more than that. However the CD player and games console could not be made to work without built-in data processing ability.2 Programs and Programming I tell people I am a "Software Engineer". road speed. A look which indicates that you can't be a very good one as they all drive Ferraris and tap into the Bank of England at will. and ever will have.. 3. At the same time it is keeping the laser head precisely positioned and also monitoring all the buttons in case you want to select another part of the disk.
He or she has problem and would like you to write a program to solve it. 1. Unfortunately it is also the most difficult part of programming as well. You look at the problem for a while and work out how to solve it and then fit the bits of the language together to solve the problem you have got. I am going to start on the basis that you are writing your programs for a customer. The customers assumed that. Solving the Wrong Problem Coming up with a perfect solution to a problem the customer has not got is something which happens surprisingly often in the real world. and only at the final handover was the awful truth revealed. Programmers pride themselves on their ability to come up with solutions. The art of programming is knowing which bits you need to take out of your bag of tricks to solve each part of the problem. From Problem to Program Programming is not about mathematics. You are given a problem to solve. We shall assume that the customer knows even less about computers than we do! Initially we are not even going to talk about the programming language. What you should do is think "Do I really understand what the problem is?" Before you solve a problem you should make sure that you have a watertight definition of what the problem is. The developers of the system quite simply did not find out what was required. tut tutting.Computers and Programs Programs and Programming Programming is defined by most people as earning huge sums of money doing something which nobody can understand. I like to think of a programmer as a bit like a plumber! A plumber will arrive at a job with a big bag of tools and spare parts. the right thing was being built. we are simply going to make sure that we know what the customer wants.1 What is Programmer? And remember just how much plumbers earn…. he will open his bag and produce various tools and parts. You have at your disposal a big bag of tricks. One or two things fall out of this definition: You need to be able to solve the problem yourself before you can write a program to do it. Instead you should think "Is that what the customer wants?" This is a kind of self-discipline. The worst thing you can say to a customer is "I can do that". Having looked at it for a while. In the real world such a definition is sometimes called a Functional Design Specification or FDS. If you think that learning to program is simply a matter of learning a programming language you are very wrong. which both you and the customer agree on. This tells you exactly what the customer wants. Programming is defined by me as deriving and expressing a solution to a given problem in a form which a computer system can understand and execute.2. since the developers had stopped asking them questions. so as soon as they are given a problem they immediately start thinking of ways to solve it. this almost a reflex action. but instead created what they thought was required. type of computer or anything like that. Programming is just like this. The art of taking a problem and breaking it down into a set of instructions you can give a computer is the interesting part of programming. fit them all together and solve your problem. It is therefore very important that a programmer holds off making something until they know exactly what is required. Many software projects have failed because the problem that they solved was the wrong one. it is about organization and structure. in this case a programming language. Both you and the C# Programming © Rob Miles 2010 9 . not all of them are directly related to the problem in hand. In fact if you think that programming is simply a matter of coming up with a program which solves a problem you are equally wrong! There are many things you must consider when writing a program. The computer has to be made to understand what you are trying to tell it to do.
What flows out of the system. He wants to just enter the dimensions of the window and then get a print out of the cost to make the window. C# Programming © Rob Miles 2010 10 . and involve them in the design process. You as a developer don’t really know much about the customer’s business and they don’t know the limitations and possibilities of the technology. The height of the window.Computers and Programs Programs and Programming customer sign it. What the system does with the information.. This is true even (or perhaps especially) if I do a job for a friend. These work on the basis that it is very hard (and actually not that useful) to get a definitive specification at the start of a project.2. Information coming out The information that our customer wants to see is: the area of glass required for the window the length of wood required to build a frame. This is not true. With this in mind it is a good idea to make a series of versions of the solution and discuss each with the customer before moving on to the next one. in terms of the amount of wood and glass required. I would never write a program without getting a solid specification first. you are sitting in your favourite chair in the pub contemplating the universe when you are interrupted in your reverie by a friend of yours who sells double glazing for a living. He knows you are a programmer of sorts and would like your help in solving a problem which he has: He has just started making his own window units and is looking for a program which will do the costing of the materials for him. "This looks like a nice little earner" you think. This is called prototyping. You might think that this is not necessary if you are writing a program for yourself. 1.2 A Simple Problem Consider the scenario. Writing some form of specification forces you to think about your problem at a very detailed level. there is no customer to satisfy. then you can think about ways of solving the problem. Specifying the Problem When considering how to write the specification of a system there are three important things: What information flows into the system. for now we will stick with written text when specifying each of the stages: Information going in In the case of our immortal double glazing problem we can describe the information as: The width of a window. It also forces you to think about what your system is not going to do and sets the expectations of the customer right at the start. The first thing you need to do is find out exactly what the customer wants you to do. and once you have agreed to a price you start work.. Programmer’s Point: The specification must always be there I have written many programs for money. Modern development techniques put the customer right at the heart of the development. There are lots of ways of representing this information in the form of diagrams. Once you have got your design specification. and the bottom line is that if you provide a system which behaves according to the design specification the customer must pay you.
25 feet per metre. in metres and being a value between 0. and two pieces of wood the height of the window.perhaps our customer buys wood from a supplier who sells by the foot. in metres and being a value between 0. To make the frame we will need two pieces of wood the width of the window. Note that we have also added units to our description. For any quantity that you represent in a program that you write you must have at least this level of metadata . in square metres. given in feet using the conversion factor of 3. This must be done in conjunction with the customer. The word meta in this situation implies a "stepping back" from the problem to allow it to be considered in a broader context.. so two panes will be required. your program will regard the data as valid and act accordingly. Having written this all up in a form that both you and the customer can understand. Remember that we are selling double glazing. he or she must understand that if information is given which fits within the range specified. in which case our output description should read: Note that both you and the customer must understand the document! The area of glass required for the window. and work can commence. this is very important . The height of the window.5 Metres and 3. C# Programming © Rob Miles 2010 11 . we now have to worry about how our program will decide when the information coming in is actually valid.0 metres inclusive. we must then both sign the completed specification. Being sensible and far thinking people we do not stop here.5 metres inclusive. Programmer’s Point: metadata is important Information about information is called metadata. In the case of the above we could therefore expand the definition of data coming in as: The width of the window. The length of wood required for the frame. specifically the units in which the information is expressed and the valid range of values that the information may have.Computers and Programs Programs and Programming You can see what we need if you take a look at the diagram below: Height of Window Width of Window The area of the glass is the width multiplied by the height.5 metres and 2. In the case of our window program the metadata will tell us more about the values that are being used and produced.
Computers and Programs Programs and Programming Proving it Works In a real world you would now create a test which will allow you to prove that the program works. and emerge with another system to be approved. is something which the customer is guaranteed to have strong opinions about. for which they can be expect to be paid. You then go back into your back room. The customer will tell you which bits look OK and which bits need to be changed. sometimes even down to the colour of the letters on the display! Remember that one of the most dangerous things that a programmer can think is "This is what he wants"! The precise interaction with the user . In a large system the person writing the program may have to create a test harness which is fitted around the program and will allow it to be tested.. However. Both the customer and the supplier should agree on the number and type of the tests to be performed and then sign a document describing these. suggests changes and then wait for the next version to find something wrong with. if you are going to use prototypes it is a good thing to plan for this from the C# Programming © Rob Miles 2010 12 . All the customer does is look at something.” The test procedure which is designed for a proper project should test out all possible states within the program.. which should include layouts of the screens and details of which keys should be pressed at each stage. Getting Paid Better yet. we have come full circle here. you could for example say: “If I give the above program the inputs 2 metres high and 1 metre wide the program should tell me I need 4 square metres of glass and 19. you can expect to write as much code to test your solution as is in the solution itself. there is no ambiguity which can lead to the customer requesting changes to the work although of course this can still happen! The good news for the developer is that if changes are requested these can be viewed in the context of additional work. Fact: If you expect to derive the specification as the project goes on either you will fail to do the job. Testing is a very important part of program development. muttering under your breath. reminiscent of a posh tailor who produces the perfect fit after numerous alterations... This is not going to happen. Ideally all this information should be put into the specification. In terms of code production. including the all-important error conditions. They will get a bit upset when the delivery deadline goes by without a finished product appearing but they can always cheer themselves up again by suing you.5 feet of wood. . because I did mention earlier that prototyping is a good way to build a system when you are not clear on the initial specificaiton. Rob's law says that 60% of the duff 40% will now be OK. Quite often prototypes will be used to get an idea of how the program should look and feel.. There is even one development technique where you write the tests before you write the actual program that does the job. Again. and one we will explore later. Actually. This is actually a good idea. What will happen is that you will come up with something which is about 60% right. Remember this when you are working out how much work is involved in a particular job. set up a phased payment system so that you get some money as the system is developed.what the program does when an error is encountered. so you accept changes for the last little bit and again retreat to your keyboard. how the information is presented etc.to emerge later with the perfect solution to the problem.
. I know nothing about these machines".. 1.. an art. Tape worms do not speak very good English. You are your own worst customer! You may think that I am labouring a point here. The best we can do is to get a computer to make sense of a very limited language which we use to tell it what to do. by using the most advanced software and hardware. It is very hard to express something in an unambiguous way using English. Fruit Flies like a Banana! C# Programming © Rob Miles 2010 13 .. This is no excuse. At the moment. When we start with our double glazing program we now know that we have to: read in the width verify the value read in the height verify the value calculate width times height times 2 and print it calculate ( width + height ) * 2 * 3. Explain the benefits of "Right First Time" technology and if that doesn't work produce a revolver and force the issue! Again. We cannot make very clever computers at the moment. all to the better. English as a language is packed full of ambiguities. why can we not use something like English?" There are two answers to this one: 1. ask any lawyer! Time Flies like an Arrow. you work with them. and there are limits to the size of program that we can create and the speed at which it can talk to us. Fact: More implementations fail because of inadequate specification than for any other reason! If your insistence on a cast iron specification forces the customer to think about exactly what the system is supposed to do and how it will work. To take the first point. You are wrong. particularly when you might have to do things like trade with the customer on features or price. You do not work for your customers. 2. This is very important.often with the help of the customer. and how we are going to determine whether it has worked or not (test) we now need to express our program in a form that the computer can work with. if I could underline in red I would: All the above apply if you are writing the program for yourself. we can make computers which are about as clever as a tape worm. the kind of simple systems we are going to create as we learn to program are going to be so trivial that the above techniques are far too long winded.25 and print it The programming portion of the job is now simply converting the above description into a language which can be used in a computer. You might ask the question "Why do we need programming languages. One very good reason for doing this kind of thing is that it gets most of the program written for you .3 Programming Languages Once we know what the program should do (specification). The customer may well say "But I am paying you to be the computer expert..Computers and Programs Programming Languages start rather than ending up doing extra work because your initial understanding of the problem was wrong. English would make a lousy programming language. If you do not believe me. To take the second point. Computers are made clever by putting software into them. If you want to call yourself a proper programmer you will have to learn how to do this. One of the first things you must do is break down the idea of "I am writing a program for you" and replace it with "We are creating a solution to a problem". Please note that this does not imply that tape worms would make good programmers! Computers are too stupid to understand English. Programmer’s Point: Good programmers are good communicators The art of talking to a customer and finding out what he/she wants is just that. therefore we cannot make a computer which can understand English..
want to use a chain saw I will hire one from a shop. i. C# is a great language to start programming in. 1. A C# program can contain managed or unmanaged parts.2 Safe C# The C# language attempts to get the best of both worlds in this respect. C is famous as the language the UNIX operating system was written in. Programmer’s Point: The language is not that important There are a great many programming languages around. you can mark your programs as unmanaged. Programmer’s Point: Computers are always stupid I reckon that you should always work on the basis that any computer will tolerate no errors on your part and anything that you do which is stupid will always cause a disaster! This concentrates the mind wonderfully. you will need to know at least 3! We are going to learn a language called C# (pronounced C sharp). If I make a mistake with the professional tool I could quite easily lose my leg. It was developed by Microsoft Corporation for a variety of reasons. which is a highly dangerous and entertaining language which was invented in the early 1970s. The managed code is fussed over by the system which runs it.4.4 C# There are literally hundreds of programming languages around. As I am not an experienced chain saw user I would expect it to come with lots of built in safety features such as guards and automatic cut outs. having borrowed (or improved) features provided by these languages. If I. and enable direct access to parts of the underlying computer system. This makes sure that it is hard (but probably not impossible) to crash your computer running managed code. some political and others marketing. 1. during your career you will have to learn more than just one. but do not think that it is the only language you will ever learn. 1. some technical. If I was a real lumberjack I would go out and buy a professional chain saw which has no safety features whatsoever but can be used to cut down most anything. Rob Miles. To get the maximum possible performance. They are simple enough to be made sense of by computer programs and they reduce ambiguity. because of all the safety stuff I might not be able to cut down certain kinds of tree.Computers and Programs C# Programming languages get around both of these problems. If you ever make the mistake of calling the language C hash you will show your ignorance straight away! C# is a very flexible and powerful programming language with an interesting history. causing your programs to run more slowly. However. and was specially designed for this. In programming terms what this means is that C lacks some safety features provided by other programming languages. However.4. The origins of both Java and C++ can be traced back to a language called C. so I have a much greater chance of crashing the computer with a C program than I do with a safer language. So what do I mean by that? Consider the chain saw. but if it crashes it is capable of taking the computer C# Programming © Rob Miles 2010 14 . These will make me much safer with the thing but will probably limit the usefulness of the tool. something the amateur machine would not let happen.1 Dangerous C I referred to C as a dangerous language.e. C# bears a strong resemblance to the C++ and Java programming languages. if I do something stupid C will not stop me. An unmanaged program goes faster. This makes the language much more flexible. all this fussing comes at a price.
for now the thing to remember is that you need to show your wonderful C# program to the compiler before you get to actually run it.Computers and Programs C# with it. but I am not going to tell you much about it just yet. and debugger. 1. How you create and run your programs is up to you. The first thing it does is check for errors in the way that you have used the language itself.4 Making C# Run You actually write the program using some form of text editor .4. each of which is in charge of part of the overall system. C# is a great language to start learning with as the managed parts will make it easier for you to understand what has happened when your programs go wrong. It is provided in a number of versions with different feature sets. which is a great place to write programs. Another free resources is the Microsoft . The C# language is supplied with a whole bunch of other stuff (to use a technical term) which lets C# programs do things like read text from the keyboard. The computer cannot understand the language directly. test and extend. An example of a warning situation is where you create something but don't use it for anything.e. There is a free version.NET Framework. C# is a compiled programming language. This provides a bunch of command line tools. The use of objects is as much about design as programming. set up network connections and the like. The compiler would tell you about this.3 C# and Objects The C# language is object oriented. in case you had forgotten to add a bit of your program. so a program called a compiler converts the C# text into the low level instructions which are much simpler. They are then located automatically when your program runs. It comprises the compiler. but may indicate that you have made a mistake somewhere. These low level instructions are in turn converted into the actual commands to drive the hardware which runs your program. The compiler will also flag up warnings which occur when it notices that you have done something which is not technically illegal. This is not because I don't know much about it (honest) but because I believe that there are some very fundamental programming issues which need to be addressed before we make use of objects in our programs. I am very keen on object oriented programming. i. along with an integrated editor. These extra features are available to your C# program but you must explicitly ask for them. Object Oriented Design makes large projects much easier to design. which is a great place to get started.4.5 Creating C# Programs Microsoft has made a tool called Visual Studio. We will look in more detail at this aspect of how C# programs work a little later. called Visual Studio Express edition. Objects are an organisational mechanism which let you break your program down into sensible chunks. It also lets you create programs which can have a high degree of reliability and stability. Later on we will look at how you can break a program of your own down into a number of different chunks (perhaps so several different programmers can work on it). 1.4.which may be part of the compiling and running system. which can be used to compile and run C# programs. Switching to unmanaged mode is analogous to removing the guard from your new chainsaw because it gets in the way. A compiler is a very large program which knows how to decide if your program is legal. 1. C# Programming © Rob Miles 2010 15 . and we have to know how to program before we can design larger systems. things that you type to the command prompt. print on the screen. Only if no errors are found by the compiler will it produce any output.
A variable is simply a named location in which a value is held whilst the program runs. Some parts of your program will simply provide this information to tell the compiler what to do.e. This is what the compiler acts on. The recipe would be a list of ingredients followed by a sequence of actions to perform on them. A program can be regarded as a recipe. The ingredients will be values (called variables) that you want your program to work with. C# also lets you build up structures which can hold more than one item. You will almost certainly end up with something which almost works. which you will then spend hours fiddling with to get it going. All computer languages support variables of one form or another. I am going to assume that you are using a computer which has a text editor (usually Notepad) and the .. for example a single structure could hold all the information about a particular bank customer. Rather than writing the program down on a piece of paper you instead put it into a file on the computer. The Human Computer Of course initially it is best if we just work through your programs on paper. i. but written for a computer to follow. The program itself will be a sequence of actions (called statements) that are to be followed by the computer. the best approach is to write (or at least map out) your solution on paper a long way away from the machine. This is not good technique.6 What Comprises a C# Program? If your mum wanted to tell you how to make your favourite fruitcake she’d write the recipe down on a piece of paper. It needs to know which external resources your program is going to use. You must also decide on sensible names that you will use to identify these items. I reckon that you write programs best when you are not sitting at the computer. To take these in turn: Controlling the Compiler .4. As part of the program design process you will need to decide what items of data need to be stored.NET framework.Computers and Programs C# I'm not going to go into details of how to download and install the . C# Programming © Rob Miles 2010 16 . A source file contains three things: instructions to the compiler information about the structures which will hold the data to be stored and manipulated. Storing the Data Programs work by processing data. not a cook. Once you are sitting in front of the keyboard there is a great temptation to start pressing keys and typing something in which might work. instructions which manipulate the data.NET framework installed. The data has to be stored within the computer whilst the program processes it. I am impressed by someone who turns up. often called a source file. It also can be told about any options for the construction of your program which are important. that is for other documents. types in the program and makes it work first time! 1. The C# compiler needs to know certain things about your program.
These kinds of messages are coloured red in this text. Identifiers and Keywords You give a name to each method that you create. your program ends. C# Programming © Rob Miles 2010 17 . They are added automatically by the editor as you write your program. In fact. To continue our cooking analogy. It can have any name you like. Your mum might add the following instruction to her cake recipe: Now write the words “Happy Christmas” on top of the cake in pink icing. Such a lump is called a method. The colours just serve to make the programs easier to understand. woodLength might a good choice when we want to hold the length of wood required. Seasoned programmers break down a problem into a number of smaller ones and make a method for each. She is using double quote characters to mark the text that is to be drawn on the cake. which are used during the cooking process. Later on we will look at the rules and conventions which you must observe when you create identifiers. The C# language actually runs your program by looking for a method with a special name. and when Main finishes. It can return a value which may or may not be of interest. In a recipe a keyword would be something like "mix" or "heat" or "until". these are things like mixing bowls and ovens. for example add two numbers together and store the result. it is what needs to be written. These save you from "re-inventing the wheel" each time you write a program. The names that you invent to identify things are called identifiers. for example ShowMenu or SaveToFile. They would let you say things like "heat sugar until molten" or "mix until smooth". and you try to make the name of the function fit what it does. A statement is an instruction to perform one particular operation. and C# works in exactly the same way. so that your program can look at things and decide what to do. In the case of C# you can lump statements together to form a lump of program which does one particular task. Colours and Conventions The colours that I use in this text are intended to line up with the colours you will see when you edit your programs using a professional program editor such as the one supplied as part of Visual Studio. instruction to do something is in a C# program is called a statement. Main. you'll find that programs look a lot like recipes. The C# language also has a huge number of libraries available which you can use. or very large. Text in a Computer Program There are two kinds of text in your program. and your program can contain as many methods as you see fit. You also create identifiers when you make things to hold values. Keywords will appear blue in some of the listings in this text. One method may refer to others. The words which are part of the C# language itself are called keywords. Objects Some of the things in the programs that we write are objects that are part of the framework we are using. A method can be very small. We will look at methods in detail later in these notes. A single. This method is called when your program starts running. There are the instructions that you want the computer to perform and there are the messages that you want the program to actually display in front of the user.Computers and Programs C# Describing the Solution The actual instructions which describe your solution to the problem must also be part of your program. The really gripping thing about programs is that some statements can change which statement is performed next. and do not have any special meaning. ―Happy Christmas‖ is not part of the instructions. simple. The names of objects will be given in a different shade of blue in some of the listings in this text.
widthString = Console. glassArea. Then we will use additional features of the C# language to improve the quality of the solution we are producing. height = double. woodLength = 2 * ( width + height ) * 3. heightString = Console.Parse(widthString). C# Programming © Rob Miles 2010 18 . We will start by creating a very simple solution and investigating the C# statements that perform basic data processing.WriteLine( "The area of the glass is " + glassArea + " square metres" ) . heightString. and you could run it. We can now go through each line in turn and try to see how it fits into our program.ReadLine(). class GlazerCalc { static void Main() { double width. The actual work is done by the two lines that I have highlighted. Broadly speaking the stuff before these two lines is concerned with setting things up and getting the values in to be processed. This is the problem we set out to solve as described in section0. 2.ReadLine(). Console. height. string widthString.1. width = double. Console.1 A First C# Program The first program that we are going to look at will read in the width and height of a window and then print out the amount of wood and glass required to make a window that will fit in a hole of that size.Simple Data Processing A First C# Program 2 Simple Data Processing In this chapter we are going to create a genuinely useful program (particularly if you are in the double glazing business). glassArea = 2 * ( width * height ) . woodLength. If you gave it to a C# compiler it would compile.25 .Parse(heightString).1 The Program Example Perhaps the best way to start looking at C# is to jump straight in with our first ever C# program. 2. } } Code Sample 1 . The stuff after the two lines is concerned with displaying the answer to the user.GlazerCalc Program This is a valid program.WriteLine ( "The length of the wood is " + woodLength + " feet" ) . Here it is: using System.
A class is a container which holds data and program code to do a particular job. in that the compiler now knows that if someone tries to use the value returned by this method.e. in order to stop someone else accidentally making use of the value returned by our Main method. This means that if I refer to something by a particular name the compiler will look in System to see if there is anything matching that name. this must be a mistake. This is an instruction to the C# compiler to tell it that we want to use things from the System namespace. We have namespaces in our conversations too. There is a convention that the name of the file which contains a particular class should match the class itself. as we shall see later. But for now I'd be grateful if you'd just make sure that you put it here in order to make your programs work properly. Except for Main.cs. just make sure that you pick sensible names for the classes that you create. This method (and there must be one. You need to invent an identifier for every class that you create. and only one such method) is where your program starts running. the word static in this context means "is part of the enclosing class and is always here". In the case of C# the System namespace is where lots of useful things are described. don't worry too much about classes. One of these useful things provided with C# is the Console object which will let me write things which will appear on the screen in front of the user. A C# program is made up of one or more classes.Simple Data Processing A First C# Program using System. static This keyword makes sure that the method which follows is always present. For now. In programming terms the void keyword means that the method we are about to describe does not return anything of interest to us. A big part of learning to program is learning how to use all the additional features of the system which support your programs. but a class can contain much more than that if it needs to. C# Programming © Rob Miles 2010 19 . This makes our programs safer. When your program is loaded and run the first method given control is the one called Main. If I am using the "Firefighter" namespace I'm saying something less good. We will use other namespaces later on. Oh. If you miss out the Main method the system quite literally does not know where to start. void A void is nothing. If I want to just refer to this as Console I have to tell the compiler I'm using the System namespace. if I am using the "Football" namespace and I say “That team is really on fire” I'm saying something good. However. Main You choose the names of your methods to reflect what they are going to do for you. In the case of our double glazing calculator the class just contains a single method which will work out our wood lengths and glass area. I've called ours GlazerCalc since this reflects what it does. i. When we get to consider objects we will find that this little keyword has all kinds of interesting ramifications. In some cases we write methods which return a result (in fact we will use such a method later in the program). class GlazerCalc Classes are the basis of object oriented programming. The method will just do a job and then finish. in other words the program above should be held in a file called GlazerCalc. we are explicitly stating that it returns nothing. and one other thing. A namespace is a place where particular names have meaning. variable you. height = double. but I think it makes it slightly clearer. this time it is important that you notice the use of parenthesis to modify the order in which values are calculated in the expression. for two panes of glass). This line repeats the calculation for the area of the glass. It is a string of text which is literally just in the program.25 . so no conversion is required. Note that I use a factor of 3. except that this one takes what it is given and then prints it out on the console. not instructions to the compiler itself. The string of text is enclosed in double quote characters to tell the compiler that this is part of a value in the program. The other items in the expression are called operands. These are what the operators work on. The + and * characters in the expression are called operators in that they cause an operation to take place. the plus here means something completely different 2.WriteLine This is a call of a method. In this case it means "add two strings together". Normally C# will work out expressions in the way you would expect. woodLength = 2*(width + height)*3. We have seen it applied to add two integers together. i.e. so I did what you would do in mathematics. This is the actual nub of the program itself.25 to allow for the fact that the customer wants the length of wood in feet. so I multiply the result in meters by this factor. just like the ReadLine method.25 feet in a meter. followed by addition and subtraction. 2 Another TV show reference C# Programming © Rob Miles 2010 23 . ( This is the start of the parameters for this method call. In the above expression I wanted to do some parts first. Console. It takes the height and width values and uses them to calculate the length of wood required. The calculation is an expression much like above. glassArea = 2 * ( width * height ) . There are around 3. We have seen these used in the calls of Parse and also ReadLine "The length of the wood is " This is a string literal. + Plus is an addition operator.Parse(heightString). This is the bit that does the work. There is no need to do this particularly. These two statements simply repeat the process of reading in the text of the height value and then converting it into a double precision value holding the height of the window. all multiplication and division will be done first. Note that the area is given in square meters.Simple Data Processing A First C# Program heightString = Console. I put brackets around the parts to be done first. This makes the program clearer.ReadLine(). When I write programs I use brackets even when the compiler does not need them. I've put one multiplication in brackets to allow me to indicate that I am working out two times the area (i.e.
03 The string "2. use a plus with this and you perform arithmetic". woodLength This is another example of context at work. Fortunately it can do this. in the context it is being used at the moment (added to the end of a string) it cannot work like that. This would perform a numeric calculation (2. Consider: Console. + " feet" Another concatenation here. adding (or concatenating) them to produce a single result. The variable woodLength is tagged with metadata which says "this is a double precision floating point value. Would regard the + as concatenating two strings. Here it is with operators. C# Programming © Rob Miles 2010 24 . Whenever I print a value out I always put the units on the end. Previously we have used woodLength as a numeric representation of a value.Simple Data Processing A First C# Program You will have to get used to the idea of context in your programs.0 + 3. between two double precision floating point numbers it means "do a sum". You can think of all of the variables in our program being tagged with metadata (there is that word again) which the compiler uses to decide what to do with them.0) and produce a double precision floating point value. However. We are adding the word feet on the end. It is very important that you understand precisely what is going on here. Here it has a string on the left hand side. The C# compiler must therefore ask the woodLength data item to convert itself into a string so it can be used correctly in this position. When the method is called the program first assembles a completed string out of all the components. This makes it much easier to ensure that the value makes sense. In the case of the previous +. in this program the length of the wood required.0" + 3. ) The bracket marks the end of the parameter being constructed for the WriteLine method call. use a plus with this and you concatenate". It then passes the resulting string value into the method which will print it out on the console.0 ).0 + 3.0" has the text of the value 3. giving the output: 5 But the line of code: Console. We have seen this with namespaces.0 ). It would ask the value 3 to convert itself into a string (sounds strange – but this is what happens. This means that it is going to perform string concatenation rather than mathematical addition. It would then produce the output: 2.WriteLine ( "2. The variable heightString is tagged with information that says "this is a string. This difference in behaviour is all because of the context of the operation that is being performed. and so the program works as you would expect.0 added on the end.WriteLine ( 2. The C# system uses the context of an operation to decide what to do. This result value would then be asked to provide a string version of itself to be printed.
One of the things that you will have noticed is that there is an awful lot of punctuation in there.WriteLine ( "The length of the wood is " + woodLength + " feet" ) . } Now for some really important stuff. Punctuation That marks the end of our program. JustlikeIfindithardtoreadenglishwithouttheproperspacing I find it hard to read a program if it has not been laid out correctly. glassArea. This simply indicates that the compiler is too stupid to make sense of what you have given it! You will quickly get used to hunting for and spotting compilation errors.string widthString. In C# everything exists inside a class. When the compiler sees this it says to itself "that is the end of the Main method". woodLength. I do not do this because I find such listings artistically pleasing. We have added all the behaviours that we need. we only want the one method in the class. the compiler still needs to be told that we have reached the end of the program. The program is essentially complete. one of the things you will find is that the compiler does not always detect the error where it takes place.Console.woodLength = 2 * ( width + height ) * 3.height = double.25 .Simple Data Processing A First C# Program . I do it because otherwise I am just about unable to read the program and make sense of what it does.Console.class GlazerCalc{static void Main(){double width. A class is a container for a whole bunch of things. } The second closing brace has an equally important job to the first. A block of code starts with a { and ends with a }. And so we use the second closing brace to mark the end of the class itself. note that just because the compiler reckons your program is OK is no guarantee of it doing what you want! Another thing to remember is that the layout of the program does not bother the compiler.ReadLine(). heightString.although if anyone writes a program which is laid out this way they will get a smart rap on the knuckles from me! Programmer’s Point: Program layout is very important You may have noticed the rather attractive layout that I have used when I wrote the program. the following is just as valid: using System.ReadLine(). height. If we want to (and we will do this later) we may put a number of methods into a class. This first close brace marks the end of the block of code which is the body of the Main method. C# Programming © Rob Miles 2010 25 . It marks the end of the class GlazerCalc.width = double. Items inside braces are indented so that it is very clear where they belong. For now however.Parse(widthString). However.widthString = Console.WriteLine( "The area of the glass is " + glassArea + " square metres" ) . The semi-colon marks the end of this statement. otherwise you will get what is called a compilation error. including methods. However.} } . This is vital and must be supplied exactly as C# wants it.Parse(heightString).heightString = Console. consider the effect of missing out a "(" character.glassArea = 2 * ( width * height ) .
Because we know that it works in terms of ons and offs it has problems holding real values. What the data actually means is something that you as programmer decide (see the above digression on data). These are referred to as reals. This provides us with the ability to perform the data processing part of programs. A variable is a named location where you can store something. The type of the variable is part of the metadata about that variable. and what other types of data we can store in programs that we write.2 Storing Numbers When considering numeric values there are two kinds of data: Nice chunky individual values. You tell C# about a variable you want to create by declaring it. You also need to choose the type of the variable (particular size and shape of box) from the range of storage types which C# provides.e.2.too little may result in the wrong values being used. for example the number of sheep in a field. In the second case we can never hold what we are looking at exactly. specifically designed to hold items of the given type. the speed of a car. i. For each type of variable the C# language has a way in which literal values of that type are expressed. Nasty real world type things. You can think of it as a box of a particular size with a name painted on the box. otherwise it is useless. To handle real values the computer actually stores them to a limited accuracy. Programs also contain literal values. The declaration also identifies the type of the thing we want to store. We also need to consider the range of possible values that we need to hold so that we can choose the appropriate type to store the data. 2.2 Manipulating Data In this section we are going to take a look at how we can write programs that manipulate data. These are real. it operates entirely on patterns of bits which can be regarded as numbers. Think of this as C# creating a box of a particular size. Programs operate on data. This means that when we want to store something we have to tell the computer whether it is an integer or a real. A literal value is just a value in your program which you use for some purpose. teeth on a cog. how values can be stored. for example the current temperature. Even if you measure a piece of string to 100 decimal places it is still not going to give you its exact length .1 Variables and Data In the glazing program above we decided to hold the width and the height of the windows that we are working on in variables that we described as double. 2.2. they are integral. When you are writing a specification you should worry about the precision to which values are to be held. the length of a piece of string. you always have an exact number of these items. A computer is digital. Before we can go much further in our programming career we need to consider just what this means. which we hope is adequate (and usually is). In the first case we can hold the value exactly. C# Programming © Rob Miles 2010 26 .Simple Data Processing Manipulating Data 2. The box is tagged with some metadata (there is that word again) so that the system knows what can be put into it and how that box can be used. Too much accuracy may slow the machine down . These are referred to as integers. A programming language must give you a way of storing the data you are processing. retrieved and generally fiddled with. apples in a basket. You chose the name to reflect what is going to be stored there (we used sensible names like woodLength in the above program).you could always get the value more accurately.
647 If you want to hold even larger integers than this (although I've no idea why you'd want this) there is a long version.Simple Data Processing Manipulating Data Storing integer values Integers are the easiest type of value for the computer to store. This creates a variable with could keep track of over two thousand million sheep! It also lets a program manipulate "negative sheep" which is probably not meaningful (unless you run a sheep bank of course and let people borrow them). The only issue is one of range.483. An example of an integer variable would be something which kept track of the number of sheep in a field: int numberOfSheep. int. not an integer. if I add one to the value in this variable the system may not detect this as an error. in the range -2. This is because the numbers are stored using "2's complement" notation.000 sheep and the number of sheep never goes negative you must add this behaviour yourself. Which could cause my program big problems. can hold frighteningly large numbers in C#. In this statement the 127 is regarded as an sbyte literal. When you edit your program source using Visual Studio (or another code editor that supports syntax highlighting) you will find that the names of types that are built into the C# language (such as int and float) are displayed in blue. If I am using one of the "shorter" types the literal value is regarded by the compiler as being of that type: sbyte tinyVal = 127. because 255 is the biggest possible value of the type can hold. C# provides a variety of integer types. C# Programming © Rob Miles 2010 27 . The bigger the value the larger the number of bits that you need to represent it. In fact this may cause the value to "wrap round" to 0. as shown above. However. Remember that the language itself is unaware of any such considerations. If I put the value 255 into a variable of type byte this is OK.147. Programmer’s Point: Check your own maths Something else which you should bear in mind is that a program will not always detect when you exceed the range of a variable.648 to 2. Each value will map onto a particular pattern of bits. integer literal values An integer literal is expressed as a sequence of digits with no decimal Point: 23 This is the integer value 23. This means that if I do something stupid: sbyte tinyVal = 128. If you want to make sure that we never have more than 1.147. I could use it in my program as follows: numberOfSheep = 23 . depending on the range of values you would like to store: sbyte byte short ushort int uint long ulong char Note that we can go one further negative than positive.483..
with real numbers the compiler is quite fussy about how they can and can't be combined.7E308 and a precision of 15 digits. C# Programming © Rob Miles 2010 28 . Unlike the way that integers work.5E-45 to 3. A standard float value has a range of 1. Storing real values "Real" is a generic term for numbers which are not integers. This process is known as casting and we will consider it in detail a bit later. This is takes up more computer memory but it has a range of 5. If you want more precision (although of course your programs will be use up more computer memory and run more slowly) you can use a double box instead (double is an abbreviation for double precision). An example of a float variable could be something which held the average price of ice cream: float averageIceCreamPriceInPence. if you want the ultimate in precision but require a slightly smaller range you can use the decimal type. When it comes to putting literal values into the program itself the compiler likes to know if you are writing a floating point value (smaller sized box) or double precision (larger sized box). real literal values There are two ways in which you can store floating point numbers. decimal robsOverdraft. This uses twice the storage space of a double and holds values to a precision of 28-29 digits. An example of a double variable could be something which held the width of the universe in inches: double univWidthInInches.4605284E15 This is a double precision literal value which is actually the number of meters in a light year.5f A double literal is expressed as a real number without the f: 3.Simple Data Processing Manipulating Data (the maximum value that an sbyte can hold is 127) the compiler will detect that I have made a mistake and the program will not compile. C# provides a type of box which can hold a real number. Finally. as float or as double.5 You can also use exponents to express double and float values: 9. This means that you have to take special steps to make sure that you as programmer make clear that you want this to happen and that you can live with the consequences. hence the name float. This is because when you move a value from a double precision variable into an ordinary floating point one some of the precision is lost. They have a decimal point and a fractional part. It is used in financial calculations where the numbers are not so large but they need to be held to very high accuracy. not as good as most pocket calculators). A float literal can be expressed as a real number with an f after it: 2.e. Depending on the value the decimal point floats around in the number.0E-324 to 1.4E48 with a precision of only 7 digits (i. If you put an f on the end it becomes a floating point literal value.
char literal values You express a character by enclosing it in single quotes: 'A' This means "the character A". This is a sequence of characters which starts with a special escape character. An example of a character variable could be something which held the command key that the user has just pressed: char commandKey. The escape character is the \ (backslash) character. and most programmers. C# Programming © Rob Miles 2010 29 . at other times it will be a string. A character is what you get when you press a key on a keyboard or display a single character on the screen..2. You can use them as follows: char beep = '\a' . Some clear the screen when you send the Form feed character. C# uses a character set called UNICODE which can handle over 65. It is what your program would get if you asked it to read a character off the keyboard and the user held down shift and pressed A. If you are editing your program using an editor that supports syntax highlighting a character literal is shown in red.000 different character designs including a wide range of foreign characters.Simple Data Processing Manipulating Data Programmer’s Point: Simple variables are probably best You will find that I. Character Escape Sequences This leads to the question "How do we express the ' (single quote) character". 2. Escape in this context means "escape from the normal hum-drum conventions of just meaning what you are and let's do something special". C# provides variables for looking after both of these types of information: char variables A char is type of variable which can hold a single character. This can be in the form of a single character. Some systems will make a beep when you send the Alert character to them.3 Storing Text Sometimes the information we want to store is text. This is achieved by the use of an escape sequence. This may seem wasteful (it is most unlikely I'll ever need to keep track of two thousand million sheep) but it makes the programs easier to understand. tend to use just integers (int) and floating point (float) variable types.
This is represented in hexadecimal (base 16) as four sixteens and a single one (i. or it can be very long. The bad news is that you must express this value in hexadecimal which is a little bit harder to use than decimal. The line breaks in the string are preserved when it is stored. string variables A type of box which can hold a string of text. 41). The verbatim character has another trick.and try to ring the bell. In C# a string can be very short. string literal values A string literal value is expressed enclosed in double quotes: "this is a string" The string can contain the escape sequences above: "\x0041BCDE\a" If we print this string it would print out: ABCDE . which is that you can use it to get string literals to extend over several lines: @"The quick brown fox jumps over the lazy dog" This expresses a string which extends over three lines. However. As an example however. If I am just expressing text with no escape characters or anything strange I can tell the compiler that this is a verbatim string.e.Simple Data Processing Manipulating Data Note that the a must be in lower case. C# Programming © Rob Miles 2010 30 . because there are special characters which mean "take a new line" (see above) it is perfectly possible for a single string to hold a large number of lines of text. you can express a character literal as a value from the Unicode character set. If you wish. A string variable can hold a line of text. Character code values We have already established that the computer actually manipulates numbers rather than actual letters. for example "War and Peace" (that is the book not the three words). I do this by putting an @ in front of the literal: @"\x0041BCDE\a" If I print this string I get: \x0041BCDE\a This can be useful when you are expressing things like file paths. for example "Rob". if at all. C# uses the Unicode standard to map characters onto numbers that represent them. An example of a string variable could be something which holds the line that the user has just typed in: string commandLine. I can therefore put this in my program as: char capitalA = '\x0041' . The good news is that this gives you access to a huge range of characters (as long as you know the codes for them). Note that I have to put leading zeroes in front of the two hex digits. I happen to know that the Unicode value for capital a (A) is 65. The best news of all is that you probably don't need to do this kind of thing very often.
This illustrates another metadata consideration. In the example above I've used the double type to hold the width and height of a window.5 pounds (needing the use of float) I will store the price as 150 pence. Upper and lower case letters are different. These are the only two values which the bool type allows. Sometimes that is all you want. However. An example of a bool variable could be one which holds the state of a network connection: bool networkOK. this makes the job much simpler. This is really stupid. One of the golden rules of programming. you might think that being asked to work with the speed of a car you would have to store a floating point value. Also when considering how to store data it is important to remember where it comes from. Here are a few example declarations. According to the Mills and Boon romances that I have read. For example. Programmer’s Point: Think about the type of your variables Choosing the right type for a variable is something of a skill. They introduce a lack of precision that I am not too keen on.4 Storing State using Booleans A bool (short for boolean) variable is a type of box which can hold whether or not something is true. bool literal values These are easily expressed as either true or false: networkOK = true . It does not take into account the precision required or indeed how accurately the window can be measured. I would suspect that my glazing salesman will not be able to measure to accuracy greater than 1 mm and so it would make sense to only store the data to that precision. float jim . Instead you just need to hold the states true or false.Simple Data Processing Manipulating Data 2. one of which are not valid (see if you can guess which one and why): int fred . After the letter you can have either letters or numbers or the underscore "_" character. I find that with a little bit of ingenuity I can work in integers quite comfortably. C# Programming © Rob Miles 2010 31 . the best relationships are meaningful ones.2.5 Identifiers In C# an identifier is a name that the programmer chooses for something in the program. We will see other places where we create identifiers.e. 2. rather than store the price of an item as 1. i. when you find out that the speed sensor only gives answers to an accuracy of 1 mile per hour.2. along with "always use the keyboard with the keys uppermost" is: Always give your variables meaningful names. find out how it is being produced before you decide how it will be stored. char 29yesitsme . If you are storing whether or not a subscription has been paid or not there is no need to waste space by using a type which can hold a large number of possible values. I tend to use floating point storage only as a last resort. As an example. when you are given the prospect of storing floating point information. C# has some rules about what constitutes a valid identifier: All identifiers names must start with a letter. Fred and fred are different identifiers. The name of a variable is more properly called an identifier.
2. second. 2. Expressions An expression is something which can be evaluated to produce a result. presumably because of the "humps" in the identifier which are caused by the capitals. We can then use the result as we like in our program. and get the value out. An assignment gives a value to a specified variable. These are assignment statements. The value which is assigned is an expression. second and third.Simple Data Processing Manipulating Data The convention in C# for the kind of variables that we are creating at the moment is to mix upper and lower case letters so that each word in the identifier starts with a capital: float averageIceCreamPriceInPence. which must be of a sensible type (note that you must be sensible about this because the compiler. The last three statements are the ones which actually do the work. They should be long enough to be expressive but not so long that your program lines get too complicated. for example consider the following: class Assignment { static void Main () { int first. as we already know. The equals in the middle is there mainly to confuse us.6 Giving Values to Variables Once we have got ourselves a variable we now need to know how to put something into it. } } The first part of the program should be pretty familiar by now. the thing you want to assign and the place you want to put it. operators and operands. I like to think of it as a gozzinta (see above). This is sometimes called camel case. But I could live with it. There are two parts to an assignment. second = 2 . second = second + first . Within the Main function we have declared three variables. first = 1 . These are each of integer type. first. Expressions can be as simple as a single value and as complex as a large calculation. third . it does not mean equals in the numeric sense. C# does this by means of an assignment statement. which means that: 2 = second + 1.is a piece of programming naughtiness which would cause all manner of nasty errors to appear. They are made up of two things. Programmer’s Point: Think about the names of your variables Choosing variable names is another skill you should work at. . C# Programming © Rob Miles 2010 32 . does not know or care what you are doing). Gozzintas take the result on the right hand side of the assignment and drop it into the box on the left. Remember that you can always do sensible things with your layout to make the program look OK: averageIceCreamPriceInPence = computedTotalPriceInPence / numberOfIceCreams. Perhaps the name averageIceCreamPriceInPence is a bit over the top in this respect.
2. Note that we use exactly the same character as for unary minus. Because these operators work on numbers they are often called the numeric operators. as in the final example. Note that this means that the first expression above will therefore return 14 and not 20. It then looks for the next ones down and so on until the final result is obtained. I am listing the operators with the highest priority first. It is also possible to use operators in a way which causes values to be moved from one type to another. note the use of the * rather than the more mathematically correct but confusing x. Here are a few example expressions: 2 + 3 * 4 -1 + 3 (2 + 3) * 4 These expressions are worked out (evaluated) by C# moving from left to right. -1. but it will do for now. A literal value is something which is literally there in the code. In the program above first. e. because of the difficulty of drawing one number above another on a screen we use this character instead Addition. This can cause problems as we shall see now. In the program above + is the only operator. one each side. This is not a complete list of all the operators available. what they do and their precedence (priority). If you want to force the order in which things are worked out you can put brackets around the things you want done first. Most operators work on two operands.2. When C# works out an expression it looks along it for all the operators with the highest priority and does them first. third are identifiers and 2 is a literal value. It is probably not worth getting too worked up about this expression evaluation as posh people call it. subtraction. It worries about whether or not the operation I'm about C# Programming © Rob Miles 2010 33 . multiplication.Simple Data Processing Manipulating Data Operands Operands are things the operators work on. division. They are usually literal values or the identifiers of variables. just as in traditional maths all the multiplication and division is performed first in an expression. followed by the addition and subtraction. A literal value has a type associated with it by the compiler. Unary means applying to only one item. the minus that C# finds in negative numbers. generally speaking things tend to be worked out how you would expect them. C# does this by giving each operator a priority. Operators Operators are the things which do the work: They specify the operation to be performed on the operands. second. Being a simple soul I tend to make things very clear by putting brackets around everything. For completeness here is a list of all operators. just as you would yourself. * / + unary minus. Again.7 Changing the Type of Data Whenever I move a value from one type to another the C# compiler gets very interested in what I am doing. But of course you should remember that some of them (for example +) can be used between other types of data as well. provided you make sure that you have as many open ones as close ones.g. You can put brackets inside brackets if you want.
the cast is doomed to fail. as the writer of the program. However: float x = 1.would cause the compiler to complain (even though at the moment the variable x only holds an integer value).Simple Data Processing Manipulating Data to perform will cause data to be lost from the program. If I am packing for a trip I will take a case. float x = i. A cast takes the form of an additional instruction to the compiler to force it to regard a value in a particular way. However. . each type of variable has a particular range of possible values. float f = (float) d .the program will not notice but the user certainly will! C# Programming © Rob Miles 2010 34 .would cause an error as well. This is "narrowing". In the above code the message to the compiler is "I don't care that this assignment could cause the loss of information. I do not think of this as a failing in C#. float f = d . at the cost of assuming you know what you are doing. if I change to a bigger case there is no problem. will take the responsibility of making sure that the program works correctly". It is up to you when you write your program to make sure that you never exceed the range of the data types you are using . I.999 . Casting We can force C# to regard a value as being of a certain type by the use of casting. If I decide to switch to a smaller case I will have to take everything out of the large case and put it into the smaller one. As we saw above. so I have to leave behind one of my shirts. In C# terms the "size" of a type is the range of values (the biggest and smallest) and the precision (the number of decimal places).. You can regard casting as the compiler's way of washing its hands of the problem. If you are widening there is no problem. This works fine because the floating point type can hold all the values supported by the integer type. The value which gets placed in i will be invalid. This means that if you do things like this: int i . For example: double d = 1. for example: double d = 1.5. The compiler is concerned that you may be discarding information by such an assignment and treats it as an error. int i = x .5. . It considers every operation in terms of "widening and narrowing" values. Widening and Narrowing The general principle which C# uses is that if you are "narrowing" a value it will always ask you to explicitly tell it that this is what you want to do. It gives you great flexibility. You cast a value by putting the type you want to see there in brackets before it. i = (int) 123456781234567890. Note that this applies within a floating point values as well. The bigger case will take everything that was in the smaller case and have room for more. and the range of floating point values is much greater than that for integers... Nothing in C# checks for mistakes like this. But it might not have room. If a program fails because data is lost it is not because the compiler did something silly. To understand what we mean by these terms we could consider suitcases. since the compiler knows that a double is wider than a float. . This means that if I write: int i = 1 .
4 is a double precision value when expressed as a literal.25 feet in a meter). the more accurate answer of 0. x = 3. It therefore would calculate this to be the integer value 0 (the fractional part is always truncated).Simple Data Processing Manipulating Data A cast can also lose information in other ways: int i . If you put an f after the value this is regarded as a floating point value. . However. The C# compiler knows that it is daft to divide the value 3. You should remember that this truncation takes place whenever you cast from a value with a fractional part (float. If the two are floating point it says that the result should be floating point.would compile correctly. To make life easier the creators of C# have added a different way we can express a floating point literal value in a program.4 . decimal) into one without. consider the following: 1/2 1/2.will be treated with the contempt they richly deserve.0 by the string "stupid". The code above takes 1. This process discards the fractional part. This is so that statements like: int i . double. x = 3. x = (float) 3.25 to convert the length value from meters to feet (there are about 3. This can lead to problems.8 Types of Data in Expressions When C# uses an operator. even though the original number was much closer to 2. should give an integer result. This code looks perfectly legal. which means that the variable I will end up with the value 1 in it. C# keeps careful track of the things that it is combining. i = (int) 1.999 . and the variable x has been declared as a floating point. Not so. so that the assignment works.5. consider this: float x . i = 3. . The compiler thinks that the first expression. These are just values you want to use in your calculations. This is because the literal value 3.0 You might think that these would give the same result. C# Programming © Rob Miles 2010 35 . Essentially. If I want to put a floating point literal value into a floating point variable I can use casting: float x . This means that: float x . it makes a decision as to the type of the result that is to be produced. it is not. Casting and Literal Values We have seen that you can put "literal" values into your program. because it involves a floating point value would however be evaluated to give a double precision floating point result. This casts the double precision literal into a floating point value.999 (which would be compiled as a value of type double) and casts it to int. 2. if the two operands are integer it says that the result should be integer.4f . For example. However. in our double glazing program we had to multiply the wood length in meters by 3.2. and this includes how it allows literal values to be used. The second expression.4 .4 / "stupid" . which involves only integers.
The tablets are always sold in bottles of 100. As an example. Later on we will see that the + operator. If you just divide the number of tablets by 100 an integer division will give you the wrong answer (for any number of tablets less than 100 your program will tell you that 0 bottles are needed). string heightString = Console. and the number of bottles that he needs. One way to solve this is to add 99 to the number of tablets before you C# Programming © Rob Miles 2010 36 . The code that actually does the work boils down to just a few lines which read in the data.2.WriteLine("The area of the glass is " + glassArea + " square metres" ) . woodLength = 2 * ( width + height ) * 3. i.ReadLine(). the only hard part is figuring out how many bottles that are needed for a particular number of tablets. height = double.WriteLine ( "The length of the wood is " + woodLength + " feet" ) . It may not affect the result of the calculation but it will inform the reader of what I am trying to do. float fraction . Console. double width = double.Simple Data Processing Manipulating Data The way that an operator behaves depends on the context of its use. Programmer’s Point: Casts can add clarity I tend to put the casts in even if they are not needed. Console. glassArea = 2 * ( width * height ) . You can very easily modify your program to do this job.9 Programs and Patterns At this point we can revisit our double glazing program and look at the way that it works. consider another friend of yours.25 . who runs a chemist shop. 2.Parse(heightString). this can make the program clearer.Parse(widthString). He wants a program that will work out the total cost of tablets that he buys. can be used between strings to concatenate them together. } } The (float) cast in the above tells the compiler to regard the values in the integer variables as floating point ones. If you want complete control over the particular kind of operator the compiler will generate for you the program must contain explicit casts to set the correct context for the operator. so that we get 1. "Ro" + "b" would give the result "Rob". He enters the cost of the tablets and the number he wants. using System. Console. The interesting thing about this is that it is a pattern of behaviour which can be reused time and time again. store it in an appropriate type of location and then uses the stored values to calculate the result that the user requires: string widthString = Console.ReadLine(). class CastDemo { static void Main () { int i = 3. which normally performs a numeric calculation. fraction = (float) i / (float) j .e.WriteLine ( "fraction : " + fraction ) . j = 2 .5 printed out rather than 1.
1 Software as a story Some people say that writing a program is a bit like writing a story. A good program is well laid out. In this section we are going to consider how we can give our programs that extra level of complexity. They may need to repeat things until something is true. 2.Simple Data Processing Writing a Program perform the division. int bottleCount = ((tabletCount + 99) / 100) .WriteLine ( "The number of bottles is " + bottleCount ) . This makes the active part of the program as follows: int bottleCount = ((tabletCount + 99) / 100) . forcing the number of bottles required to "round up" any number of tablets greater than 0. C# Programming © Rob Miles 2010 37 . string pricePerBottleString = Console. Part of the skill of a programmer is identifying the nature of a problem in terms of the best pattern to be used to solve it. we will need to create programs which do things which are more complex that this. The different blocks should be indented and the statements spread over the page in a well formed manner. and look at the general business of writing programs. They may need to read in a large amount of data and then process that in a number of different ways. 2. We can then put the rest of the code around this to make a finished solution: Remember that if you divide two integers the result is always rounded down and the fractional part discarded. However. int salePrice = bottleCount * pricePerBottle . Both conform to a pattern of behaviour (read data in. process it. I have found that some computer manuals are works of fiction.ReadLine(). The interesting thing here is that the program for the chemist is actually just a variation on the program for the double glazing salesman. print it out) which is common to many applications. but programs are something else. At no point should the hapless reader be forced to backtrack or brush up on knowledge that the writer assumes is there. Console. Any time that you are asked to write a program that reads in some data.ReadLine(). int tabletCount = int. int salePrice = bottleCount * pricePerBottle . The various components should be organised in a clear and consistent way. They just read data in. I think that while it is not a story as such. works out some answers and then prints out the result you can make use of this pattern.WriteLine( "The total price is " + salePrice ) . It should look good on the page.Parse(tabletCountString). I'm not completely convinced that this is true.Parse(pricePerBottleString). They may have to make a decision based on the data which they are given. It should have good punctuation and grammar.3. All the names in the text should impart meaning and be distinct from each other. string tabletCountString = Console.3 Writing a Program The programs that we have created up until now have been very simple. do something with it and then print out the result. int pricePerBottle = int. a good program text does have some of the characteristics of good literature: It should be easy to read. Console.
Often you will come across situations where your program must change what it does according to the data which is given to it. You can also use comments to keep people informed of the particular version of the program. If you chose sensible identifiers you should find that your program will express most of what it does directly from the code itself. straight line chosen depending on a given condition repeated according to a given condition C# Programming © Rob Miles 2010 38 .Simple Data Processing Writing a Program It should be clear who wrote it. You will be very surprised to find that you quickly forget how you got your program to . But don't go mad. A big part of a well written program is the comments that the programmer puts there. // move on to the next customer I've annotated the statement to give the reader extra information about what it actually does.3. Basically there are three types of program flow: 1. I will ignore everything following until I see a */ which closes the comment. They help to make your program much easier to understand. If you change what you wrote you should add information about the changes that you made and why. */ Be generous with your comments.” As an example: /* This program works out glass and wood required for a double glazing salesman. There is a chance that it might take you to the right place. Line Comments Another form of comment makes use of the // sequence. 2. Programmer’s Point: Don't add too much detail Writing comments is a very sensible thing to do. 3. This marks the start of a comment which extends to the end of that particular line of code. Block Comments When the C# compiler sees the "/*" sequence which means the start of a comment it says to itself: “Aha! Here is a piece of information for greater minds than mine to ponder. 2.2 Controlling Program Flow Our first double glazing program is very simple. If you write something good you should put your name on it. A program without comments is a bit like an aeroplane which has an autopilot but no windows. // add one to goatCount This is plain insulting to the reader I reckon. when it was last modified and why. it runs straight through from the first statement to the last. and then stops. and the name of the programmer who wrote it – even if it was you. but it will be very hard to tell where it is going from the inside. It is useful for putting a quick note on the end of a statement: position = position + 1 . and when it was last changed. to
MIN_WIDTH = 0.0. MAX_HEIGHT = 3.WriteLine ( "Using minimum" ) . height = double. width = double. and also much easier to change.75 and 3. string widthString. what I would like to do is replace each number with something a bit more meaningful. heightString = Console. We can therefore modify our double glazing program as follows: using System. for example: const double MAX_WIDTH 5.141592654. We can do this by making a variable which is constant.\n\n" ) . glassArea. widthString = Console. This means that you can do things like: circ = rad * 2 * PI . This both more meaningful (we are using PI not some anonymous value) and makes the program quicker to write.Write ( "Give the width of the window : " ).e.ReadLine().0 .0 . if (width < MIN_WIDTH) { Console. Anywhere you use a magic number you should use a constant of this form. Now I could just use the values 0. I do not like the idea of "magic numbers" in programs.0 .Parse(heightString). } if (width > MAX_WIDTH) { Console. height.ReadLine(). If. i.75 . These come from the metadata I was so careful to gather when I wrote the specification for the program. for some reason. width = MIN_WIDTH . class GlazerCalc { static void Main() { double width. There is a convention that you always give constant variables names which are expressed in CAPITAL LETTERS. width = MAX_WIDTH .but these are not packed with meaning and make the program hard to change.5 .Write ( "Give the height of the window : " ). 0. MIN_HEIGHT = 0.Simple Data Processing Writing a Program values for heights and widths. C# Programming © Rob Miles 2010 42 . const double PI=3. 5.Parse(widthString). This is so that when you read your program you can tell which things have been defined.WriteLine ( "Using maximum" ) . woodLength. const const const const double double double double MAX_WIDTH = 5.5 metres I have to look all through the program and change only the appropriate values. } Console.5. it can never be changed. Console. my maximum glass size becomes 4. Console. Console.0 . heightString.WriteLine ( "Width is too large. This makes your programs much easier to read.WriteLine ( "Width is too small" ) .
Simple Data Processing Writing a Program if (height < MIN_HEIGHT) { Console. This means that if we get the number correctly first time the loop will execute just once. (the rest is finding out why the tool didn't do what you expected it to!). However I would still not call it perfect.WriteLine( "The area of the glass is " + glassArea + " square metres" ) . with the height having to be entered again. C# has three ways of doing this.\n\n" ) . depending on precisely what you are trying to do. What we would really like is a way that we can repeatedly fetch values for the width and height until we get one which fits.WriteLine ( "Using height = MAX_HEIGHT . Most of the skill of programming involves picking the right tool or attachment to do the job in hand.WriteLine ( "The length of the wood is " + woodLength + " feet" ) . Console. You might think that I have pulled a fast one here. do -. 2. } if (height > MAX_HEIGHT) { Console. is too large. If our salesman gives a bad height the program simply limits the value and needs to be re-run. i.while construction which looks like this: C# Programming © Rob Miles 2010 43 . Console.e. maximum" ) .\n\n" ) . } } This program fulfils our requirements.WriteLine ( "Using height = MIN_HEIGHT .3. woodLength = 2 * ( width + height ) * 3.while loop In the case of our little C# program we use the do -. glassArea = 2 * ( width * height ) .WriteLine( "Height Console. It will not use values incompatible with our specification.3 Loops Conditional statements allow you to do something if a given condition is true. minimum" ) . C# allows us to do this by providing looping constructions. } is too small. or a given number of times. However often you want to repeat something while a particular condition is true. Note that we get three methods not because we need three but because they make life easier when you write the program (a bit like an attachment to our chainsaw to allow it to perform a particular task more easily).25 .( "Height Console. In the case of our program we want to repeatedly get numbers in until while we are getting duff ones.
for loop Often you will want to repeat something a given number of times. raising the intriguing possibility of programs like: using System.e. while ( true ). (if you put the do in the compiler will take great delight in giving you an error message . The loop constructions we have given can be used to do this quite easily: C# Programming © Rob Miles 2010 44 . Rinse with warm water. If you think about how the loop above works the test is done after the code to be repeated has been performed once. Just as it is possible with any old chainsaw to cut off your leg if you try really hard so it is possible to use any programming language to write a program which will never stop. This allows us to repeat a chunk of code until the condition at the end becomes false. i. A condition in this context is exactly the same as the condition in an if construction. even if the test is bound to fail the statement is performed once. The universe implodes. Note that the test is performed after the statement or block.. How long it will run for is an interesting question. 2. 3. Repeat. You get bored with it. 2.e. } } This is a perfectly legal C# program. Your electricity runs out. Wet Your Hair Add Shampoo and Rub vigorously. the answer contains elements of human psychology.Simple Data Processing Writing a Program do statement or block while (condition) . 4. i. class Forever { public static void Main () { do Console. It reminds me of my favourite shampoo instructions: 1.WriteLine ( "Hello mum" ) . not a powerful chainsaw situation.but you had already guessed that of course!). we need to ask for a value before we can decide whether or not it is valid. I wonder how many people are still washing their hair at the moment? while loop Sometimes you want to decide whether or not to repeat the loop before you perform it. This is a chainsaw situation. energy futures and cosmology. For our program this is exactly what we want. 3.
The update is the statement which is performed to update the control variable at the end of each loop. Test to see if we have finished the loop yet and exit to the statement after the for loop if we have.WriteLine ( "Hello mum" ) . while ( i < 11 ) { Console. And serve you right. class ForLoop { public static void Main () { int i . Writing a loop in this way is quicker and simpler than using a form of while because it keeps all the elements of the loop in one place instead of leaving them spread about the program.e. The variable is given an initial value (1) and then tested each time we go around the loop. C# provides a construction to allow you to set up a loop of this form all in one: for ( setup . i < 11 . Put the setup value into the control variable. If you are so stupid as to mess around with the value of the control variable in the loop you can expect your program to do stupid things. 4. 5. or update it. 2. at which point the loop terminates and our program stops. The control variable is then increased for each pass through the statements. class WhileLoopInsteadOfFor { public static void Main () { int i . finish test .WriteLine ( "Hello mum" ) . 3. for ( i = 1 . update ) { things we want to do a given number of times } We could use this to re-write the above program as: using System.loop to continue. This means that you are less likely forget to do something like give the control variable an initial value. i = i + 1 . } } } The setup puts a value into the control variable which it will start with. Eventually it will reach 11. if you put i back to 0 within the loop it will run forever. Perform the statements to be repeated. Perform the update. This useless program prints out hello mum 10 times. It does this by using a variable to control the loop. i = i + 1 ) { Console. The precise sequence of events is as follows: 1. } } } The variable which controls things is often called the control variable.Simple Data Processing Writing a Program using System. Note that the three elements are separated by semicolons. i = 1 . Repeat from step 2. i. C# Programming © Rob Miles 2010 45 . The test is a condition which must be true for the for -. and is usually given the name i.
Simple Data Processing Writing a Program Programmer’s Point: Don't be clever/stupid Some people like to show how clever they are by doing cunning things with the setup.e. The goto is a special one that lets execution jump from one part of the program to another. one for every break in the loop above.. normally false becomes true when the loop has to be abandoned and the variable runningOK. for example in the following program snippet the variable aborted. which can do things other than simple assignment. they do not hold values as such. For this reason the goto is condemned as a potentially dangerous and confusing device. } ... bit we get to if aborted becomes true . This happens when you have gone as far down the statements as you need to. You can break out of any of the three kinds of loop. This is a standard programming trick that you will find very useful. This is a command to leave the loop immediately. normally true. Breaking Out of Loops Sometimes you may want to escape from a loop whilst you are in the middle of it. but can still lead to problems. while (runningOK) { complex stuff . The break construction is less confusing than the goto.. In every case the program continues running at the statement after the last statement of the loop. C# provides the continue keyword which says something along the lines of: C# Programming © Rob Miles 2010 46 .. your program may decide that there is no need or point to go on and wishes to leap out of the loop and continue the program from the statement after it.. The break statement lets you jump from any point in a loop to the statement just outside the loop. In this respect we advise you to exercise caution when using it.... } . i. if (aborted) { break . I call these people "the stupid people". I find it most useful so that I can provide a "get the heck out of here" option in the middle of something. You can do this with the break statement.. There is rarely need for such convoluted code. Your program would usually make some form of decision to quit in this way.. which programmers are often scared of. condition and update statements. Note that we are using two variables as switches. This can make the code harder to understand... When you are writing programs the two things which you should be worrying about are "How do I prove this works?" and "How easy is this code to understand?" Complicated code does not help you do either of these things.. becomes false when it is time to finish normally. more complex stuff . increment and test. Programmer’s Point: Be careful with your breaks The break keyword smells a little like the dread goto statement.. This means that if my program is at the statement immediately following the loop. Some programmers think they are very clever if they can do all the work "inside" the for part at the top and have an empty statement after it..
item processing stuff .. i. Essentially we want to keep asking the user for a value until we get one which is OK.e. additional item processing stuff ... Programmer’s Point: Get used to flipping conditions One of the things that you will have to come to terms with is the way that you often have to reverse the way you look at things. if (Done_All_We_Need_This_Time) continue . rather than the thing that you do. More Complicated Decisions We can now think about using a loop to test for a valid width or height... } The continue causes the program to re-run the loop with the next value of item if it is OK to do so.. do all the updating and stuff and go around if you are supposed to. Rather than saying "Read me a valid number" you will have to say "Read numbers while they are not valid". ... Go back to the top of the loop... item < Total_Items .. You can regard it as a move to step 2 in the list above. if you get a value which is larger than the maximum or smaller than the minimum ask for another. This means that you will often be checking to find the thing that you don't want.. Remember the notes about reversing conditions above when you write the code.. item=item+1 ) { . for ( item = 1 .Simple Data Processing Writing a Program Please do not go any further down this time round the loop. Complete Glazing Program This is a complete solution to the problem that uses all the tricks discussed above. C# Programming © Rob Miles 2010 47 .. To do this we have to combine two tests to see if the value is OK. Our loop should continue to run if: width > MAX_WIDTH or width < MIN_WIDTH To perform this test we use one of the logical operators described above to write a condition which will be true if the width is invalid: if ( width < MIN_WIDTH || width > MAX_WIDTH ) . In the following program the bool variable Done_All_We_Need_This_Time is set true when we have gone as far down the loop as we need to.
glassArea = 2 * ( width * height ) . do { Console. e.ReadLine(). widthString = Console.0 . However. C# allows us to be terser if we wish. const double MAX_WIDTH = 5. woodLength. It causes the value in that operand to be increased by one.Simple Data Processing Writing a Program using System.Parse(heightString).would do the same thing.0 . do { Console.WriteLine ( "The length of the wood is " + woodLength + " feet" ) . We can express ourselves more succinctly and the compiler can generate more efficient code because it now knows that what we are doing is adding one to a particular variable. width = double. The purpose of the above statement is to add 1 to the variable window_count.Write ( "Give the width of the window between " + MIN_WIDTH + " and " + MAX_WIDTH + " :" ). C# Programming © Rob Miles 2010 48 .operator which can be used to decrease (decrement) variables. height. glassArea.3.4 Operator Shorthand So far we have looked at operators which appear in expressions and work on two operands. const double MAX_HEIGHT = 3. } } 2. } while ( width < MIN_WIDTH || width > MAX_WIDTH ) . heightString. string widthString. Console.Parse(widthString).Write ( "Give the height of the window between " + MIN_HEIGHT + " and " + MAX_HEIGHT + " :" ).5 . woodLength = 2 * ( width + height ) * 3. Console. } while ( height < MIN_HEIGHT || height > MAX_HEIGHT ). height = double. const double MIN_HEIGHT = 0. the line: window_count++ .75 . class GlazerCalc { static void Main() { double width. The ++ is called a unary operator.g. heightString = Console. window_count = window_count + 1 In this case the operator is + and is operating on the variable window_count and the value 1.25 . because it works on just one operand. both in terms of what we have to type and what the computer will actually do when it runs the program.ReadLine(). const double MIN_WIDTH = 0. There is a corresponding -. You can see examples of this construction in the for loop definition in the example above. it is a rather long winded way of expressing this.WriteLine( "The area of the glass is " + glassArea + " square metres" ) .
but sometimes it can be very useful. += etc. I will leave you to find them! Statements and Values One of the really funky things about C# is that all statements return a value. The += operator combines addition and the assignment.Simple Data Processing Writing a Program The other shorthand which we use is when we add a particular value to a variable. .e. I still don't do it. Nowadays when I am writing a program my first consideration is whether or not the program is easy to understand. consider the following: i = (j=0). The fact that you can produce code like: height = width = speed = count = size = 0 . You determine whether you want to see the value before or after the sum by the position of the ++ : i++ ++i Means “Give me the value before the increment” Means “Give me the value after the increment” As an example: int i = 2. This is perfectly legal (and perhaps even sensible) C#. We could put: house_cost = house_cost + window_cost. this makes the whole thing much clearer for both you and the compiler! When you consider operators like ++ there is possible ambiguity. . but again is rather long winded. all return the value after the operator has been performed. Most of the time you will ignore this value. C# Programming © Rob Miles 2010 49 .would make j equal to 3.). This is perfectly OK. depending on which effect you want. which you can use in another statement if you like. This value can then be used as a value or operand. Programmer’s Point: Always strive for simplicity Don't get carried away with this. An assignment statement always returns the value which is being assigned (i. particularly when we get around to deciding things (see later). C# has some additional operators which allow us to shorten this to: house_cost += window_cost. which is OK.does not mean that you should. C# provides a way of getting either value. It has the effect of setting both i and j to 0. The other special operators. If you do this you are advised to put brackets around the statement which is being used as a value. I don't think that the statement above is very easy to follow – irrespective of how so much more efficient it is. in that you do not know if you get the value before or after the increment. so that the value in house_cost is increased by window_cost. In order to show how this is done. j . j = ++i .
This provides more flexibility. i.WriteLine ( "i: {0:0} f: {1:0.WriteLine ( "i: {1} f: {0}". i.56789 . counting from 0‖.56789 .56789 The {n} part of the string says ―parameter number n. f ) . double f = 1234.00}". which is useful if you are printing things like cheques. Console. This would print out: i: 150 f: 1234. for example {99}. A # in the format string means ―put a digit here if you have one‖: int i = 150 . f ) . This would print out: i: 150 f: 1234. Of course if I do something mad.56789 i: 150 f: 1234.##0} f: {1:##. Note that doing this means that if the number is an integer it is printed out as 12. If you have run any of the above programs you will by now have discovered that the way in which numbers are printed leaves much to be desired. Adjusting real number precision Placeholders can have formatting information added to them: int i = 150 . double f = 1234. Really Fancy Formatting If you want really fancy levels of control you can use the # character. To get around this C# provides a slightly different way in which numbers can be printed.Simple Data Processing Writing a Program 2.WriteLine ( "i: {0:0000} f: {1:00000. In the second write statement I have swapped the order of the numbers. This would print out: i: 0150 f: 01234.57 Note that if I do this I get leading zeroes printed out.56789 .5 Neater Printing Note that the way that a number is printed does not affect how it is stored in the program. i.3.00}". i ) . but floating point numbers seem to have a mind of their own. double f = 1234. When placed after a decimal point they can be used to control the number of decimal places which are used to express a value. Console.00}".##0. Integers seem to come out OK. Console. it just tells the printing method how it is supposed to be printed. Specifying the number of printed digits I can specify a particular number of digits by putting in a given number of zeroes: int i = 150 .00.57 The 0 characters stand for one or more digits. the WriteLine method will fail with an error. I have used the # character to get my thousands printed out with commas: C# Programming © Rob Miles 2010 50 . Console. f ). Using Placeholders in Print Strings A placeholder just marks the place where the value is to be printed.56789 . f. but since I've swapped the order of the parameters too the output is the same. f ). and is also somewhat easier to use if you are printing a large number of values. double f = 1234.WriteLine ( "i: {0} f: {1}". i. Console. Consider: int i = 150 .WriteLine ( "i: {0:#.
15:0. You can specify the print width of any item.00 Note that this justification would work even if you were printing a string rather than a number. C# Programming © Rob Miles 2010 51 .Simple Data Processing Writing a Program i: 150 f: 1.15:0.WriteLine ( "i: {0.56789 . This is so that when I print the value 0 I actually get a value printed. 0 ) .56789 . Console.10:0} f: {1. i. so if you want to print columns of words you can use this technique to do it. Console. otherwise when I print zero I get nothing on the page. f ) . f ) .00 The integer value is printed in a column 10 characters wide. Console.-10:0} f: {1. This is very useful if you want to print material in columns: int i = 150 . Printing in columns Finally I can add a width value to the print layout information.WriteLine ( "i: {0.10:0} f: {1. and the double is printed in a 15 character wide column. Note also though that I have included a 0 as the smallest digit.00}".57 0. Console. double f = 1234. which makes printing in columns very easy. 0.00}". This would produce the output: i: i: 150 f: 0 f: 1234. i. double f = 1234.57 f: 0.00}". 0 ) .-15:0. The value 150 does not have a thousands digit so it and the comma are left out. if I want the numbers left justified I make the width negative: int i = 150 .WriteLine ( "i: {0.WriteLine ( "i: {0. 0. even a piece of text. This would produce the output: i: 150 i: 0 f: 1234.-10:0} f: {1.00}".-15:0.234. At the moment the output is right justified.57 Note that the formatter only uses the # characters and commas that it needs.
methods don't actually make things possible. We will need both of these when we start to write larger programs. Then you can refer to this block of code to do something for you. This is not very efficient. it makes the program bigger and harder to write. WriteLine and ReadLine were provided by the creators of C# to give us a way of displaying text and reading information from the user. 3. The method is the block of code which follows the main part in our program. 3. Your programs will contain methods that you create to solve parts of the problem and they will also use methods that have been provided by other people.1 Methods We have already come across the methods Main. To do this you need to define a method to do the work for you. Essentially you take a block of code and give it a name. Method and Laziness We have already established that a good programmer is creatively lazy. C# lets us create other methods which are used when our program runs. Again. We have exactly the same piece of code to check widths and heights. Methods give us two new weapons: We can use methods to let us re-use a piece of code which we have written.1.Creating Programs Methods 3 Creating Programs In this chapter we will build on our programming abilities to make programs that are broken down into manageable chunks and find out how a program can store and manipulate large amounts of data using arrays. Main is the method we write which is where our program starts. In this section we are going to consider why methods are useful and how you can create your own. However. We can also use methods to break down a large task into a number of smaller ones.1 The Need for Methods In the glazing program above we spend a lot of time checking the values of inputs and making sure that they are in certain ranges. If we added a third thing to read. One of the tenets of this is that a programmer will try to do a given job once and once only. Up until now all our programs have been in a single method. As a silly example: C# Programming © Rob Miles 2010 52 . we would have to copy the code a third time. WriteLine and ReadLine. but they do help with the organisation of our programs. for example frame thickness. as with lots of features of the C# language. What we would like to do is write the checking code once and then use it at each point in the program. This is what methods are all about.
} } The method silly has a single integer parameter. As an example. The method is given the data to work on.WriteLine ("Hello"). class MethodDemo { static void silly ( int i) { Console. the methods ReadLine and Parse both return results that we have used in our programs: C# Programming © Rob Miles 2010 53 . } public static void Main () { silly ( 101 ) . When the method starts the value supplied for the parameter is copied into it.1. This means that when the program runs we get output like this: i is : 101 i is : 500 3. However. we can use methods to save us from writing the same code twice. You have already used this feature. silly ( 500 ) .Creating Programs Methods using System . consider the code below: using System .3 Return values A method can also return a value to the caller.1. In this case it contains a single statement which prints "Hello" on the console. 3. We simply put the code inside a method body and then call it when we need it. } public static void Main () { doit(). doit().WriteLine ( "i is : " + i ) . Within the block of code which is the body of this method we can use the parameter i as an integer variable. Each time I call the method the code in the block which is the body of the method is executed. } } In the main method I make two calls of doit. they become more useful if we allow them to have parameters. class MethodDemo { static void doit () { Console.2 Parameters At this point methods are useful because they let us use the same block of statements at many points in the program. A parameter is a means of passing a value into a method call. The result of running the above program would be: Hello Hello So.
WriteLine (prompt + " between " + low + " and " + high ). Console.4 A Useful Method Now we can start to write genuinely useful methods: static double readValue ( string prompt.Creating Programs Methods using System . } } The method sillyReturnPlus takes the value of the parameter and returns it plus one.WriteLine ( "i is : " + i ) .WriteLine ( "res is : " + res ) . Console. MIN_WIDTH. // prompt for the user double low.1. // lowest allowed value double high // highest allowed value ) { double result = 0. return result .ReadLine (). } public static void Main () { int res. } The readValue method is told the prompt to use and the lowest and the highest allowed values. class ReturnDemo { static int sillyReturnPlus ( int i) { i = i + 1. but this is actually a rather pointless thing to do: sillyReturnPlus (5). C# Programming © Rob Miles 2010 54 . It can then be used to read values and make sure that they are in range. return i.WriteLine ( "res is : " + res ) . It is actually OK to ignore the value returned by a method. string resultString = Console. The second reads an age between 0 and 70. We can use this method to read anything and make sure that value supplied is within a particular range. 0. The value that a method returns can be used anywhere in a program where a variable of that type could be used. double age = readValue ( "Enter your age: ". // will compile but do nothing useful 3. See if you can work out what this code would display: res = sillyReturnPlus (5) + sillyReturnPlus (7) + 1. MAX_WIDTH) . res = sillyReturnPlus (5). do { Console. result = double. double windowWidth = readValue ( "Enter width of window: ". The first call of readValue gets the width of a window. } while ( (result < low) || (result > high) ).Parse(resultString). in other words a call of sillyReturnPlus can take the place of an integer. Console. 70) .
From what we have seen of methods. Moving code around and creating methods is called refactoring. Console. } The method addOneToParam adds one to the parameter. 3. if I want to write a method which reads in the name and the age of a person I have a problem. There are two reasons why this is a good idea: 1: 2: It saves you writing the same code twice.1. Console. changing the value of a parameter does not change the value of the thing passed in. Method Limitations A method is very good for getting work done. When it runs it prints out the following: i is : 21 test is : 20 It is very important that you understand what is happening here. Once you have worked out what the customer wants and gathered your metadata you can start thinking about how you are going to break the program down into methods. C# Programming © Rob Miles 2010 55 . prints the result out and then returns: int test = 20 . The program works out the result of the expression to be passed into the method call as a parameter. If you do this you should consider taking that action and moving it into a method. This will be an important part of the Software Engineering we do later. As you will find out when you try. or write one which returns an age. So I could write a method which returns the name of a person. only the value of a parameter is passed into a call to a method.Creating Programs Methods Programmer’s Point: Design with methods Methods are a very useful part of the programmer's toolkit. because nothing the method does can affect variables in the code which calls it.WriteLine ( "i is : " + i ) . The value of test is being used in the call of addOneToParam. but it can be a bit limited because of the way that it works. addOneToParam(test + 99). They form an important part of the development process. addOneToParam(test).5 Parameter Passing By Value So. It then passes this value into the call. what do I mean by "passing parameters by value". This would print out: i is : 120 Pass by value is very safe. But I can’t write a method that returns both values at the same time as a method can only return one value. This means that you can write calls like: test = 20 . they can only return one value. Consider: static void addOneToParam ( int i) { i = i + 1. For example. it is a limitation when we want to create a method which returns more than one value. Often you find that as you write the code you are repeating a particular action. This is because. If a fault is found in the code you only have to fix it in one place.WriteLine ( "test is : " + test ) . However. unless you specify otherwise. The piece of C# above calls the method with the variable test as the parameter.
1. If you say ―Deliver the carpet to 23 High Street. In this case I can replace the ref with the keyword out: C# Programming © Rob Miles 2010 56 . You have to put the word ref in the method heading and also in the call of the method. However.7 Passing Parameters as "out" references When you pass a parameter as a reference you are giving the method complete control of it. rather than the content of the variable. it is going to have the “side effect” of changing something outside the method itself (namely the value of the parameter passed by reference).6 Parameter Passing By Reference It is very important that you understand how references work. when someone calls our addOneToRefParam method. Inside the method. rather than using the value of the variable the reference is used to get the actual variable itself. In other words. test = 20 . rather than sending the value of a variable into a method. Console. rather than passing in "20" in our above call the compiler will generate code which passes in "memory location 5023" instead (assuming that the variable test is actually stored at 5023). This is the case when we want to read in the name and age of a user. The program will say ―Get the value from location 5023‖ rather than ―The value is 1‖.Creating Programs Methods 3. Effectively the thing that is passed into the method is the position or address of the variable in memory. Using a reference in a program is just the same. Generally speaking you have to be careful with side effects. Console.WriteLine ( "test is : " + test ) . If you don't understand these you can't call yourself a proper programmer! Fortunately C# provides a way that. Sometimes you don't want this. Instead it just wants to deliver results to them. Instead you want to just allow the method to change the variable. and also has the word ref in front of the parameter.‖ you are giving the delivery man a reference. as someone reading your program has to know that your method has made changes in this way. 3. The code above makes a call to the new method. addOneToRefParam(ref test). Programmer’s Point: Document your side-effects A change by a method to something around it is called a side effect of the method. In this case the output is as follows: i is : 21 test is : 21 In this case the method call has made changes to the content of the variable.WriteLine ( "i is : " + i ) . In other words: “If you pass by reference. The original value of the parameters is of no interest to the method.1. we use them in real life all the time with no problems. } Note that the keyword ref has been added to the information about the parameter. instead of the value. So. Consider the code: static void addOneToRefParam ( ref int i) { i = i + 1. instead a reference to that variable is supplied instead. Note that C# is careful about when a parameter is a reference. This memory location is used by the method. changes to the parameter change the variable whose reference you passed” If you find references confusing you are not alone.
Note how I have rather cleverly used my readString method in my readInt one. result = int. I can call readPerson as follows: string name . This is very useful. 3. } while ( result == "" ) . readString and readInt. This makes it harder for me to get the program wrong. } The method readPerson reads the name and the age of a person. It also allows the compiler to make sure that somewhere in the method the output parameters are assigned values.Creating Programs Methods static void readPerson ( out string name.1. 0. } The readString method will read text and make sure that the user does not enter empty text. readPerson ( out name. result = Console. age = readInt ( "Enter your age : ". It means that if I mark the parameters as out I must have given them a value for the program to compile. int age . The readInt method reads a number within a particular range. so that the user can't enter an empty string when a number is required.Write ( prompt ) . do { string intString = readString (prompt) . Note that it uses two more methods that I have created. int low. } while ( ( result < low ) || ( result > high ) ).ReadLine (). int high ) { int result . as I am protected against forgetting to do that part of the job. The readPerson method will read the person and deliver the information into the two variables.8 Method Libraries The first thing that a good programmer will do when they start writing code is to create a set of libraries which can be used to make their job easier. out age ) . return result .Parse(intString). It makes sure that a programmer can't use the value of the parameter in the method. return result. 100 ) . We can use the methods as follows: C# Programming © Rob Miles 2010 57 . In the code above I have written a couple of library methods which I can use to read values of different types: static string readString ( string prompt ) { string result . } static int readInt ( string prompt. Note that I must use the out keyword in the call of the method as well. do { Console. out int age ) { name = readString ( "Enter your name : " ) . Programmer’s Point: Languages can help programmers The out keyword is a nice example of how the design of a programming language can make programs safer and easier to write.
or that the user does something that may cause it to fail. 3. { int j . If the method deals with the error itself this may lead to problems because the user may have no way of cancelling a command. } } The variable j has the scope of the inner block.e. 0. name = readString( "Enter your name : " ).2.2. The methods that we have created have often contained local variables. In other words the code: C# Programming © Rob Miles 2010 58 . i. as well as making sure that it does the required job! We are going to discuss error management later 3. This adds another dimension to program design. I could add methods to read floating point values as well.1 Scope and blocks We have already seen that a block is a number of statements which are enclosed in curly brackets. 3. I often solve this problem by having my methods return a code value. If the method involves talking to the user it is possible that the user may wish to abandon the method.2 Variables and Scope We have seen that when we want to store a quantity in our program we can create a variable to hold this information. This means that only statements in the inner block can use this variable. The scope of a local variable is the block within which the variable is declared. int age. 100). Programmer’s Point: Always consider the failure behaviours Whenever you write a method you should give some thought to the ways that it could fail. If the return value is non-zero this means that the method did not work and the value being returned is an error which identifies what went wrong. If the method passes the error on to the code which called it you have to have a method by which an error condition can be delivered to the caller. If the return value is 0 this means that the method returned correctly. Any block can contain any number of local variables. As far as the C# language is concerned you can declare a variable at any point in the block. variables which are local to that block. the variable result in the readInt method is local to the method block. age = readInt ( "Enter your age : ". The C# compiler makes sure that the correctly sized chunk of memory is used to hold the value and it also makes sure that we only ever use that value correctly. but you must declare it before you use it. This is called the scope of a variable.Creating Programs Variables and Scope string name. in that you also have to consider how the code that you write can fail. Each of these nested blocks can have its own set of local variables: { int i . When the execution of the program moves outside a block any local variables which are declared in the block are automatically discarded. The C# compiler also looks after the part of a program within which a variable has an existence.
i < 10 . but they disappear when the program execution leaves the block where they are declared. Note that this is in contrast to the situation in other languages. { int j . C# has an additional rule about the variables in the inner blocks: { int i . It is however perfectly acceptable to reuse a variable name in successive blocks because in this situation there is no way that one variable can be confused with another. } j = 99 . This allows you to declare a control variable which exists for the duration of the loop itself: for ( int i = 0 .would cause an error. { int i . } The variable i is declared and initialized at the start of the for loop and only exists for the duration of the block itself. } . where this behaviour is allowed. i = i + 1 ) { Console. so this code is OK. for example C++. In order to remove this possibility the compiler refuses to allow this. } } The first incarnation of i has been destroyed before the second. This is because inside the inner block there is the possibility that you may use the "inner" version of i when you intend to use the outer one. For loop local variables A special kind of variable can be used when you create a for loop construction.2. In order to keep you from confusing yourself by creating two versions of a variable with the same name. { int j . 3.WriteLine ( "Hello" ) . } } This is not a valid program because C# does not let a variable in an inner block have the same name as one in an outer block. } { int i . Variables Local to a Method Consider the following code: C# Programming © Rob Miles 2010 59 . as the variable j does not exist at this point in the program. { int i .3 Data Member in classes Local variables are all very well. We often need to have variables that exist outside the methods in a class.Creating Programs Variables and Scope { int i .
we will investigate the precise meaning of static later on. Class variables are very useful if you want to have a number of methods ―sharing‖ a set of data. and can’t be used anywhere else. For now you just have to remember to put in the static keyword. Console. If a statement in OtherMethod tries to use local the program will fail to compile. } } The variable local is declared and used within the Main method. Static class members Note that I have made the data member of the class static. display the board. and calculate the computer move could all use the same board information. } } The variable member is now part of the class MemberExample. static void OtherMethod () { member = 99. if you were creating a program to play chess it would be sensible to make the variable that stores the board into a member of the class. Console. The program above would print out: member is : 0 member is now : 99 This is because the call of OtherMethod would change the value of member to 99 when it runs. Then the methods that read the player move. This means declaring it outside the methods in the class: class MemberExample { // the variable member is part of the class static int member = 0 . OtherMethod(). C# Programming © Rob Miles 2010 60 . otherwise your program will not compile.WriteLine ("local is :" + local). For example. so that it is part of the class and not an instance of the class.Creating Programs Variables and Scope class LocalExample { static void OtherMethod () { local = 99. } static void Main () { Console.WriteLine ("member is now : " + member). This is not something to worry about just now.WriteLine ("member is : " + member). and so the Main method and OtherMethod can both use this variable. Variables which are Data Members of a Class If I want to allow two methods in a class to share a variable I will have to make the variable a member of the class. // this will not compile } static void Main () { int local = 0.
1000). ". 3. given a set of player scores from a game he wants a list of those scores in ascending order. and when. 0. 0. you agree on when the software must be finished and how you are going to demonstrate it to your new customer and you write all this down and get it signed.1000).1000). I am very careful to keep the number of member variables in a class to the minimum possible and use local variables if I only need to store the value for a small part of the code. 0. score6. C# Programming © Rob Miles 2010 61 . Marking a variable as const means ―the value cannot be changed‖.Creating Programs Arrays One common programming mistake is to confuse static with const. 0. ―This is easy‖ you think. ". Now you can start putting the data into each variable. score9. 0. ". score4. Our programs can also make decisions based on the values supplied by the user and also repeat actions a given number of times.1000).3. Alternatively you can think of it as stationary.1000). He would like to you write a program for him to help him analyse the performance of his players. ". 0. What the customer wants is quite simple.1000). score3. score10. Only one thing is missing. 0. When a game of cricket is played each member of the team will score a particular number of runs. Marking a variable with static means ―the variable is part of the class and is always present‖.1000). score5. With all this sorted. ". 0.3 Arrays We now know how to create programs that can read values in. score2. score11 . 3. Finally. and what information it will print out. calculate results and print them.1000). like the background static noise on your radio when you tune it off station. and we are going to find out about them next. The first thing to do is define how the data is to be stored: int score1. 0. score7 score8. to make this the perfect project. Bear in mind that if you make a variable a member of the class it can be used by any method in that class (which increases the chances of something bad happening to it). Arrays are one way to do this. You discuss sensible ranges (no player can score less than 0 or more than 1000 runs in a game). You decide how much money you are going to be paid. You draw out a rough version of what the program will accept. : ".1 Why We Need Arrays Your fame as a programmer is now beginning to spread far and wide. 0.1000). The next thing you do is refine the specification and add some metadata.1000). all you have to do now is write the actual program itself. ".1000). Programmer’s Point: Plan your variable use You should plan your use of variables in your programs. and therefore not going anywhere. 0. ". and that is the ability to create programs which store large amounts of data. It turns out that you now know about nearly all the language features that are required to implement every program that has ever been written. You should decide which variables are only required for use in local blocks and which should be members of the class. : ". If it helps you can think of static as something which is always with us. ". The next person to come and see you is the chap in charge of the local cricket team. ".
C# Programming © Rob Miles 2010 62 . Hmmmm.2 Array Elements Each compartment in the box is called an element. One thing adding to this confusion is the fact that this numbering scheme is not the same in other languages. This is very important. class ArrayDemo { public static void Main () { int [] scores = new int [11] . ―The first element has the subscript 0‖ then the best way to regard the subscript is as the distance down the array you have to travel to get to the element that you need. This means that you specify the element at the start of the array by giving the subscript 0. If you find this confusing.. Consider the following: using System. It then gets some pieces of wood and makes a long thin box with 11 compartments in it. it just goes to show that not everything about programming is consistent. } } } The int [] scores part tells the compiler that we want to create an array variable. When an array is created all the elements in the array are set to 0. In fact you can use any expression which returns an integer result as a subscript. but you should get a picture of what is going on here. The bit which makes the array itself is the new int [11]. scores [i+1] . we know that computers are very good at sorting this kind of thing. This is awful! There seems to be no way of doing it. I’m sorry about this.Creating Programs Arrays All we have to do next is sort them. We can then use things called subscripts to indicate which box in the row that we want to use. An array allows us to declare a whole row of a particular kind of box. C# provides us with a thing called an array. If you follow the rope from the scores tag you reach the array box. each large enough to hold a single integer. 3. for ( int i=0. This part is called the subscript. You can think of this as a tag which can be made to refer to a given array. after all. Actually. It then gets a piece of rope and ties the tag scores to this box. Array Element Numbering C# numbers the boxes starting at 0. It then paints the whole box red .. Visual Basic numbers array elements starting at 1. There is consequently no element scores [11]. 0.. it probably doesn't use wood or rope.. Just deciding whether score1 is the largest value would take an if construction with 10 comparisons! Clearly there has to be a better way of doing this. (as long as you don't fall off the end of the array).is quite OK.e. If you look at the part of the program which reads the values into the array you will see that we only count from 0 to 10. i=i+1) { scores [i] = readInt ( "Score : "..because boxes which can hold integers are red. Note that the thing which makes arrays so wonderful is the fact that you can specify an element by using a variable..3. i<11. When C# sees this it says ―Aha! What we need here is an array‖. i.. An attempt to go outside the array bounds of scores cause your program to fail as it runs. In the program you identify which element you mean by putting its number in square brackets [ ] after the array name.1000)..
If the call of Parse throws an exception the code in the catch block runs and will display a message to the user. If your program does not contain a catch for the exception it will be caught by a catch which is part of the run time system. which is managing the execution of your program inside the computer. This is useful if the code inside the try block could throw several different kinds of exception. Console. Within the catch clause the value of e is set to the exception that was thrown by Parse. the parse action takes place inside the try block. Note that once the exception has been thrown there is no return to the code in the try block. C# Programming © Rob Miles 2010 66 . If a user types in an invalid string the program above will write the text in the exception.Creating Programs Exceptions and Errors int age.3 The Exception Object When I pass a problem up to my boss I will hand over a note that describes it. The Exception object also contains other properties that can be useful.WriteLine(e. will look for the enclosing catch clause.4. An exception is a type of object that contains details of a problem that has occurred.4 Exception Nesting When an exception is thrown the run time system. if the parse fails the program will not display the message "Thank you". try { age = int. } catch (Exception e) { // Get the error message out of the exception Console. 3.WriteLine("Thank you"). The Exception type has a property called Message which contains a string describing the error. 3. } The catch now looks like a method call.Parse(ageString). Exceptions work in the same way. Console. This message is obtained from the exception that was thrown. Programs can have multiple levels of try – catch. The program above ignores the exception object and just registers to the exception event but we can improve the diagnostics of our program by catching the exception if we wish: int age. with the Exception e being a parameter to the method. This is exactly how it works.Message).4. and the program will use the catch which matches the level of the code in the try block. The code in this catch clause will display the exception details and then stop the program. } The code above uses Parse to decode the age string. since it means that the message reflects what has actually happened.Parse(ageString).WriteLine("Invalid age value"). When Parse fails it creates an exception object that describes the bad thing that has just happened (in this case input string not in the correct format). } catch { Console. try { age = int.e. i.WriteLine("Thank you"). However. which contains the message: Input string was not in a correct format.
and the program never returns to the try part of the program. In these situations any code following your try – catch construction would not get the chance to run. we know that when an exception is thrown the statements in the catch clause are called. try { // Code that } catch (Exception { // Code that } finally { // Code that // is thrown } might throw an exception outer) catches the exception is obeyed whether an exception or not C# Programming © Rob Miles 2010 67 .5 Adding a Finally Clause Sometimes there are things that your program must do irrespective of whether or not as exception is thrown. The faster you can get a fault to manifest itself the easier it is to identify the cause.4. releasing resources and generally tidying up. Statements inside the finally clause will run irrespective of whether or not the program in the try block throws an exception. not try and handle things by returning a null reference or empty item. Programmer’s Point: Don’t Catch Everything Ben calls this Pokemon® syndrome: “Gotta catch’em all”. The code in the catch clause could return from the method it is running within or even throw an exception itself. However. If someone asks your Load method to fetch a file that doesn’t exist the best thing it can do is throw a “file not found”. Fortunately C# provides a solution to this problem by allowing you to add a finally clause to your try-catch construction. 3. However. Returning a placeholder will just cause bigger problems later when something tries to use the empty item that was returned. Don’t feel obliged to catch every exception that your code might throw. If code in the innermost block throws an exception the run time system will find the inner catch clause. once execution leaves that inner block the outer catch is the one which will be run in the event of an exception being thrown.
4. You ask something like Enter the type of window: 1 = casement 2 = standard 3 = patio door Your program can then calculate the cost of the appropriate window by selecting type and giving the size.7 Exception Etiquette Exceptions are best reserved for situations when your program really cannot go any further.1 Making Multiple Decisions Suppose you are refining your double glazing program to allow your customer to select from a pre-defined range of windows. 3. When you come to write the program you will probably end up with something like: C# Programming © Rob Miles 2010 68 . Each method asks the relevant questions and works out the price of that kind of item. Most of the rest of C is concerned with making the business of programming simpler. A good example of this is the switch construction. You may find it rather surprising.5.Creating Programs The Switch Construction In the above code the statements in the finally part are guaranteed to run. or just before execution leaves the catch part of your program. 3. the next thing we need to consider is how to throw them. In this case I have used the somewhat unhelpful message ―Boom‖. I reserve my exceptions for catastrophic events that my program really cannot deal with and must pass on to something else. Throwing an exception might cause your program to end if the code does not run inside a try – catch construction. either when the statements in the try part have finished. You can even create your own custom exception types based on the one provided by the System use these in your error handling. Programmer’s Point: Plan your Exception Handling When you design a program you should consider what events count as “showstoppers” and how you are going to deal with them. but there is really very little left to know about programming itself. and you should too. If you are going to throw an exception this should be in a situation where your program really could not do anything else. This means that errors at this level are not worthy of exception throwing. 3.5 The Switch Construction We now know nearly everything you need to know about constructing a program in the C# language.4. 3. For example if a user of the double glazing program enters a window height which is too large the program can simply print the message ―Height too large‖ and ask for another value. This turns out to be very easy: throw new Exception("Boom"). When you make a new exception you can give it a string that contains the message the exception will deliver.6 Throwing an Exception Now that we know how to catch exceptions. The statement above makes a new exception and then throws it.
This is called the switch construction. } } } This would work OK. If you write the above using it your program would look like this. the next thing you need to do is write the code that will call the one that the user has selected. Once you have the methods in place. You have to write a large number of if constructions to activate each option. 3.Creating Programs The Switch Construction static void handleCasement () { Console.3 The switch construction Because you have to do this a lot C# contains a special construction to allow you to select one option from a number of them based on a particular value.WriteLine ( "Invalid number" ). } static void handlePatio () { Console. but is rather clumsy. } These methods are the ones which will eventually deal with each type of window.5.WriteLine("Handle patio"). We already have a method that we can use to get a number from the user (it is called readInt and is given a prompt string and high and low limits). 3. Our program can use this method to get the selection value and then pick the method that needs to be used.2 Selecting using the if construction When you come to perform the actual selection you end up with code which looks a bit like this: int selection . } else { Console. 1. } else { if ( selection == 3 ) { handlePatio() . selection = readInt ( "Window Type : ". 3 ) . Later you will go on and fill the code in (this is actually quite a good way to construct your programs). } static void handleStandard () { Console. C# Programming © Rob Miles 2010 69 . } else { if ( selection == 2 ) { handleStandard(). if ( selection == 1 ) { handleCasement().WriteLine("Handle Standard").5.WriteLine("Handle Casement"). At the moment they just print out that they have been called.
WriteLine ( "Invalid command" ) .Creating Programs The Switch Construction switch (selection) { case 1 : handleCasement (). It executes the case which matches the value of the switch variable. } This switch uses a string to control the selection of the cases. your users would not thank you for doing this. when the break is reached the switch is finished and the program continues running at the statement after the switch. case 2 : handleStandard () . in true C# tradition. default : Console. and of course if they type a character wrong the command is not recognised. In the same way as you break out of a loop. break . break . You can use the switch construction with types other than numbers if you wish: switch (command) { case "casement" : handleCasement (). break . case "patio" : handlePatio () .WriteLine ( "Invalid number" ) . Multiple cases You can use multiple case items so that your program can execute a particular switch element if the command matches one of several options: C# Programming © Rob Miles 2010 70 . However. Another other useful feature is the default option. default : Console. break . The break statement after the call of the relevant method is to stop the program running on and performing the code which follows. break . case 3 : handlePatio () . break . Of course this means that the type of the cases that you use must match the switch selection value although. break . This gives the switch somewhere to go if the switch value doesn't match any of the cases available. } The switch construction takes a value which it uses to decide which option to perform. the compiler will give you an error if you make a mistake. break . since it means that they have to type in the complete name of the option. in our case (sorry!) we put out an appropriate message. case "standard" : handleStandard () .
Data can flow up or down your stream. We know that you can store data in this way. break . so that streams can be used to read and write to files. 3. case "patio" : case "P" : handlePatio () . that is how we have kept all the programs we have created so far. These can be used to obtain a version of a string which is all in upper or lower case. which can make the testing of the commands much easier: switch (command.Creating Programs Using Files switch (command) { case "casement" : case "c" : handleCasement (). default : Console. However. case "standard" : case "s" : handleStandard () . We can write a C# program which creates a file on a Windows PC and then use the same program to create a file on a UNIX system with no problems. If you want to perform selection based on strings of text like this I’d advise you to take a look at the ToUpper and ToLower methods provided by the string type..WriteLine ( "Invalid command" ) .6. What we want to do is use C# to tell the operating system to create files and let us access them.ToUpper()) { case "CASEMENT" : case "C" : . in files.1 Streams and Files C# makes use of a thing called a stream to allow programs to work with files. the way in which you manipulate files in C# is the same for any computer..6 Using Files If you want your program to be properly useful you have to give it a way of storing data when it is not running. It is also easier to add extra commands if you use a switch since it are just a matter of putting in another case. Files are looked after by the operating system of the computer. I'd advise against putting large amounts of program code into a switch case. Instead you should put a call to a method as I have above. break .. Programmer’s Point: switches are a good idea Switches make a program easier to understand as well as quicker to write. The stream is the thing that links your program with the operating system of the computer you are using. A stream is a link between your program and a data resource. 3. break . The operating system actually does the. break . } The above switch will select a particular option if the user types the full part of the name or just the initial letter.
you will find out later how to do this. 3. StreamWriter writer . these are the StreamWriter and StreamReader types. If this happens. is implemented as a stream. C# has a range of different stream types which you use depending on what you want to do. This is potentially dangerous. writer = new StreamWriter("test. then the action will fail with an appropriate exception. The program performs operations on the file by calling methods on the stream object to tell it what to do. All that happens is that a brand new.txt already exists. This is exactly the same technique that is used to write information to the console for the user to read. In fact you can use all the writing features including those we explored in the neater printing section to format your output. Most useful programs ask the user whether or not an existing file should be overwritten.6.txt for output and connect the stream to it. which would be bad. and the write cannot be performed successfully. since the Console class.2 Creating an Output Stream You create a stream object just like you would create any other one. When the new StreamWriter is created the program will open a file called test. When the stream is created it can be passed the name of the file that is to be opened. which connects a C# program to the user. writer. The above statement calls the WriteLine method on the stream to make it write the text ―hello world‖ into the file test. A properly written program should probably make sure that any exceptions like this (they can also be thrown when you open a file) are caught and handled correctly. Each time you write a line to the file it is added onto the end of the lines that have already been written. In fact you are already familiar with how streams are used.6. perhaps your operating system is not able/allowed to write to the file or the name is invalid. Note however that this code does not have a problem if the file test. It means that you could use the two statements above to completely destroy the contents of an existing file. The variable writer will be made to refer to the stream that you want to write into. C# Programming © Rob Miles 2010 72 .3 Writing to a Stream Once the stream has been created it can be written to by calling the write methods it provides. the call of WriteLine will throw an exception. file is created in place of what was there. 3.txt. All of the streams are used in exactly the same way. If this process fails for any reason. by using new.WriteLine("hello world"). We are going to consider two stream types which let programs use files.Creating Programs Using Files C# program stream File in Windows A C# program can contain an object representing a particular stream that a programmer has created and connected to a file.txt"). empty. The ReadLine and WriteLine methods are commands you can give any stream that will ask it to read and write data. If your program got stuck writing in an infinite loop it is possible that it might fill up the storage device.
The full name of the Console class that you have been using to write text to the user is System. Any further attempts to write to the stream will fail with an exception. An open stream consumes a small.e. The designers of the C# language created a namespace facility where programmers can do the same kind of thing with their resources. The above uses the fully qualified name of the console resource and calls the method WriteLine provided by that resource. at the start of our C# programs.Creating Programs Using Files 3. Namespaces are all to do with finding resources. It will also be impossible to move or rename the file. If your program creates lots of streams but does not close them this might lead to problems opening other files later on. this object is defined in the System. Sorry about that. when we reflected on the need to have the statement using System. and the Greek ones in another.5 Streams and Namespaces If you rush out and try the above bits of code you fill find that they don’t work.WriteLine("Hello World"). We have touched on namespaces before. The using keyword allows us to tell the compiler where to look for resources. Forgetting to close a file is bad for a number of reasons: It is possible that the program may finish without the file being properly closed. using System. These resources are things like the Console object that lets us read and write text to the user.4 Closing a Stream When your program has finished writing to a stream it is very important that the stream is explicitly closed using the Close method: writer. The C# language provides the keywords and constructions that allow us to write programs. 3. There is something else that you need to know before you can use the StreamWriter type. a ―space where names have meaning‖.6.Close(). Once a file has been closed it can then be accessed by other programs on the computer. part of operating resource. So.txt and take a look at what is inside it. once the close has been performed you can use the Notepad program to open test. Like lots of the objects that deal with input and output. In fact it is quite OK to use this full form in your programs: System. quite literally.6. However. If your program has a stream connected to a file other programs may not be able to use that file.Console. Museum curators do this all the time. This statement tells the compiler to look in the System namespace for resources. but significant.IO namespace. They put all the Roman artefacts in one room. When the Close method is called the stream will write out any text to the file that is waiting to be written and disconnect the program from the file.Console. A C# installation actually contains many thousands of resources. close the file or suffer the consequences. Whenever the compiler finds an C# Programming © Rob Miles 2010 73 . we’ve not had to use this form because at the start of our programs we have told the compiler to use the System namespace to find any names it hasn’t seen before. A namespace is. i. Now we need to find out more about them. If you were in charge of cataloguing a huge number of items you would find it very helpful to lump items into groups. the Console class in the System namespace. but on top of this there are a whole lot of extra resources supplied with a C# installation. each of which must be uniquely identified. That is. In this situation some of the data that you wrote into the file will not be there. Once we have specified a namespace in a program file we no longer need to use the fully qualified name for resources from that namespace.
txt. StreamReader reader. reads the first line from the file.ReadLine(). Namespaces are a great way to make sure that names of items that you create don’t clash with those from other programmers.IO namespace.WriteLine(line).Close().txt"). TextReader reader = new StreamReader("Test. in that the program will create a stream to do the actual work.WriteLine("Hello World"). } reader. . while (reader. However.the compiler will look in the System namespace. In this case the stream that is used is a StreamReader. If the file can’t be found then the attempt to open it will fail and the program will throw an exception.WriteLine("Hello World").6.WriteLine (line). if your program reaches the end of the file the ReadLine method will return an empty string each time it is called. In other words.IO. If the programmer miss-types the class name: Consle. display it on the screen and then close the stream.txt").it knows to look in the System namespace for that object so that it can use the WriteLine method on it.Close().6 Reading from a File Reading from a file is very similar to writing. However. fail to find an object called Console and generate a compilation error. . and so you must include the above line for file handling objects to be available. just because you use a namespace. reader = new StreamReader("Test. We will see how you can create your own namespaces later on. It is possible to put one namespace inside another (just like a librarian would put a cabinet of Vases in the Roman room which he could refer to as Roman.txt and display every line in the file on the console. 3. The above program connects a stream to the file Test. reader. when the compiler sees the statement: Console. Detecting the End of an Input File Repeated calls of ReadLine will return successive lines of a file. The above program will open up the file test. This is the same error that you will get if you try to use the StreamWriter class without telling the compiler to look in the System. Console. Console. In other words. to use the file handing classes you will need to add the following statement at the very top of your program: using System. Fortunately the StreamReader object provides a property called EndOfStream that a program can use to determine when the end of the file has been reached.Vases) and so the IO namespace is actually held within the System namespace. The while loop will stop the program when the end of the file is reached.EndOfStream == false) { string line = reader.Creating Programs Using Files item it hasn’t seen before it will automatically look in the namespaces it has been told to use. C# Programming © Rob Miles 2010 74 . When the property becomes true the end of the file has been reached. string line = reader.ReadLine(). this does not imply that you use all the namespaces defined within it.
txt) then the system assumes the file that is being used is stored in the same folder as the program which is running. If you use Windows you will find that there several folders created for you automatically.6. You can create your own folders inside these (for example Documents\Stories).txt. the location of the folder and the name of the file itself.7 File Paths in C# If you have used a computer for a while you will be familiar with the idea of folders (sometimes called directories). If you have problems where your program is not finding files that you know are there. if you are running the program FileRead. The backslash (\) characters in the string serve to separate the folders along the path to the file. C# Programming © Rob Miles 2010 75 . which is in turn held in the folder 2009.Creating Programs Using Files 3.txt". Each file you create is placed in a particular folder. If you want to use a file in a different folder (which is a good idea.txt is in the MyProgs folder too. I’d advise you to make sure that your path separators are not getting used as control characters. path = @"c:\data\2009\November\sales. The above statements create a string variable which contains the path to a file called sales. This file is held in the folder November. One can be used for Documents. In other words. Note that I have specified a string literal that doesn’t contain control characters (that is what the @ at the beginning of the literal means) as otherwise the \ characters in the string will get interpreted by C# as the start of a control sequence. The location of a file on a computer is often called the path to the file. which is held in the folder data which is on drive C. another for Pictures and another one for Music.exe in the folder MyProgs then the above programs will assume that the file Test. If you don’t give a folder location when you open a file (as we have been doing with the file Test. These are used to organise information we store on the computer. The path a file can be broken into two parts. as data files are hardly ever held in the same place as programs run from) you can add path information to a filename: string path.
implement transactions that change the content of one or more items in the system) are common to many other types of programs. This equally as important. The bank manager has told us that the bank stores information about each customer. Bank Notes At the end of some sections there will be a description of how this new piece of C# will affect how we create our bank system. At the moment we are simply concerned with managing the account information in the bank. from a programming point of view it is an interesting problem and as we approach it we will uncover lots of techniques which will be useful in other programs that we might write.2 Enumerated Types These sound really posh. By setting out the scope at the beginning you can make sure that there are no unpleasant surprises later on.1 Bank System Scope The scope of a system is a description of the things that the system is going to do. account number. This is also. 4. This information includes their name.1. The program we are making is for a bank. the "United Friendly and Really Nice Bank of Lovely People ™". There are many thousands of customers and the manager has also told us that there are also a number of different types of accounts (and that new types of account are invented from time to time). Of course if C# Programming © Rob Miles 2010 76 . A lot of the things that our bank is going to do (store a large amount of information about a large number of individuals. otherwise known as the Friendly Bank.Creating Solutions Our Case Study: Friendly Bank 4 Creating Solutions 4. a statement of what the system will not do. However. as a customer will not usually have clear idea of what you are doing and may well expect you to deliver things that you have no intention of providing. by implication. Other data items might be added later.1 Our Case Study: Friendly Bank The bulk of this section is based on a case study which will allow you to see the features of C# in a strong context. balance and overdraft value. The system must also generate warning letters and statements as required. 4. address. search for information for a particular person. Programmer’s Point: Look for Patterns The number of different programs in the world is actually quite small. We will be creating the entire bank application using C# and will be exploring the features of C# that make this easy. from video games to robots. You are taking the role of a programmer who will be using the language to create a solution for a customer. If anyone asks you what you learnt today you can say "I learnt how to use enumerated types" and they will be really impressed. These notes should put the feature into a useful context. It is unlikely that you will get to actually implement an entire banking system during your professional career as a programmer (although it might be quite fun – and probably rather lucrative).
These types are called "enumerated types": enum SeaState { EmptySea. RowingBoat } . and must be managed solely in terms of these named enumerations. C# Programming © Rob Miles 2010 77 .Creating Solutions Enumerated Types they know about programming they'll just say "Oh. But if you think of "enumerated" as just meaning "numbered" things get a bit easier. Of course C# itself will actually represent these states as particular numeric values. However. Submarine. in that I have decided that I need to keep track of the sea and then I have worked out exactly what I can put in it. For example I must write: SeaState openSea . To understand what we are doing here we need to consider the problem which these types are intended to solve. Sample states Enumerated types are very useful when storing state information. I could do something with numbers if I like: Empty sea = 1 Attacked = 2 Battleship = 3 Cruiser = 4 Submarine = 5 Rowing boat = 6 However. We know that if we want to hold an integer value we can use an int type. 4. openSea = SeaState. My variable openSea is only able to hold values which represent the state of the sea contents. States are not quite the same as other items such as the name of a customer or the balance of their account. but how these are managed is not a problem for me. C# has a way in which we can create a type which has just a particular set of possible values. I am sort of assembling more metadata here. If we want to hold something which is either true or false we can use a bool. Cruiser.2. Battleship..EmptySea. Attacked. I have created a type called SeaState which can be used to hold the state of a particular part of the sea.1 Enumeration and states Enumerated sounds posh. this would mean that I have to keep track of the values myself and remember that if we get the value 7 in a sea location this is clearly wrong. you mean you’ve numbered some states" and not be that taken with it. For example. sometimes we want to hold a range of particular values or states. It can only have the given values above.
Every account will contain a variable of type AccountState which represents the state of that account. If this is the case it is sensible to create an enumerated type which can hold these values and no others enum AccountState { New. Closed } .2. Frozen. For example. This shows that these items are extra types I have created which can be used to create variables. "New". enum TrafficLight { Red. UnderOffer. like keywords are. Active.Red. 4. "Active". You should therefore use them a lot. The program becomes simpler to write. Sold. Green. for example int and double. but they are not actually part of the C# language. Amber } . For the bank you want to hold the state of an item as well as other information about the customer. OffTheMarket etc) then you should think in terms of using enumerated types to hold the values.2 Creating an enum type The new enum type can be created outside any class and creates a new type for use in any of my programs: using System. RedAmber. We now have a variable which can hold state information about an account in our bank. } } Every time that you have to hold something which can take a limited number of possible values.Creating Solutions Enumerated Types Note that types I create (like SeaState) will be highlighted by the editor in a blue colour which is not quite the same as keywords. Now we have reached the point where we are actually creating our own data types which can be used to hold data values that are required by our application. Previous we have used types that are part of C#. or states (for example OnSale. light = TrafficLight. easier to understand and safer. Programmer’s Point: Use enumerated types Enumerated types are another occasion where everyone benefits if you use them. we could have the states "Frozen". "Closed" and "Under Audit" as states for our bank account. UnderAudit. C# Programming © Rob Miles 2010 78 . It is important that you understand what is happening here. class EnumDemonstration { public static void Main () { TrafficLight light .
This is all very well.3 Structures Structures let us organise a set of individual values into a cohesive lump which we can map onto one of the items in the problem that we are working on. i. would be called a field. A structure is a collection of C# variables which you want to treat as a single entity. Negotiate an extortionate fee. 4.3. This is important in many applications.integer value account balance .e. and so on.2 Creating a Structure C# lets you create data structures. What we have is an array for each single piece of data we want to store about a particular customer. for example the overdraft value.string customer address . int [] balances = new int [MAX_CUST] . overdraft [0] holds the overdraft of the first customer. However it would me much nicer to be able to lump your record together in a more definite way. the lump of data for each customer would be called a record and an individual part of that lump. The Friendly Bank has commissioned an account storage system and you can use structures to make this easier.3. Establish precisely the specification. Like any good programmer who has been on my course you would start by doing the following: 1.Creating Solutions Structures 4. 4. In our program we are working on the basis that balance[0] holds the balance of the first customer in our database. get in written form exactly what they expect your system to do. int [] overdraft = new int [MAX_CUST] . In C# a lump of data would be called a structure and each part of it would be called a field. A sample structure From your specification you know that the program must hold the following: customer name . Consider how you will go about storing the data. 2. To help us with our bank database we could create a structure which could hold all the information about a customer: C# Programming © Rob Miles 2010 79 .integer value The Friendly Bank have told you that they will only be putting up to 50 people into your bank storage so.string account number .1 What is a Structure? Often when you are dealing with information you will want to hold a collection of different things about a particular item.integer value overdraft limit . string [] addresses = new string [MAX_CUST] . and you could get a database system working with this data structure. string [] names = new string [MAX_CUST] . If we were talking about a database (which is actually what we are writing). after a while you come up with the following: const int MAX_CUST = 50. AccountState [] states = new AccountState [MAX_CUST] . (Remember that array subscript values start at 0). int [] accountNos = new int [MAX_CUST] . 3.
Name . C# Programming © Rob Miles 2010 80 . public int Overdraft . public string Name . which contains all the required customer information. 4. so that: Bank [25]. (i. public int AccountNumber . We refer to individual members of a structure by putting their name after the struct variable we are using with a . the AccountNumber value in RobsAccount) You can do this with elements of an array of structures too. for example: RobsAccount.e. When the assignment is performed all the values in the source structure are copied into the destination: Bank[0] = RobsAccount. Closed } .would be the string containing the name of the customer in the element with subscript 25. This would copy the information from the RobsAccount structure into the element at the start of the Bank array.would refer to the integer field AccountNumber in the structured variable RobsAccount. called Bank which can hold all the customers. which can hold the information for a single customer. Frozen. UnderAudit. Active. public int Balance . public string Address . called Account. (full stop) separating them. Account [] Bank = new Account [MAX_CUST].Creating Solutions Structures struct Account { public AccountState State. This defines a structure. The second declaration sets up an entire array of customers. Having done this we can now define some variables: Account RobsAccount . The first declaration sets up a variable called RobsAccount.3 Using a Structure A program which creates and sets up a structure looks like this: using System. // enum enum AccountState { New. just as we would any other variable type. } . We can assign one structure variable to another.3.AccountNumber . can think of them as a bit like a luggage tag. The compiler therefore says.Creating Solutions Objects.3): error CS0165: Use of unassigned local variable ' RobsAccount' So. The account class is called.Name = "Rob". The problem is that when we compile the program we get this: ObjectDemo.Name = "Rob". But in the case of objects. in that it prints out the name "Rob". This looks like a declaration of a variable called RobsAccount. quite simply. The compiler knows this. class StructsAndObjectsDemo { public static void Main () { Account RobsAccount .cs(12. If you have the tag you can then follow the rope to the object it is tied to. RobsAccount. and so it gives me an error because the line: RobsAccount. in effect. this is not what it seems. "you are trying to follow a reference which does not refer to anything. Structures and References It then sets the name property of the variable to the string "Rob". } } The account information is now being held in a class. We solve the problem by creating an instance of the class and then connecting our tag to it. This is achieved by adding a line to our program: C# Programming © Rob Miles 2010 84 . therefore I am going to give you a 'variable undefined' error". in that they can be tied to something with a piece of rope. Such references are allowed to refer to instances of the Account. But when we create a reference we don't actually get one of the things that it refers to. Console. } . If we run this program it does exactly what you would expect. If the structure contained other items about the bank account these would be stored in the structure as well. rather than a structure. RobsAccount What you actually get when the program obeys that line is the creation of a reference called RobsAccount.is an attempt to find the thing that is tied to this tag and set the name property to "Rob". what is going on? To understand what is happening you need to know what is performed by the line: Account RobsAccount. Since the tag is presently not tied to anything our program would fail at this point. Creating and Using an Instance of a Class We can make a tiny change to the program and convert the bank account to a class: class Account { public string Name . . Account.WriteLine (RobsAccount. and I could use them in just the same way.Name ).
in that you can treat a reference as if it really was the object just about all of the time.4. I'll repeat that in a posh font: “An object is an instance of a class” I have repeated this because it is very important that you understand this. } } The line I have added creates a new Account object and sets the reference RobsAccount to refer to it.Creating Solutions Objects. The thing that new creates is an object. and what it can do. and so we use new to create it. Note that in the above diagram I have called the object an Account. RobsAccount = new Account(). Account RobsAccount Name: Rob We have seen this keyword new before.Name ). Console. } . A class provides the instructions to C# as to what is to be made. but for real object oriented satisfaction you have to have an object. and that means that we must manage our access to a particular object by making use of references to it. not RobsAccount. Structures are kind of useful. The new keyword causes C# to use the class information to actually make an instance. This is because an array is actually implemented as an object. RobsAccount. it is simply the one which RobsAccount is connected to at the moment. An object is an instance of a class.Name = "Rob". but you must remember that when you hold a reference you do not hold an instance. The two come hand in hand and are inseparable. Consider the following code: C# Programming © Rob Miles 2010 85 . we have to use references.WriteLine (RobsAccount. Actually this is not that painful in reality. We use it to create arrays.2 References We now have to get used to the idea that if we want to use objects. you hold a tag which is tied onto an instance… Multiple References to an Instance Perhaps another example of references would help at this point. class StructsAndObjectsDemo { public static void Main () { Account RobsAccount . 4. Structures and References class Account { public string Name . This is because the object instance does not have the identifier RobsAccount.
Name = "Jim".Name = "Rob".WriteLine (RobsAccount. Temp. Account Temp . This code makes an account instance. This means that any changes which are made to the object that Temp refers to will also be reflected in the one that RobsAccount refers to. No References to an Instance Just to complete the confusion we need to consider what happens if an object has no references to it: Account RobsAccount . Temp = RobsAccount. The question is. RobsAccount = new Account(). The question is: What happens to the first instance? Again. RobsAccount. Console. sets the name property of it to Rob and then makes another account instance.Name ). Structures and References Account RobsAccount .WriteLine (RobsAccount. This indicates a trickiness with objects and references.Creating Solutions Objects. because they are the same object. RobsAccount = new Account().WriteLine (RobsAccount. which has the name set to Jim. There is no limit to the number of references that can be attached to a single instance. this can be made clearer with a diagram: C# Programming © Rob Miles 2010 86 .WriteLine (RobsAccount.Name = "Jim". what would the second call of WriteLine print out? If we draw a diagram the answer becomes clearer: Account RobsAccount Name: Jim Temp Both of the tags refer to the same instance of Account. RobsAccount. since that is the name in the object that RobsAccount is referring to. Console. RobsAccount.Name ).Name ). Console. RobsAccount = new Account(). This means that the program would print out Jim.Name = "Rob". Console.Name ). The reference RobsAccount is made to refer to the new item. so you need to remember that changing the object that a reference refers to may well change that instance from the point of view of other objects.
Instead you just say ―The coin in the road on top of the hill is now yours‖. You should also remember that you can get a similar effect when a reference to an instance goes out of scope: { Account localVar .3 Why Bother with References? References don’t sound much fun at the moment. Programmer’s Point: Try to avoid the Garbage Collector While it is sometimes reasonable to release items you have no further use for. meaning another job for the garbage collector. 4. Consider a bank which contains many accounts.4. If we wanted to sort them into alphabetical order of customer name we have to move them all around. called the ―Garbage Collector‖ which is given the job of finding such useless items and disposing of them. you must remember that creating and disposing of objects will take up computing power. That is why we use references in our programs. Structures and References Account RobsAccount Name: Rob Account Name: Jim The first instance is shown ―hanging‖ in space. So why do we bother with them? To answer this we can consider the Pacific Island of Yap. with nothing referring to it. Note that the compiler will not stop us from ―letting go‖ of items like this. localVar = new Account(). C# Programming © Rob Miles 2010 87 .Creating Solutions Objects. it might as well not be there. } The variable localVar is local to the block. Just because the objects are disposed of automatically doesn’t mean that you should abuse the facility. This means that the only reference to the account is also removed. When I work with objects I worry about how much creating and destroying I am doing. The currency in use on this island is based around 12 feet tall stones which weigh several hundred pounds each. As far as making use of data in the instance is concerned. Indeed the C# language implementation has a special process.. In other words they use references to manage objects that they don’t want to have to move around. When you pay someone with one of these coins you don’t actually pick it up and give it to them. This means that when the program execution leaves the block the local variable is discarded.
and also speed up searching. Structures and References Sorting by moving objects around If we held the accounts as an array of structure items we would have to do a lot of work just to keep the list in order. If I want a sorted list of the items I just have to go as far down the ―lighter‖ side as I can and I will end up at the lightest. instead the references can be moved around. With references we just need to keep a number of arrays of references. The bank may well want to order the information in more than one way too. New objects can be added without having to move any objects. for example they might want to order it on both customer surname and also on account number. one can refer to a node which is ―lighter‖. We can get over this. the other to a node which is ―darker‖. Without references this would be impossible. Sorting by use of a tree In the tree above each node has two references. but if we want to add something to our sorted list we still have to move the references around.Creating Solutions Objects. each of which is ordered in a particular way: Sorting by using references If we just sort the references we don’t have to move the large data items at all. by structuring our data into a tree form. Then C# Programming © Rob Miles 2010 88 . References and Data Structures Our list of sorted references is all very good.
Reference Importance The key to this way of working is that an object can contain references to other objects. Just remember that references are an important mechanism for building up structures of data and leave it at that. The accounts will be held in the memory of the computer and.‖ Objects let us do this. Programmer’s Point: Data Structures are Important This is not a data structures document. But sometime in the future you are going to have to get your head around how to build structures using these things. in that I can look at each node and decide which way to look next until I either find what I am looking for or I find there is no reference in the required direction.. And if the manager comes along with a need for a new structure or view we can create that in terms of references as well.5 Designing With Objects We are now going to start thinking in terms of objects. I just find the place on the tree that they need to be hung on and attach the reference there. Sorting a list of references is very easy.Creating Solutions Designing With Objects I go up to the one above that (which must be the next lightest). This means that the only way to manipulate them is to leave them in the same place and have lists of references to them. for now we just need to remember that the reference and the object are distinct and separate. it is a programming document. object based design turns this on its head. and if possible get someone else to do it. The references are very small "tags" which can be used to locate the actual item in memory. Bank Notes: References and Accounts For a bank with many thousands of customers the use of references is crucial to the management of the data that they hold. Searching is also very quick. as well as the data payload. it will not be possible to move them around memory if we want to sort them. Then I go down the dark side (Luke) and repeat the process. The neat thing about this approach is also that adding new items is very easy. This means that we can offer the manager a view of his bank sorted by customer name and another view sorted in order of balance. in which case the item is not in the structure. don’t worry. a bit like President Kennedy did all those years ago: C# Programming © Rob Miles 2010 89 . This all comes back to the ―creative laziness‖ that programmers are so famous for. The reason that we do this is that we would like a way of making the design of our systems as easy as possible. We will consider this aspect of object use later. The thing that we are trying to do here is best expressed as: ―Put off all the hard work for as long as we can. and it would also be possible to have several such lists. 4. If you don’t get all the stuff about trees just yet. because of the size of each account and the number of accounts being stored.
We can get this behaviour by simply not providing a means by which it can be changed. RobsAccount. Each time I create an instance of the class I get all the members as well. We might even identify some things as being audited. For the sake of simplicity. along with what should be done. The account number of an account is something which is unique to that account and should never change.5. Instead we ask it to do these things for us.Balance = 99. If our specification is correct and they implement it properly. we don’t have to worry precisely how they made it work – we just have to sit back and take the credit for a job well done. That way we can easily find out if bad things are being done. since this is specially designed to hold financial values. class Account { public decimal Balance.Creating Solutions Designing With Objects ―And so. for now I’m just going to consider how I keep track of the balance of the accounts. the next thing we need to do is devise a way in which each of the actions can be tested. This brings us back to a couple of recurring themes in this document.Balance = 0. The design of our banking application can be thought of in terms of identifying the objects that we are going to use to represent the information and then specifying what things they should be able to do. In this section we are going to implement an object which has some of the behaviours of a proper bank account. We have seen that each of the data items in a class is a member of it and stored as part of it. C# Programming © Rob Miles 2010 90 . We have already seen that it is very easy to create an instance of a class and set the value of a member: Account RobsAccount . my fellow Americans: ask not what your country can do for you—ask what you can do for your country‖ (huge cheers) We don’t do things to the bank account. 4. It is important at design time that we identify what should not be possible. Programmer’s Point: Not Everything Should Be Possible Note that there are also some things that we should not be able to do with our bank account objects. Members of a class which hold a value which describes some data which the class is holding are often called properties. This means that any programmer writing the application can do things like: RobsAccount. RobsAccount = new Account(). The first thing is to identify all the data items that we want to store in it. we can consider our bank account in terms of what we want it to do for us. The reason that this works is that the members of the object are all public and this means that anybody has direct access to them. This will let me describe all the techniques that are required without getting bogged down too much. I’ve used the decimal type for the account balance. in that an object will keep track of what has been done to it. The really clever bit is that once we have decided what the bank account should do. And once we have decided on the actions that the account must perform. metadata and testing. we then might be able to get somebody else to make it do these things. } The Account class above holds the member that we need to store about the balance of our bank accounts. What a bank account object should be able to do is part of the metadata for this object.1 Data in Objects So.
3): error CS0122: 'PrivateMembers. This technology is the key to my defensive programming approach which is geared to making sure that. This means that the outside world no longer has direct access to it. my part of the program does not go wrong. Instead it is now private.balance = 0. but only using code actually running in the class. thanks for the vote of confidence folks. Consider the program: class Account { private decimal balance = 0. } The property is no longer marked as public.2 Member Protection inside objects If objects are going to be useful we have to have a way of protecting the data within them. Well. It turns out that I can change the value.cs(13. C# Programming © Rob Miles 2010 91 . . I want all the important data hidden inside my object so that I have complete control over what is done with it. now you can’t change it at all‖.Account. } } . The posh word for this is encapsulation.and take away all my money.amount . If we are going to provide a way of stopping this from happening we need to protect the data inside our objects.Creating Solutions Designing With Objects . If I write the code: RobsAccount. and stop the change from being made if I don’t like it. Ideally I want to get control when someone tries to change a value in my objects. } balance = balance . public bool WithdrawFunds ( decimal amount ) { if ( balance < amount ) { return false . return true.I will get an error when I try to compile the program: PrivateDemo. whatever else happens.balance' is inaccessible due to its protection level The balance value is now held inside the object and is not visible to the outside world. The first thing we need to do is stop the outside world from playing with our balance value: class Account { private decimal balance. 4.5. Changing private members I can tell what you are thinking at this point. in our bank program we want to make sure that the balance is never changed in a manner that we can't control. For example. You are thinking ―What is the point of making it private.
I don’t usually go that far. C# Programming © Rob Miles 2010 92 . } else { Console.). } } } This creates an account and then tries to draw five pounds out of it. because I reckon that the name of the member is usually enough. If you want to write a method which is only used inside a class and performs some special. If you don’t care about possible corruption of the member and you want your program to run as quickly as possible you can make a data member public. They would call their balance value m_balance so that class members are easy to spot. the rules can be broken on special occasions. and expect developers to adhere to these. This will of course fail. In fact. This means that code running outside the class can make calls to that method. most development companies have documents that set out the coding conventions they use. since the initial balance on my account is zero. if ( RobsAccount. it does something) make it public Of course. since we want people to interact with our objects by calling methods in them. In general the rules are: if it is a data member (i. public Methods You may have noticed that I made the WithdrawFunds method public.e. secret. but it shows how I go about providing access to members in an account. it holds data) of the class. but opinions differ on this one. Programmer’s Point: Metadata makes Members and Methods I haven’t mentioned metadata for at least five minutes. So perhaps now is a good time. The most important thing in this situation is that the whole programming team adopts the same conventions on matters like these. In the code above the way that I am protecting the balance value is a reflection of how the customer wants me to make sure that this value is managed properly. task you can make it private. The convention also extends to variables which are local to a block. make it private if it is a method member (i.WriteLine ( "Insufficient Funds" ) .WithdrawFunds (5) ) { Console. This makes it easy for someone reading my code. These (for example the ubiquitous i) always start with a lower case letter. But I make the first letter of private members lower case (as in the case of the balance data member of our bank account).Creating Solutions Designing With Objects class Bank { public static void Main () { Account RobsAccount.WriteLine ( "Cash Withdrawn" ) . The method WithdrawFunds is a member of the Account class and can therefore access private members of the class. Some people go further and do things like put the characters m_ in front of variables which are members of a class.e. This has got to be the case. The metadata that I gather about my bank system will drive how I provide access to the members of my classes. RobsAccount = new Account().
At the end of this set of statements the test account should have 50 pounds in it. I have created three methods which I can use to interact with an account object. I could write a little bit of code to test these methods: Account test = new Account().PayInFunds(50). for example: Account test = new Account(). If the error count is greater than zero they print out a huge message in flashing red text to indicate that something bad has happened. } public void PayInFunds ( decimal amount ) { balance = balance + amount . Some development teams actually connect sirens and flashing red lights to their test systems.GetBalance() != 50 ) { Console. which is tedious. and if you don’t notice it then you might think your code is OK. if ( test. } } The bank account class that I have created above is quite well behaved. test. C# Programming © Rob Miles 2010 93 . find out how much is there and withdraw cash. } public decimal GetBalance () { return balance.PayInFunds(50). } balance = balance . Of course I must still read the output from all the tests. My tests count the number of errors that they have found.Creating Solutions Designing With Objects 4. You have to read that message.5. test. It just produces a little message if the test fails. } My program now tests itself. return true..amount . If it does not my program is faulty. I can pay money in. public bool WithdrawFunds ( decimal amount ) { if ( balance < amount ) { return false .WriteLine ( "Pay In test failed" ). Later we will consider the use of unit tests which make this much easier. They then search out the programmer who caused the failure and make him or her pay for coffee for the next week. in that it does something and then makes sure that the effect of that action is correct. Programmer’s Point: Make a Siren go off when your tests fail The above test is good but not great.
When you fix bugs in your program you need to be able to convince yourself that the fixes have not broken some other part (about the most common way of introducing new faults into a program is to mend a bug). Only when someone comes back and says “The game is too hard because you can’t kill the end of level boss without dying” can you actually do something about it. 2. i. but it does not solve all your problems. 4. If I ever write anything new you can bet your boots that I will write it using a test driven approach. This means that whenever we create an instance of the Account class we get a balance member.4 Test Driven Development I love test driven development. Programmer’s Point: Some things are hard to test Test development is a good way to travel. It is very important that you learn what static means in the context of C# programs. My approach in these situations is to make the user interface part a very thin layer which sits on top of requests to objects to do the work. The other kind of program that is very hard to test in this way is any kind of game. This is mainly because the quality of gameplay is not something you can design tests for. In the case of our bank account above. And there is a good chance that the tests that you write will be useful at some point too. This solves three problems that I can see: 1. when you have the best possible understanding of what it is supposed to do. We have used it lots in just about every program that we have ever written: C# Programming © Rob Miles 2010 94 . and the speed of all the game objects. they exist outside of any particular instance. You will thank me later. Anything with a front end where users type in commands and get responses is very hard to test like this. You can write code early in the project which will probably be useful later on. since you might be using code that you wrote some time back. This is usually the worst time to test. I can be fairly confident that the user interface will be OK too. For example it should be easy to adjust how much damage a hit from an alien causes to your spacecraft. 4.1 Static class members The static keyword lets us create members which are not held in an instance.6 Static Items At the moment all the members that we have created in our class have been part of an instance of the class.6. Some types of programs are really hard to test in this way. So. but in the class itself. If you have a set of automatic tests that run after every bug fix you have a way of stopping this from happening. we can also create members which are held as part of the class. Many projects are doomed because people start programming before they have a proper understanding of the problem. because although it is easy to send things into a program it is often much harder to see what the program does in response. If the bugs are in an old piece of code you have to go through the effort of remembering how it works. Far better to test the code as you write it. However.5. 3. As long as my object tests are passed. The only solution in this situation is to set out very clearly what your tests are trying to prove (so that the human testers know what to look for) and make it very easy to change the values that will affect the gameplay. place develop using tests. the code that provides the user interface where the customer enters how much they want to withdraw will be very simple and connect directly to the methods provided by my objects. You don't do the testing at the end of the project.Creating Solutions Static Items 4.e. Writing the tests first is actually a really good way of refining your understanding.
GetBalance()). The customer has told us that one of the members of the account class will need to be the interest rate on accounts.2 Using a static data member of a class Perhaps an example of static data would help at this point. We know that this is the method which is called to run the program.Balance = 100. It is part of the class AccountTest. The snag is. This means that to implement the change I'd have to go through all the accounts and update the rate. I think this is time for more posh font stuff: Static does not mean “cannot be changed”. If I made fifty AccountTest instances. (of course if I was doing this properly I'd make this stuff private and provide methods etc. I will write that down again in a posh font. Account RobsAccount = new Account(). I solve the problem by making the interest rate member static: C# Programming © Rob Miles 2010 95 . Console. Consider the interest rates of our bank accounts. } } The AccountTest class has a static member method called Main. they would all share the same Main method. This would be tedious. not part of an instance of the class. In terms of C# the keyword static flags a member as being part of the class.WriteLine ("Balance:" + test. RobsAccount. Either a data member or a method can be made static. Members of a class which have been made static can be used just like any other member of a class. 4. RobsAccount. but I'm keeping things simple just now). test. Static does not mean "cannot be changed". possibly expensive. If the interest rate changes it must change for all accounts. This is how my program actually gets to work. and if I missed one account. } Now I can create accounts and set balances and interest rates on them.PayInFunds (50).InterestRateChanged = 10. otherwise it cannot run.6. I've been told that the interest rate is held for all the accounts. public decimal InterestRateCharged . not a member of an instance of the class” I don't have to make an instance of the AccountTest class to be able to use the Main method.Creating Solutions Static Items class AccountTest { public static void Main () { Account test = new Account(). for it is important: “A static member is a member of the class. and so this method must be there already. in that when it starts it has not made any instances of anything. In the program we can implement this by adding another member to the class which holds the current interest rate: public class Account { public decimal Balance .
But you can also use them when designing your system. I can now call the method by using the class name: C# Programming © Rob Miles 2010 96 . public static decimal interestRateCharged . We can solve this by making the method static: public static bool AccountAllowed ( decimal income. It would take in their age and income. You should be careful about how you provide access to static data items.Balance = 100. int age ) { if ( ( income >= 10000 ) && ( age >= 18 ) ) { return true. } } This checks the age and income. Things like the limits of values (the largest age that you are going to permit a person to have) can be made static. A change to a single static value will affect your entire system. Programmer’s Point: Static Data Members are Useful and Dangerous When you are collecting metadata about your project you should look for things which can be made static. It would then return true or false depending on whether these are acceptable or not: public bool AccountAllowed ( decimal income. } else { return false. For example. We have been doing this for ages with the Main method. and you don't want to have to update all the objects in your program. } } Now the method is part of the class.6. at the moment. we can't call the method until we have an Account instance. There might be a time where the age limit changes. Since it is a member of the class I now have to use the class name to get hold of it instead of the name of the instance reference. not an instance of the class. you must be over 17 and have at least 1000 pounds income to be allowed an account.InterestRateChanged = 10. Account. RobsAccount. int age ) { if ( ( income >= 10000 ) && ( age >= 18 ) ) { return true. But of course. as Spiderman's uncle said. "With great power comes great responsibility". } The interest rate is now part of the class. The snag is that.Creating Solutions Static Items public class Account { public decimal balance . we might have a method which decides whether or not someone is allowed to have a bank account. So they should always be made private and updated by means of method calls. This means that I have to change the way that I get hold of it: Account RobsAccount = new Account(). } else { return false.3 Using a static method in a class We can make methods static too. not part of any instance. 4.
However. } This is nice because I have not had to make an instance of the account to find out if one is allowed. int age) { if ( ( income >= minIncome) && ( age >= minAge) ) { return true. } else { return false. method. However it is a bad program. If that doesn’t help. 21 ) ) { Console.cs(19. or property 'Account.AccountAllowed ( 25000. I might decide to make the method more flexible: public class Account { private decimal minIncome = 10000.minIncome' AccountManagement.43): error CS0120: An object reference is required for the nonstatic field.WriteLine ( "Allowed Account" ). } } } This is a better design.cs(19.minAge' As usual. public static bool AccountAllowed(decimal income. What the compiler really means is that "a static method is using a member of the class which is not static". how about this: The members minIncome and minAge are held within instances of the Account class. Using member data in static methods The Allowed method is OK. private int minAge = 18. using language which makes our heads spin. or property 'Account. the compiler is telling us exactly what is wrong. method. We can fix this (and get our program completely correct) by making the income and age limits static as well: C# Programming © Rob Miles 2010 97 . The compiler is unhappy because in this situation the method would not have any members to play with.Creating Solutions Static Items if ( Account. but of course I have fixed the age and income methods into it. since the class above will not compile: AccountManagement.21): error CS0120: An object reference is required for the nonstatic field. in that I now have members of the class which set out the upper limits of the age and income. a static method can run without an instance (since it is part of the class).
A single static member of the Account class will provide a variable which can be used inside all instances of the class. Again. since we want them to be the same for all instances of the class. This is actually exactly what is happening. The time it becomes impossible to use static is when the manager says "Oh. C# Programming © Rob Miles 2010 98 .7 The Construction of Objects We have seen that our objects are created when we use new to bring one into being: test = new Account(). the compiler instead quietly creates a default one for you and uses that. Programmer’s Point: Static Method Members can be used to make Libraries Sometimes in a development you need to provide a library of methods to do stuff. for example sin and cos. One of the rules of the C# game is that every single class must have a constructor method to be called when a new instance is created. so that it can execute without an instance. you say. static member method: the manager tells us that we need a method to determine whether or not a given person is allowed to have an account.. public static bool AccountAllowed(decimal income. in that in this situation all we want is the method itself. I must make it static. making them static is what we should have done in the first place. private static int minAge . In the C# system itself there are a huge number of methods to perform maths functions.Creating Solutions The Construction of Objects public class Account { private static decimal minIncome . But because there is only a single copy of this value this can be changed and thereby adjust the interest rate for all the accounts. int age) { if ( ( income > minIncome) && ( age > minAge) ) { return true. ―But wait a minute‖. If you look closely at what is happening you might decide that what is happening looks quite a bit like a method call. The constructor method is a member of the class and it is there to let the programmer get control and set up the contents of the shiny new object. At this point we know we can’t use static because we need to hold different values for some of the instances. } else { return false. This is because the C# compiler is. I can't make this part of any Account instance because at the time it runs an account has not been generated. being friendly here. The limit values should not be held as members of a class. When an instance of a class is created the C# system makes a call to a constructor method in that class. for a change. this makes perfect sense. } } } If you think about it. Any value which is held once for all classes (limits on values are another example of this) is best managed as a static value. not an instance of a class. 4. therefore. accounts for five year olds have a different interest rate from normal ones". when you are building your system you should think about how you are going to make such methods available for your own use. It makes sense to make these methods static. Rather than shout at you for not providing a constructor method.
Creating Solutions The Construction of Objects You might think this is strange. This means that when my program executes the line: robsAccount = new Account(). As an example. I might want to set the name.7. } } This constructor is not very constructive (ho ho) but it does let us know when it has been called. 4. in that normally the compiler loses no time in telling you off when you don’t do something. This could create a new account and set the name property to Rob Miles. public class Account { public Account () { } } This is what the default constructor looks like.1 The Default Constructor A constructor method has the same name as the class. In other words I want to do: robsAccount = new Account( "Rob Miles". all I have to do is make the constructor method to accept these parameters and use them to set up the members of the class: C# Programming © Rob Miles 2010 99 .WriteLine ( "We just made an account" ).the program will print out the message: We just made an account Note that this is not very sensible. It turns out that I can do this very easily.7. "Hull". but it does show how the process works. and initial balance of an account holder when the account is created. which we will discuss later. 0 ). but in this case it is simply solving the problem without telling you. It accepts no parameters. It is public so that it can be accessed from external classes who might want to make instances of the class. If I create my own constructor the compiler assumes that I know what I’m doing and stops providing the default one. we could make a constructor which just prints out that it has been called: public class Account { public Account () { Console. but it would be even nicer to be able to feed information into the Account when I create it. the address to Hull and the initial balance to zero. This can cause problems. It is called when we perform.2 Our Own Constructor For fun. Feeding the Constructor Information It is useful to be able to get control when an Account is created. If you don’t supply a constructor (and we haven’t so far) the compiler creates one for us. 4. but it does not return anything. address. in that it will result in a lot of printing out which the user of the program might not appreciate. .
In the context of a C# program it means: "A method has the same name as another. what this means is that you can provide several different ways of constructing an instance of a class. . Something a bit like this: C# Programming © Rob Miles 2010 100 . because it can tell from the parameters given at the call of the method which one to use. address = inAddress. i. or create a default constructor of your own for these calls to use. Of course you don't have to do this because your design of the program was so good that you never have this problem. and nothing else.cs(9.e.3 Overloading Constructors Overload is an interesting word. In other words. The default constructor is no longer supplied by the compiler and our program now fails to compile correctly. but has a different set of parameters" The compiler is quite happy for you to overload methods.the compiler will stop being nice to me and produce the error: AccountTest. In the context of the constructor of a class. private string address. i. the compiler only provides a default constructor if the programmer doesn't provide a constructor. } } The constructor takes the values supplied in the parameters and uses them to set up the members of the Account instance that is being created. 4. string inAddress. // constructor public Account (string inName. decimal inBalance) { name = inName. If I try to do this: robsAccount = new Account(). Just like me.e. In that situation you have to either find all the calls to the default one and update them. the only way I can now make an Account object is by supplying a name. hem hem. nothing in the account. This means that we would like to be able to write robsAccount = new Account("Rob Miles". "Hull").Creating Solutions The Construction of Objects class Account { // private member data private string name. many (but not all) of your accounts will be created with a balance value of zero.7. balance = inBalance. private decimal balance. This can cause confusion if we have made use of the default constructor in our program and we then add one of our own. In this respect it behaves exactly as any other method call.27): error CS1501: No overload for method 'Account' takes '0' arguments What the compiler is telling me is that there is no constructor in the class which does not have any parameters. In the context of the "Star Trek" science fiction series it is what they did to the warp engines in every other episode. since I want to use the "default" one of zero. Note that adding a constructor like this has one very powerful ramification: You must use the new constructor to make an instance of a class. address and starting balance. I've missed off the balance value. For example. If your code does this the compiler simply looks for a constructor method which has two strings as parameters.
The scary thing is that it is quite easy to do. . Good programmers hate duplicating code. 2005 ). address = inAddress. } public Account (string inName) { name = inName. and sets the address to "Not Supplied". C# provides a way in which you can call one constructor from another. } I've made three constructors for an Account instance. But you should not do this. balance = 0. If you need to change this piece of code you have to find every copy of the code and change it. Because it is bad. address = inAddress. address = "Not Supplied". balance = 0. This can be useful if you have a particular action which can be driven by a number of different items of data.4 Constructor Management If the Account class is going to have lots of constructor methods this can get very confusing for the programmer: public Account (string inName. } public Account (string inName. address = inAddress. even if you don't put a bug in your code. 7. This happens more often than you'd think. balance = inBalance. you still might find yourself having to change it because the specification changes. string inAddress) { name = inName. } Overloading a method name In fact. To do this I have had to duplicate code. string inAddress. the second is not given a balance and sets the value to 0. It is regarded as "dangerous extra work".would be matched up with the method which accepts three integer parameters and that code would be executed. So. The first is supplied with all the information. decimal inBalance) { name = inName. int day ) SetDate ( int year. string inAddress) { name = inName.Creating Solutions The Construction of Objects public Account (string inName. you can overload any method name in your classes. for example you could provide several ways of setting the date of a transaction: SetDate ( int year. int month. balance = 0. The third is not given the address either. 4. Consider: C# Programming © Rob Miles 2010 101 . just use the block copy command in the text editor and you can take the same piece of program and use it all over the place. int julianDate ) SetDate ( string dateInMMDDYY ) A call of: SetDate ( 23.7.
address = inAddress. attempts to withdraw negative amounts of money from a bank account should be rejected. Failure is not an option. } public Account ( string inName. the highlighted bits of the code are calls to the first constructor. 0 ) { } The keyword this means "another constructor in this class". Constructors cannot fail.Creating Solutions The Construction of Objects public Account (string inName. "Not Supplied". Then you should make all the other constructor methods use this to get hold of that method. They simply pass the parameters which are supplied.5 A constructor cannot fail If you watch a James Bond movie there is usually a point at which agent 007 is told that the fate of the world is in his hands. on to the "proper" constructor to deal with. In fact. The syntax of these calls is rather interesting. in that the call to the constructor takes place before the body of the constructor method.PayInFunds (1234567890). C# Programming © Rob Miles 2010 102 . 1234567890).7. This means that the actual transfer of the values from the constructor into the object itself only happens in one method. so the PayInFunds method will refuse to pay the money in. and the other constructor methods just make calls to it. in the code above. string inAddress ) : this (inName. "Hull". string inAddress. The "this" constructor runs before the body of the other constructor is entered. There will be an upper limit to the amount of cash you can pay in at once. because it reflects exactly what is happening. the body of the constructor can be empty. since the call of this does all the work. balance = inBalance. The whole basis of the way that we have allowed our objects to be manipulated is to make sure that they cannot be broken by the people using them. For example. And this is a problem: Whenever we have written methods in the past we have made sure that their behaviour is error checked so that the method cannot upset the state of our object. But what is to stop the following: RobsAccount = new Account ("Rob". decimal inBalance) { name = inName. So we know that when we create a method which changes the data in an object we have to make sure that the change is always valid. inAddress. In fact it is outside the block completely. For example. Constructors are a bit like this. This is sensible. 4. You should create one "master" constructor which handles the most comprehensive method of constructing the object. 0 ) { } public Account ( string inName ) : this (inName. As you can see in the code sample above. If you try to do something stupid with a method call it should refuse to perform the action and return something which indicates that it could not do the job. we would not let the following call succeed: RobsAccount. Programmer’s Point: Object Construction Should Be Planned The way in which objects are constructed is something that you should plan carefully when you write your program. along with any default values that we have created.
This can be done. and it complains about my address. I hate it when I'm using a program and this happens. I type in my name wrong and it complains about that. This means that the user of the constructor must make sure that they catch exceptions when creating objects. This poses a problem. Writing code which will handle all the possible failure conditions in a useful way is much trickier. } } If we try to create an account with a bad name it will throw an exception. string inAddress) { string errorMessage = "". What I want is a way in which I can get a report of all the invalid parts of the item at once. i.e. } if ( errorMessage != "" ) { throw new Exception ( "Bad account" + errorMessage) . Constructors and Exceptions The only way round this at the moment is to have the constructor throw an exception if it is unhappy. Whatever happens during the constructor call. Writing code to do a job is usually very easy. at the expense of a little bit of complication: public Account (string inName. It is normally when I'm filling in a form on the web. and if any of them returns with an error the constructor should throw the exception at that Point: public Account (string inName. C# Programming © Rob Miles 2010 103 . which is not a bad thing. Programmer’s Point: Managing Failure is Hard Work This brings us on to a kind of recurring theme in our quest to become great programmers. It is a fact of programming life that you will (or at least should) spend more time worrying about how things fail than you ever do about how they work correctly. when the object is first created. which is what we want. the user of the method will not know this until they have fixed the name and then called the constructor again. } if ( SetAddress ( inAddress) == false ) { errorMessage = errorMessage + " Bad addr " + inAddress. Then I put my name right. Each new thing which is wrong is added to the message and then the whole thing is put into an exception and thrown back to the caller. } if ( SetAddress ( inAddress) == false ) { throw new Exception ( "Bad address" + inAddress) . The only problem here is that if the address is wrong too. it will complete and a new instance will be created. } } This version of the constructor assembles an error message which describes everything which is wrong with the account. if ( SetName ( inName ) == false ) { errorMessage = errorMessage + "Bad name " + inName. string inAddress) { if ( SetName ( inName ) == false ) { throw new Exception ( "Bad name " + inName) . It looks as if we can veto stupid values at every point except the one which is most important. constructors are not allowed to fail. The really clever way to do this is to make the constructor call the set methods for each of the properties that it has been given.Creating Solutions The Construction of Objects Like James Bond.
C# Programming © Rob Miles 2010 104 . For this to work properly the people who make main boards and the people who make graphics adapters have had to agree on an interface between two devices. If it is you will need to manage the storage and selection of appropriate messages. and how to design systems using them. You should be familiar with the way that. Fortunately there are some C# libraries which are designed to make this easier. some parts are not "hard wired" to the system. if you write the program as above this might cause a problem when you install the code in a French branch of the bank.8. if the manager says something like "The customer fills in a form. 4. Posh people call this "abstraction". So. enters their name and address and this is used to create the new account" this gives you a good idea of what parameters should be supplied to the constructor.8 From Object to Component I take the view that as you develop as a software writer you go through a process of "stepping back" from problems and thinking at higher and higher levels. for example which signals are inputs.1 Components and Hardware Before we start on things from a software point of view it is probably worth considering things from a hardware point of view. because it means that I can buy a new graphics adapter at any time and fit it into the machine to improve the performance. This is good.Creating Solutions From Object to Component Programmer’s Point: Consider the International Issues The code above assembles a text message and sends it to the user when something bad happens. That said. which signals are outputs and so on. During the specification process you need to establish if the code is ever going to be created in multiple language versions. This is the progress that we have made so far: representing values by named locations (variables) creating actions which work on the variables (statements and blocks) putting behaviours into lumps of code which we can give names to. and from the point of view of what the Account class needs to do. This takes the form of a large document which describes exactly how the two components interact. the graphics adapter is usually a separate device which is plugged into the main board. from the point of view of hardware. since they really relate to how the specification is implemented. Later we will come back and revisit the problem in a greater level of detail. we just say "We need an account here" and then move on to other things. This is a good thing.. However. components are possible because we have created standard interfaces which describe exactly how they fit together. Bank Notes: Constructing an Account The issues revolving around the constructor of a class are not directly relevant to the bank account specification as such. Software components are exactly the same. in a typical home computer. 4. and not what the system itself actually does. Any main board which contains a socket built to the standard can accept a graphics card. For example. In this section you will find out the difference between an object and a component. The next thing to do is consider how we take a further step back and consider expressing a solution using components and interfaces.
8. one to pay money in. When we are creating a system we work out what each of the parts of it need to do. An interface is placed in a source file just like a class. An interface on the other hand just specifies how a software component could be used by another software component. Programmer’s Point: Interface names start with I We have seen that there are things called coding conventions. However. It is not obvious at this stage why components are required. These are usually either text based (the user types in commands and gets responses) or graphical (the user clicks on ―buttons‖ on a screen using the mouse). This will earn you zero marks. Please don’t be tempted to answer an exam question about the C# interface mechanism with a long description of how windows and buttons work. a system designed without components is exactly like a computer with a graphics adapter which part of the main board.Creating Solutions From Object to Component Why we Need Software Components? At the moment you might not see a need for software components. From the balance management point of view this is all we need. } This says that the IAccount interface is comprised of three methods. This might happen even after we have installed the system and it is being used. In C# we express this information in a thing called an interface. An interface is simply a set of method definitions which are lumped together. By describing objects in terms of their interfaces however. decimal GetBalance (). If you don’t do this your programs will compile fine. in this case what a class must do to be considered a bank account. we might be asked to create a "BabyAccount" class which only lets the account holder draw out up to ten pounds each time. Interfaces and Design So. Note that at the interface level I am not saying how it should be done. And quite right too. 4. another to withdraw it and a third which returns the balance on the account. It sets out a number of methods which relate to a particular task or role. C# Programming © Rob Miles 2010 105 . Our first pass at a bank account interface could be as follows: public interface IAccount { void PayInFunds ( decimal amount ). The user interface is the way a person using our program would make it work for them. i. but you may have trouble sleeping at night. instead of starting off by designing classes we should instead be thinking about describing their interfaces. we can use anything which behaves like an Account in this position. Well. what it is they have to do. For example. Another convention is that the name of an interface should start with the letter I. it is unfortunately the case that with our bank system we may have a need to create different forms of bank account class. and then we create those parts. It is not possible for me to improve the graphics adapter because it is "hard wired" into the system.2 Components and Interfaces One point I should make here is that we are not talking about the user interface to our program. I am instead just saying what should be done. since the compiler has no opinions on variable names. and compiled in the same way.e. which set down standards for naming variables. If everything has been hard wired into place this will be impossible. bool WithdrawFunds ( decimal amount ).
PayInFunds(decimal)' In this case I missed out the PayInFunds method and the compiler complained accordingly.4 References to Interfaces Once we have made the CustomerAccount class compile. The highlighted part of the line above is where the programmer tells the compiler that this class implements the IAccount interface.CustomerAccount' does not implement interface member 'AccountManagement. If the class does not contain a method that the interface needs you will get a compilation error: error CS0535: 'AccountManagement.8. we have now got something which can be regarded in two ways: as a CustomerAccount (because that is what it is) as an IAccount (because that is what it can do) People do this all the time. } public decimal GetBalance () { return balance. } } The code above does not look that different from the previous account class.3 Implementing an Interface in C# Interfaces become interesting when we make a class implement them.IAccount.. 4. it has a corresponding implementation.Creating Solutions From Object to Component 4. so that it can be thought of as an account component. In the case of the bank account.amount .. You can think of me in a whole variety of ways. here are two: C# Programming © Rob Miles 2010 106 . return true.8. This means that the class contains concrete versions of all the methods described in the interface. The only difference is the top line: public class CustomerAccount : IAccount { . Implementing an interface is a bit like a setting up a contract between the supplier of resources and the consumer. } balance = balance . I am going to create a class which implements the interface. irrespective of what it really is: public class CustomerAccount : IAccount { private decimal balance = 0. public bool WithdrawFunds ( decimal amount ) { if ( balance < amount ) { return false . } public void PayInFunds ( decimal amount ) { balance = balance + amount . If a class implements an interface it is saying that for every method described in the interface.
In the case of our bank.5 Using interfaces Now that we have our system designed with interfaces it is much easier to extend it. There is no such physical thing as a "lecturer". this means that we want to deal with objects in terms of IAccount.(the set of account abilities) rather than CustomerAccount (a particular account class). This implements all the required methods. it is much more useful for it to think of me as a lecturer. The account variable is allowed to refer to objects which implement the IAccount interface. and starting to think about them in terms of what they can do. rather than the particular type that they are. And you can use the same methods with any other lecturer (i. 4.amount .8. account. person who implements that interface). contains the required methods). which has to manage a large number of interchangeable lecturers. return true. } } C# Programming © Rob Miles 2010 107 . public bool WithdrawFunds ( decimal amount ) { if (amount > 10) { return false . From the point of view of the university. I can create a BabyAccount class which implements the IAccount interface.e. The compiler will check to make sure that CustomerAccount does this. So. with interfaces we are moving away from considering classes in terms of what they are.e. the compilation is successful. } public decimal GetBalance () { return balance. and if it does. } public void PayInFunds ( decimal amount ) { balance = balance + amount . In C# terms this means that we need to be able to create reference variables which refer to objects in terms of interfaces they implement. It is simply a way that we can refer to something which has that ability (i.PayInFunds(50). } balance = balance . } if (balance < amount) { return false . This is the same in real life. but they behave slightly differently because we want all withdrawals of over ten pounds to fail: public class BabyAccount : IAccount { private decimal balance = 0. merely a large number of people who can be referred to as having that particular ability or role. Note that there will never be an instance of IAccount interface. rather than Rob Miles the individual. It turns out that this is quite easy: IAccount account = new CustomerAccount().Creating Solutions From Object to Component Rob Miles the individual (because that is who I am) A university lecturer (because that is what I can do) If you think of me as a lecturer you would be using the interface that contains methods like GiveLecture.
I don't want to have to provide a print method in each of these. For example. You might think that all I have to do is add a print method to the IAccount interface. The IAccount interface lets me regard a component purely in terms of its ability to behave as a bank account.8. there will be lots of things which need to be printed.6 Implementing Multiple Interfaces A component can implement as many interfaces as are required. If you have a set of fundamental behaviours that all bank accounts must have (for example C# Programming © Rob Miles 2010 108 . so that we can make sure that withdrawals of more than ten pounds do fail. what I really want is a way that I can regard an object in terms of its ability to print. what is important to the customer.. We will of course have to create some tests especially for it. ISpecialOffer for example).8. You should also have spotted that interfaces are good things to hang tests on. the bank will want the account to be able to print itself out on paper. special offers and the like. 4.. before you write any code at all. This would be reasonable if all I ever wanted to print was bank accounts. public class BabyAccount : IAccount.. However. Each of these items will be implemented in terms of a component which provides a particular interface (IWarning.Creating Solutions From Object to Component The nice thing about this is that as it is a component we don’t have to change all the classes which use it. Each interface is a new way in which it can be referred to and accessed. This means that a BabyAccount instance behaves like an account and it also contains a DoPrint method which can be used to make it print out. This is actually very easy. } Now anything which implements the IPrintToPaper interface will contain the DoPrint method and can be thought of in terms of its ability to print. The rest of the system can then pick up this object and use it without caring exactly what it is. However.7 Designing with Interfaces If you apply the "abstraction" technique properly you should end up with a system creation process which goes along the lines of: gather as much metadata as you can about the problem. There are also graphical tools that you can use to draw formal diagrams to represent this information. The field of Software Engineering is entirely based on this process. but using the new kind of account in our existing system is very easy. A class can implement as many interfaces as it needs. 4. When we create the account objects we just have ask if a standard account or a baby account is required. I create the interface: public interface IPrintToPaper { void DoPrint (). I may want to regard a component in a variety of ways. IPrintToPaper { . for example warning letters.
Programmer’s Point: Interfaces are just promises An interface is less of a binding contract. we sometimes use this to good effect when building a program. Inheritance lets a class pick up behaviours from the class which is its parent. In fact.Creating Solutions Inheritance paying in money must always make the account balance go up) then you can write tests that bind to the IAccount interface and can be used to test any of the bank components that are created. For example. We could use these in our Account constructor to create a GUID which allows each account to have a unique number. it just means that a method with that name exists within the class. The need for things like account numbers. It can also be used at the design stage of a program if you have a set of related objects that you wish to create. The interface mechanism gives us a great deal of flexibility when making our components and fitting them together. This is a very important value. If a class is descended from a particular parent class this C# Programming © Rob Miles 2010 109 . Once we have set out an interface for a component we can then just think in terms of what the component must do. From the point of view of interface design this means that the account number will be set when the account is created and the account class will provide a method to let us get the value (but there will not be a method to set the account number). These are data items which are created based on the date. I have to add comments to give more detail about what the method does. and how good your tests are. that is down to how much you trust the programmer that made the class that you are using. In this respect you can regard it as a mechanism for what is called code reuse. This is the real detail in the specification. It is a way that we can pick up behaviours from classes and just modify the bits we need to make new ones. which really need to be unique in the world. They state that we have a need for behaviours. in that we can create "dummy" components which implement the interface but don't have the behaviour as such. It means that once we have found out what our bank account class needs to hold for us we can then go on to consider what we are going to ask the accounts to do. We don't care what the method GetAccountNumber actually does.9 Inheritance Inheritance is another way we can implement creative laziness. has resulted in the creation of a set of methods in the C# libraries to create things called Globally Unique Identifiers or GUIDs. not precisely how it does it. So this requirement ends up being expressed in the interface that is implemented by the account class. Just because a class has a method called PayInFunds does not mean that it will pay money into the account. } This method returns the integer which is the account number for this instance. 4. The design of the interfaces in a system is just this. time and certain information about the host computer. but we have not actually described how this should be done. in that it will be fixed for the life of the account and can never be changed. but they do not necessarily state how they are made to work. interface IAccount { int GetAccountNumber (). and more a promise. Nothing in C# allows you to enforce a particular behaviour on a method. By placing it in the interface we can say that the account must deliver this value. as long as it always returns the value for a particular account. Each GUID is unique in the world. the manager has told us that each bank account must have an account number. No two accounts should ever have the same number. You can regard an interface as a statement by a class that it has a set of behaviours because it implements a given interface.
Baby accounts are only allowed to draw up to 10 pounds out at a time. This means that the PayInFunds method from the CustomerAccount class is used at this point. It turns out that we can do this in C# using inheritance. In short: Interface: "I can do these things because I have told you I can" Inheritance: "I can do these things because my parent can" 4. And a lot of the mistakes that I make are caused by improper use of block copy.9. it gets everything from its parent. and only once. But this does make things a bit tiresome when we write the program. the BabyAccount class has no behaviours of its own. of the new code and find that my program doesn't work properly.1 Extending a parent class We can see an example of a use for inheritance in our bank account project. In fact. Then I change most. If you need to use it in more than one place. make it a method. These can be introduced and work alongside the others because they behave correctly (i.PayInFunds(50).e. I can now write code like: BabyAccount b = new BabyAccount(). We need to create a BabyAccount class which contains a lot of code which is duplicated in the CustomerAccount class. But: Programmer’s Point: Block Copy is Evil I still make mistakes when I write programs. Customer accounts can draw out as much as they want. BabyAccount can do. I write some code and find that I need something similar.IAccount { } The key thing here is the highlighted part after the class name.Creating Solutions Inheritance means that it has a set of behaviours because it has inherited them from its parent. "This is not a problem" you probably think "I can use the editor block copy to move the program text across". Try not to do this. By separating the thing that does the job from the description of the job (which is what an interface lets you do) we can get the whole banking system thinking in terms of IAccount and then plug in accounts with different behaviours as required. You might think that after such a huge number of years in the job I get everything right every time. A great programmer writes every piece of code once. We have already noted that a BabyAccount must behave just like a CustomerAccount except in respect of the cash withdrawal method. We have solved this problem from a design point of view by using interfaces. Wrong. instances of the BabyAccount class have abilities which they pick up from their parent class. So I use block copy. but not all. What we really want to do is pick up all the behaviours in the CustomerAccount and then just change the one method that needs to behave differently. the parent class does. I have put the name of the class that BabyAccount is extending. This means that everything that CustomerAccount can do. they implement the interface). C# Programming © Rob Miles 2010 110 . So. We can even create brand new accounts at any time after the system has been deployed. When I create the BabyAccount class I can tell the compiler that it is based on the CustomerAccount one: public class BabyAccount : CustomerAccount. in another part of the program. at the moment. although BabyAccount does not have a PayInFunds method. This works because. but not exactly the same. b.
you definitely can’t.IAccount { public override bool WithdrawFunds (decimal amount) { if (amount > 10) { return false . In other words. This is because it must call an overridden method in a slightly different way from a "normal" one. This is called overriding a method.WithdrawFunds(5).2 Overriding methods We now know that we can make a new class based on an existing one. The next thing we need to be able to do is change the behaviour of the one method that we are interested in. } } The keyword override means "use this version of the method in preference to the one in the parent". To make the overriding work correctly I have to change my declaration of the method in the CustomerAccount class. In the BabyAccount class I can do it like this: public class BabyAccount : CustomerAccount.9. C# Programming © Rob Miles 2010 111 .PayInFunds(50). there is one other thing that we need to do in order for the overriding to work.amount . return true. public class CustomerAccount : IAccount { private decimal balance = 0. the above code won't compile properly because the compiler has not been told that WithDrawFunds might be overridden in classes which are children of the parent class. Virtual Methods Actually. public virtual bool WithdrawFunds ( decimal amount ) { if ( balance < amount ) { return false . } if (balance < amount) { return false . } balance = balance . but if you don’t have the word present. b.amount . } } The keyword virtual means ―I might want to make another version of this method in a child class‖.Creating Solutions Inheritance 4. We want to replace the WithdrawFunds method with a new one. You don’t have to override the method. This means that code like: BabyAccount b = new BabyAccount(). The call of PayInFunds will use the method in the parent (since that has not been overridden) but the call of WithdrawFunds will use the method in BabyAccount. } balance = balance . return true. b. The C# compiler needs to know if a method is going to be overridden.
. In other words. The word base in this context means ―a reference to the thing which has been overridden‖. in that the WithDrawFunds method in the BabyAccount class contains all the code of the method in the parent class. public class CustomerAccount : IAccount { protected decimal balance = 0.. We have already noted that we don’t like this much. However.. We would have made the WithDrawFunds method virtual because the manager would have said ―We like to be able to customise the way that some accounts withdraw funds‖. methods in the BabyAccount class can see and use a protected member because they are in the same class hierarchy as the class containing the member.Creating Solutions Inheritance This makes override and virtual a kind of matched pair. However.. This makes the member visible to classes which extend the parent. this protection is too strict.9. It also has access to all the protected members of the classes above it. Of course this should be planned and managed at the design stage. in that it stops the BabyAccount class from being able to change the value. And we would have written this down in the specification. Bank Notes: Overriding for Fun and Profit The ability to override a method is very powerful. Later we will see better ways to manage this situation. Well. It means that we can make more general classes (for example the CustomerAccount) and customise it to make them more specific (for example the BabyAccount). I can use this to make the WithDrawFunds method in my BabyAccount much simpler: C# Programming © Rob Miles 2010 112 . This is because the balance value in the CustomerAccount class is private. in that it means that the balance value has to be made more exposed that we might like. Fortunately the designers of C# have thought of this and have provided a way that you can call the base method from one which overrides it. Protection of data in class hierarchies It turns out that the code above still won’t work. We carefully made it private so that methods in other classes can’t get hold of the value and change it directly. for now making this change will make the program work. A class hierarchy is a bit like a family tree. 4. it looks as if we are breaking our own rules here. } I’m not terribly happy about doing this. To get around this problem C# provides a slightly less restrictive access level called protected. You use virtual to mark a method as able to be overridden and override to actually provide a replacement for the method. Every class has a parent and can do all the things that the parent can do.3 Using the base method Remember that programmers are essentially lazy people who try to write code only once for a given problem. the balance is very important to me and I’d rather that nobody outside the CustomerAccount class could see it. This calls for more metadata to be gathered from the customer and used to decide which parts of the behaviour need to be changed during the lift of the project. .
Creating Solutions Inheritance public class BabyAccount : CustomerAccount. and why I’m doing it: I don’t want to have to write the same code twice I don’t want to make the balance value visible outside the CustomerAccount class.4 Making a Replacement Method This bit is rather painful.9. By making this change I can put the balance back to private in the CustomerAccount because it is not changed outside it.amount . IAccount { public override bool WithdrawFunds (decimal amount) { if (amount > 10) { return false .e. This is because in this situation there is no overriding. It is important that you understand what I’m doing here. The use of the word base to call the overridden method solves both of these problems rather beautifully. } } The very last line of the WithDrawFunds method makes a call to the original WithDrawFunds method in the parent class. return true. This makes it more difficult to pick up behaviours from parent classes.WithdrawFunds(amount). If you play around with C# you will find out that you don’t actually seem to need the virtual keyword to override a method. Note that there are other useful spin-offs here. } return base. C# Programming © Rob Miles 2010 113 . } } The problem with this way of working is that you are unable to use base. in the top level class. If I leave it out (and leave out the override too) the program seems to work fine.IAccount { public new bool WithdrawFunds (decimal amount) { if (amount > 10) { return false . If I need to fix a bug in the behaviour of the WithDrawFunds method I just fix it once. you have just supplied a new version of the method (in fact the C# compiler will give you a warning which indicates that you should provide the keyword new to indicate this): public class BabyAccount : CustomerAccount. the one that the method overrides. } balance = balance . Because the method call returns a bool result I can just send whatever it delivers. i. and then it is fixed for all the classes which call back to it. but don’t worry too much since it actually does make sense when you think about it. } if (balance < amount) { return false . 4.
overriding/replacing is not always desirable. The rules are that you can only seal an overriding method (which means that we can’t seal the GetBalance virtual method in the CustomerAccount class) and you can still replace a sealed method. Consider the GetBalance method. C# Programming © Rob Miles 2010 114 . This is never going to need a replacement.e. This means that the class cannot be extended. just remember that when you create a program this is another risk that you will have to consider. This goes well with a design process which means that as you move down the ―family tree‖ of classes you get more and more specific. In fact. which has a bit more potential.Creating Solutions Inheritance Programmer’s Point: Don’t Replace Methods I am very against replacing methods rather than overriding them. i. it cannot be used as the basis for another class. Unfortunately this is rather hard to use. And yet a naughty programmer could write their own and override or replace the one in the parent: public new decimal GetBalance () { return 1000000. One of the unfortunate things about this business is that you will have to allow for the fact that people who use your components might not all be nice and trustworthy. However. This means that you should take steps when you design the program to decide whether or not methods should be flagged as virtual and also make sure that you seal things when you can do so. I’m wondering why I mentioned this at all. 4... For a programming course at this level it is probably a bit heavy handed of me to labour this point just right now. But they will want to have confidence in the code that you make. C# does this by giving us a sealed keyword which means ―You can’t override this method any more‖.. No matter how much cash is drawn out. } This is the banking equivalent of the bottle of beer that is never empty. Bank Notes: Protect Your Code As far as the bank application is concerned. Another use for sealed. public sealed class BabyAccount : CustomerAccount. the customer will not have particularly strong opinions on how you use things like sealed in your programs. If you want to have a policy of allowing programmers to make custom versions of classes in this way it is much more sensible to make use of overriding since this allows a well-managed way of using the method that you over-rid.IAccount { . It means that a programmer can just change one tiny part of a class and make a new one with all the behaviours of the parent. is that you can mark a class as sealed. } The compiler will now stop the BabyAccount from being used as the basis of another account. and if it didn’t all make sense there is no particular need to worry. it always returns a balance value of a million pounds! A naughty programmer could insert this into a class and give himself a nice spending spree..5 Stopping Overriding Overriding is very powerful. What this means is that we need a way to mark some methods as not being able to be overridden..9.
to make a CustomerAccount I have to make an Account. "Hull"). The code above will only work if the CustomerAccount class has a constructor which accepts two strings. Programmer’s Point: Design your class construction process The means by which your class instances are created is something you should design into the system that you build. Constructor Chaining When considering constructors and class hierarchies you must therefore remember that to create an instance of a child class an instance of the parent must first be created. They must make sure that at each level in the creation process a constructor is called to set up the class at that level. The keyword base is used to make a call to the parent constructor. It is part of the overall architecture of the system that you are building. And the account is the class which will have a constructor which sets the name and the initial balance.Creating Solutions Inheritance 4. to create a CustomerAccount you must first create an Account.9. For example. 4. If there are some things that an account must do then we can make these abstract and then get the child classes to actually provide the implementation. } But this class is an extension of the Account class. decimal inBalance) { name = inName. You might think that I could solve this by writing a constructor a bit like this: public CustomerAccount (string inName. in the context of the bank application we might want to provide a method which creates a warning letter to the customer that their account is overdrawn.9. In other words. The result of this is that programmers must take care of the issue of constructor chaining. decimal inBalance) : base ( inName. the name and the address of the new customer. balance = inBalance.6 Constructors and Hierarchies A constructor is a method which gets control during the process of object creation. It is used by a programmer to allow initial values to be set into an object: robsAccount = new CustomerAccount("Rob Miles". inBalance) { } The base keyword is used in the same way as this is used to call another constructor in the same class. I can use it to force a set of behaviours on items in a class hierarchy. it is also possible to use overriding in a slightly different context. This means that a constructor in the parent must run before the constructor in the child. I think of these things as a bit like the girders that you erect to hold the floors and roof of a large building. the first a string and the second a decimal value. However. They tell programmers who are going to build the components which are going to implement the solution how to create those components. In other words. This C# Programming © Rob Miles 2010 115 . the proper version of the customer account constructor is as follows: public CustomerAccount (string inName. In this situation the constructor in the child class will have to call a particular constructor in the parent to set that up before it is created. In other words. It is of course very important that you have these designs written down and readily available to the development team. The constructor above assumes that the Account class which CustomerAccount is a child of has a constructor which accepts two parameters.7 Abstract methods and classes At the moment we are using overriding to modify the behaviour of an existing parent method.
Abstract classes and interfaces You might decide that an abstract class looks a lot like an interface. We could just provide a ―standard‖ method in the CustomerAccount class and then rely on the programmers overriding this with a more specific message but we then have no way of making sure that they really do provide the method. This means that at the time we create the bank account system we know that we need this method.. you may have to repeat methods as well. in that an interface also provides a ―shopping list‖ of methods which must be provided by a class. The methods in the second category must be made abstract. abstract classes are different in that they can contain fully implemented methods alongside the abstract ones. C# provides a way of flagging a method as abstract. If you think about it this is sensible. If you want to implement interfaces as well. If you want to make an instance of a class based on an abstract parent you must provide implementations of all the abstract methods given in the parent. An instance of Account would not know what to do it the RudeLetterString method was ever called. } The fact that my new Account class contains an abstract method means that the class itself is abstract (and must be marked as such). An abstract class can be thought of as a kind of template. This is true. The problem is that you can only inherit from one parent. This means that the method body is not provided in this class. but we don’t know precisely what it does in every situation. It is not possible to make an instance of an abstract class. This leads us to a class design a bit like this: C# Programming © Rob Miles 2010 116 . Perhaps at this point a more fully worked example might help. This can be useful because it means you don’t have to repeatedly implement the same methods in each of the components that implement a particular interface.. so you can only pick up the behaviours of one class.
} } public class BabyAccount : Account { public override bool WithdrawFunds ( decimal amount ) { if (amount > 10) { return false . return true. } public void PayInFunds ( decimal amount ) { balance = balance + amount . public virtual bool WithdrawFunds ( decimal amount ) { if ( balance < amount ) { return false . public abstract string RudeLetterString(). decimal GetBalance (). } balance = balance . } } public class CustomerAccount : Account { public override string RudeLetterString() { return "You are overdrawn" . } public virtual decimal GetBalance () { return balance. string RudeLetterString(). } public override string RudeLetterString() { return "Tell daddy you are overdrawn".Creating Solutions Inheritance public interface IAccount { void PayInFunds ( decimal amount ). bool WithdrawFunds ( decimal amount ).amount . } } C# Programming © Rob Miles 2010 117 . } return base.WithdrawFunds(amount). } public abstract class Account : IAccount { private decimal balance = 0.
including credit card. This might seem useful.e. The child classes can make use of the methods from the parent and override the ones that need to be provided differently for that particular class. I can now use their accounts. If you have an understanding of what an interface and abstract classes are intended to achieve this will stand you in very good stead for your programming career. This gives you a degree of flexibility that you can use to good effect. Then I have added customised methods into the child classes where appropriate. Interfaces let me describe a set of behaviours which a component can implement.Creating Solutions Inheritance This code repays careful study. Use Interface References One important consideration is that even if you make use of an abstract parent class I reckon that you should still make use of interfaces to reference the data objects themselves. as we can consider something as an ―account‖ rather than a BabyAccount. Then our printer can just regard each of the instances that implement this interface purely in this way. If you want to create a related set of items. I much prefer it if you manage references to abstract things (like accounts) in terms of their interface instead. This would be much more difficult if my entire system thought in terms of a parent Account class – since their classes would not fit into this hierarchy at all. Objects can implement more than one interface. In other words the other bank must create the methods in the IAccount interface. hey presto. However. even though I now have this abstract structure I still want to think of the account objects in terms of their ―accountness‖ rather than any particular specific type. Note also though that I have left the interface in place. A concrete example of this would be something like IPrintHardCopy.9. 4. A reference to an Account class can refer to any class which extends from that parent. References to abstract classes References to abstract classes work just like references to interfaces. If their accounts are software components too (and they should be) then all we have to do is implement the required interfaces at each end and then our systems understand each other. allowing them to present different faces to the systems that use them. Lots of items in my bank system will need to do this and so we could put the behaviour details into the interface for them to implement in their own way. Abstract: lets you create a parent class which holds template information for all the classes which extend it. That is because. deposit account. Broadly: Interface: lets you identify a set of behaviours (i. Any component which implements the interface can be thought of in terms of a reference of that interface type. then the best way to do this is to set up a parent class which contains abstract and non-abstract methods. Once a component can implement an interface it can be regarded purely in terms of a component with this ability. methods) which a component can be made to implement.8 Designing with Objects and Components For the purpose of this part of the text you now have broad knowledge of all the tools that can be used to design large software systems. Bank Notes: Making good use of interface and abstract If our bank takes over another bank and wants to share account information we might need a way to use their accounts. C# Programming © Rob Miles 2010 118 . Note how I have moved all the things that all accounts must do into the parent Account class. current account etc. for example all the different kinds of bank account you might need to deal with. get their account objects (whatever they are called) to implement the interface and.
It is in fact a child of the object class. This has a couple of important ramifications: Every object can do what an object can do.10 Object Etiquette We have considered objects "in the large". This will print out: 99 The integer somehow seems to know how to print itself out. C# Programming © Rob Miles 2010 119 . What we need to do now is take a look at some smaller. If I write the code: int i = 99. (in fact we have seen that the whole basis of building programs is to decide what the objects should do and then make them do these things). We know that an object can contain information and do things for us. Now it is time to find out how this is achieved. In other words. The important point to bear in mind is that the features are all provided so that you can solve one problem: Create software which is packaged in secure.9 Don’t Panic This is all deep stuff. if I write: public class Account { . 4. These features of C# are tied up with the process of software design which is a very complex business. We have also seen that you can extend a parent object to create a child which has all the abilities of the parent. A reference to an object type can refer to any class. interchangeable components.Creating Solutions Object Etiquette 4. If you don’t get it now.10. It turns out that this is all provided by the "objectness" of things in C#. but very important. The Object class When you create a new class this is not actually created from nowhere. Console. and also how we can give our own objects the same magical ability. Interfaces let me describe what each component can do. And that is it.WriteLine(i). plus the new ones that we add. and everything is a child of the object class. in that we know how they can be used to design and implement large software systems.9.1 Objects and ToString We have taken it as read that objects have a magical ability to print themselves out. issues that relate to how we use objects in our programs. Class hierarchies let me re-use code inside those components. 4.this is equivalent to writing: public class Account : object { The object class is a part of C#. Now we are going to see how these abilities of objects are used in making parts of the C# implementation itself work. don’t worry.
This means that the code: Account a = new Account("Rob". 25). . Getting the string description of a parent object If you want to get hold of a string description of the parent object.Creating Solutions Object Etiquette For the purpose of this part of the notes. you can use the base mechanism to do this. It means that all classes that are made have a number of behaviours that they inherit from their ultimate parent. from the point of view of good etiquette.WriteLine(a). public override string ToString() { return "Name: " + name + " balance: " + balance. This means that we can override it to make it behave how we would like: class Account { private string name. the first point is the one which has the most importance here. The ToString method The system knows that ToString exists for every object. The object implementation of ToString returns a string description of the type of that object.and the results would be exactly the same.ToString()). . . } } In the tiny Account class above I've overridden the ToString method so that it prints out the name and balance value.would print out: Name: Rob balance: 25 So. If you look inside the actual code that makes an object work you will find a method called ToString. The nice thing about ToString is that it has been declared virtual. whenever you design a class you should provide a ToString method which provides a text version of the content of that class. Console.ToString() + " Parent : " + parentName.WriteLine(o. the object. private decimal balance.would print out: System. } C# Programming © Rob Miles 2010 120 . Console. balance = inBalance.WriteLine(o). In other words: object o = new object(). decimal inBalance) { name = inName. and so if it ever needs the string version of an object it will call this method on the object to get the text. } public Account (string inName. This is sometimes useful if you add some data to a child class and want to print out the content of the parent first: public override string ToString() { return base.Object You can call the method explicitly if you like: Console.
missilePosition. This class extends the CustomerAccont and holds the name of the child's parent. spaceshipPosition. i. spaceshipPosition. } Note that I've made the x and y members of the Point class public. new members are added or the format of the string changes. Even though I have put the spaceship and the missile at the same place on the screen the word Bang is not printed. We can express this position as a coordinate or point. The code above uses the ToString method in the parent object and then tacks the name of the parent on the end before returning it. The nice thing about this is that if the behaviour of the parent class changes. with an x value and a y value. they are not located at the same address in memory. We know that objects are managed by named tags which refer to unnamed items held in memory somewhere. class Point { public int x. To see how this might cause us problems we need to consider how we would implement a graphical computer game (makes a change from the bank for a while). 4.2 Objects and testing for equals We have seen that when object references are compared a test for equals does not mean the same as it does for values. Point missilePosition = new Point(). This is because I'm not that concerned about protecting them. Some of the nastiest bugs that I've had to fix have revolved around programmers who have forgotten which test to use. which means that the equals test will fail.x = 1. public int y. When we perform an equals test the system simply checks to see if both references refer to the same location. Adding your own Equals method The way that you solve this problem is to provide a method which can be used to compare the two points and see if they refer to the same place.y = 2.e.y = 2. take a look at the test that is being performed.Creating Solutions Object Etiquette The method above is from a ChildAccount class. since it will just make use of the upgraded method.10. I can now create instances of Point and use them to manage my game objects: Point spaceshipPosition = new Point().. missilePosition.WriteLine("Bang"). In the game the various objects in it will be located at a particular place on the screen. If you find that things that contain the same data are not being compared correctly.x = 1. but I do want my program to run quickly. } This is my point class. if ( spaceshipPosition == missilePosition ) { Console. To do this we must override the standard Equals behaviour and add one of our own: C# Programming © Rob Miles 2010 121 . We then might want to test to see if two items have collided. The problem is that the above program code does not work. This is because although the two Point objects hold the same data.
Equals(spaceshipPosition) ) { Console. When you write the part of the program which stores data and brings it back again you will find it very useful to have a way of testing that what comes back from the store is identical to what you put there. because the Equals method actually compares the content of the two points rather than just their references. You will expect all programmers to write to these standards if they take part in the project.WriteLine("Bang"). Note that this reference is supplied as a reference to an object. The first thing we need to do is create a reference to a Point. } else { return false. for a professional approach you should set out standards which establish which of these methods you are going to provide. } This test will work. C# Programming © Rob Miles 2010 122 . if ( ( p. In fact. Programmer’s Point: Equals behaviours are important for testing The customer for our bank account management program is very keen that every single bank account that is created is unique. the Equals method is sometimes used by C# library methods to see if two objects contain the same data and so overriding Equals makes my class behave correctly as far as they are concerned. Bank Notes: Good Manners are a Good Idea It is considered good manners to provide the Equals and ToString methods in the classes that you create. In this situation an equals behaviour is important. and so I reckon you should always provide one. If the bank ever contains two identical accounts this would cause serious problems. } } The Equals method is given a reference to the thing to be compared. “If the system will never contain two things that are the same. I could have written one called TheSame which did the job.x == x ) && ( p. This means that I can write code like: if ( missilePosition. If they are both the same the method returns true to the caller. The fact that everything in the system is required to be unique might lead you to think that there is no need to provide a way to compare two Account instances for equality.Creating Solutions Object Etiquette public override bool Equals(object obj) { Point p = (Point) obj.y == y ) ) { return true. When you start to create your bank account management system you should arrange a meeting of all the programmers involved and make them aware that you will be insisting on good mannered development like this. there is a very good reason why you might find an equals behaviour very useful. It is also very useful to make appropriate use of this when writing methods in classes. The object is cast into a Point and then the x and y values are compared. why should I waste time writing code to compare them in this way?” However. We need to do this because we want to get hold of the x and y values from a Point (we can't get them from an object). These will allow your classes to fit in with others in the C# system. Note that I didn't actually need to override the Equals method. However.
Data). In other words.Data + 1. Consider: public class Counter { public int Data=0. However it might take a bit of getting used to. in this situation we are not passing an account into the bank. The Store method accepts this and then stores this somehow.WriteLine("Count : " + c.Creating Solutions Object Etiquette 4. I want to use the word this to mean this. Perhaps the best way to get around the problem is to remember that when I use the word this I mean "a reference to the currently executing instance of a class". It means that people reading my code can tell instantly whether I am using a local variable or a member of the class. We know that in this context the . I can use the class as follows: Counter c = new Counter(). } } The class above has a single data member and a single method member. but this also has a special meaning within your C# programs. A new bank account could add store itself in a bank by passing a reference to itself to a method that will store it: bank. If this hurts your head. the "proper" version of the Counter class is as follows: public class Counter { public int Data=0. public void Count () { Data = Data + 1. Of course. When a method in a class accesses a member variable the compiler automatically puts a this. then don't worry about it for now. public void Count () { this. and I want to use one of those methods. This calls the method and then prints out the data.Count(). Passing a reference to yourself to other classes Another use for this is when an instance class needs to provide a reference to itself to another class that wants to use it. this as a reference to the current instance I hate explaining this. Each time the Count method is called the counter is made one larger. If I have a member of my class which contains methods.Store(this).Data = this. in front of each use of a member of the class. (dot) means "follow the reference to the object and then use this member of the class". if we like to make it explicit that we are using a member of a class rather than a local variable. Confusion with this I reckon that using this is a good idea.3 Objects and this By now you should be used to the idea that we can use a reference to an object to get hold of the members of that object. } } We can add a this. When the Store method is called it is given a reference to the currently executing account instance. c. The data is a counter. I end up writing code like this: C# Programming © Rob Miles 2010 123 .10. instead we are passing a reference to the account. Console.
Call the SetName method on that member to set the name to 'Rob'".1. You can sort out the case of the text. This means "I have a member variable in this class called account. is how the system implements immutable. These are exposed as methods which you can call on a string reference.account. The thing that s1 is referring to is unchanged.WriteLine(s1 + " " + s2). By using references we only actually need one string instance with the word ―the‖ in it. because C# regards an instance of a string type in a special way. after the assignment s1 and s2 no longer refer to the same object. . 4.11 The power of strings and chars It is probably worth spending a few moments considering the string type in a bit more detail. The methods will return a new string. Console. string s2=s1.it makes a new string which contains the text "different" and makes s2 refer to that. The second statement made the reference s2 refer to the same object as s1.1 String Manipulation Strings are rather special. This behaviour. so changing s2 should change the object that s1 refers to as well. when the system sees the line: s2 = "different". Consider the situation where you are storing a large document in the memory of the computer. If you think you know about objects and references. This is because it gives you a lot of nice extra features which will save you a lot of work.11. because they seem to break some of the rules that we have learnt. C# Programming © Rob Miles 2010 124 . the C# system instead creates a new string and makes the reference you are "changing" refer to the changed one. 4. they don't actually behave like objects all the time. This is because programmers want strings to behave a bit like values in this respect. All the occurrences in the text can just refer to that one instance. A string can be regarded as either an object (referred to by means of a reference) or a value (referred to as a value). It calls it immutable. You might ask the question: "Why go to all the trouble?" It might seem all this hassle could be saved by just making strings into value types. trim spaces off the start and end and extract sub-strings using these methods. s2 = "different". I regard them as a bit like bats. This hybrid behaviour is provided because it makes things easier for us programmers. To find out more about this.11.2 Immutable strings The idea is that if you try to change a string. string s1="Rob".SetName("Rob"). This does not happen though. although strings are objects. This saves memory and it also makes searching for words much faster. you should be expecting s1 to change when s2 is changed. In other words. no. It is very important that you understand what happens when you transform a string. take a look at section 4. However it does mean that we have to regard strings as a bit special when you are learning to program. 4. never allowing a thing to be changed by making a new one each time it is required. A bat can be regarded as either an animal or a bird in many respects. So. This is because.4.Creating Solutions The power of strings and chars this. Well. transformed in the way that you ask.
(remember that strings are indexed starting at location 0). The first parameter is the starting position and the second is the number of characters to be copied. .4 String Editing You can read individual characters from a string by indexing them as you would an array: char firstCh = name[0].Length).WriteLine("The same"). in which case all the characters up to the end of the string are copied: string s1="Miles". C# Programming © Rob Miles 2010 125 . .Substring(2).2). s1=s1. versions of themselves in slightly different forms. This would leave the string "ob" in s1.11. You do this by calling methods on the reference to get the result that you want: s1=s1.11.11. This would set the character variable firstCh to the first character in the string. modified.would leave "les" in s1. It is also possible to use the same methods on them to find out how long they are: Console.Creating Solutions The power of strings and chars 4.5 String Length All of the above operations will fail if you try to do something which takes you beyond the length of the string. 4. s1=s1. you can't change the characters: name[0] = 'R'.6 Character case Objects of type string can be asked to create new.ToUpper(). In this respect strings are just like arrays.Equals(s2) ) { Console. You can use an equals method if you prefer: if ( s1.WriteLine("Still the same"). 4.WriteLine ( "Length: " + s1. } If s1 and s2 were proper reference types this comparison would only work if they referred to the same object. You can pull a sequence of characters out of a string using the SubString method: string s1="Rob". However. You can leave out the second parameter if you like. } 4.would cause a compilation error because strings are immutable. The Length property gives the number of characters in the string.11.3 String Comparison The special nature of strings also means that you can compare strings using equals and get the behaviour you want: if ( s1 == s2 ) { Console.Substring(1. But in C# the comparison works if they contain the same text.
They are a bit like the switch keyword. You should look this up if you have a need to do some proper editing. The reason you are suffering is that strings are really design to hold strings.Creating Solutions Properties The ToUpper method returns a version of the string with all the letters converted to UPPER CASE. There are TrimStart and TrimEnd methods to just take off leading or trailing spaces if that is what you want. If you don't trim the text you will find equals tests for the name will fail. These are static methods which are called on the character class and can be used to test characters in a variety of ways: char. but you can assign to characters and even replace one string with another.11. 4.11. If you trim a string which contains only spaces you will end up with a string which contains no characters (i. There is a corresponding ToLower method as well.IsDigit(ch) char. 4. We don't need properties. It is found in the System. No other characters in the string are changed. which lets us select things easily. This removes any leading or trailing spaces from the string.IsLetterOrDigit(ch) char.IsPunctuation(ch) char.IsUpper(ch) char.Text namespace. 4.8 Character Commands The char class also exposes some very useful methods which can be used to check the values of individual characters.9 String Twiddling with StringBuilder If you really want to twiddle with the contents of your strings you will find the fact that you can't assign to individual characters in the string a real pain. its length is zero).IsLower(ch) char. tab or newline You can use these when you are looking through a string for a particular character. It works a lot like a string. It is also very easy to convert between StringBuilder instances and strings. C# Programming © Rob Miles 2010 126 .11.7 Trimming and empty strings Another useful method is Trim.IsLetter(ch) char. s1=s1. 4.Trim(). but C# provides them because they make programs slightly easier to write and simpler to read. not provide a way that they can be edited. This is useful if your users might have typed " Rob " rather than "Rob". For proper string editing C# provides a class called StringBuilder.e.12 Properties Properties are useful.
public int GetAge() { return this. I can get hold of this member in the usual way: StaffMember s = new StaffMember(). Console.1 Properties as class members A property is a member of a class that holds a value. } } } We now have complete control over our property. s. } The class contains a public member. These provide access to the member in a managed way.GetAge() ).12.12. but we need to make the member value public. 4.Creating Solutions Properties 4. We then make the Age member private and nobody can tamper with it: public class StaffMember { private int age. An age property for the StaffMember class would be created as follows: C# Programming © Rob Miles 2010 127 . For example. just by giving the name of the member. the bank may ask us to keep track of staff members. but because the Age member is public we cannot stop it. This is very naughty.age. but we have had to write lots of extra code.SetAge(21). I can access a public member of a class directly. We have seen that we can use a member variable to do this kind of thing. } public void SetAge( int inAge ) { if ( (inAge > 0) && (inAge < 120) ) { this. There is nothing to stop things like: s.3 Using Properties Properties are a way of making the management of data like this slightly easier.WriteLine ( "Age is : " + s. The problem is that we have already decided that this is a bad way to manage our objects. Programmer’s who want to work with the age value now have to call methods: StaffMember s = new StaffMember(). s.2 Creating Get and Set methods To get control and do useful things we can create get and set methods which are public.12. One of the items that they may want to hold is the age of a member of staff.Age = -100210232.Age = 21.age = inAge. I can do it like this: public class StaffMember { public int Age. 4.
} } } The age value has now been created as a property. since it does not provide a set behaviour. They are packaged as a list of methods which a class must contain if it implements the interfaces. } } get { return this. You do this by leaving out the statements which are the body of the get and set behaviours: interface IStaff { int Age { get. I can do other clever things too: public int AgeInMonths { get { return this. It is also possible to add properties to interfaces. However. called AgeInMonths. When the Age property is given a value the set code is run. } } This is a new property. Note how there are get and set parts to the property. When the Age property is being read the get code is run. based on the same source value as was used by the other property. This gives us all the advantages of the methods. 4.4 Properties and interfaces Interfaces are a way that you can bring together a set of behaviours. It can only be read. The really nice thing about properties is that they are used just as the class member was: StaffMember s = new StaffMember(). it returns the age in months. You can also provide read-only properties by leaving out the set behaviour.WriteLine ( "Age is : " + s. public int Age { set { if ( (value > 0) && (value < 120) ) { this. These equate directly to the bodies of the get and set methods that I wrote earlier. but they are much easier to use and create. Console.Age = 21.ageValue*12. The keyword value means ―the thing that is being assigned‖. set.ageValue. Write only properties are also possible if you leave out the get.Creating Solutions Properties public class StaffMember { private int ageValue.ageValue = value.Age ). } } C# Programming © Rob Miles 2010 128 . This means that you can provide several different ways of recovering the same value.12. s.
would fail. . We can use interfaces to define the behaviour of a bank account component. I suppose that it would be possible to combine a set method and a get property. and they are used throughout the classes in the . but I reckon that would be madness. but it has no way of telling the user of the property that this has happened.age = inAge.NET libraries.Age = 99. Properties Run Code When you assign a value to a property you are actually calling a method. With our Age property above the code: s. If there is a situation where a property assignment can fail I never expose that as a property. A SetAge method on the other hand could return a value which indicates whether or not it worked: public bool SetAge( int inAge ) { if ( (inAge > 0) && (inAge < 120) ) { this.5 Property problems Properties are really neat. This gives us a way of creating new types of account as the bank business develops. } A programmer setting the age value can now find out if the set worked or failed.12. } C# Programming © Rob Miles 2010 129 . Unfortunately there is no way you can tell that from the code which does the assignment: s. This looks very innocent. We can express the behaviour that we need from our bank in terms of an interface: interface IBank { IAccount FindAccount (string name). but could result in a thousand lines of code running inside the set property. The only way that a property set method could do this would be to throw and exception. } return false.Creating Solutions Building a Bank This is an interface that specifies that classes which implement it must contain an Age property with both get and set behaviours. But it can also be made very confusing. 4. which is not a good way to go on. What we now need is a way of storing a large number of accounts. However. return true. This is OK. in that an object can react to and track property changes. It is possible to use this to advantage. But there are a few things that you need to be aware of when deciding whether or not to use them: Property Assignment Failure We have seen that the set behaviour can reject values if it thinks they are out of range.13 Building a Bank We are now in a situation where we can create working bank accounts. bool StoreAccount (IAccount account). This container class will provide methods which allow us to find a particular account based on the name of the holder. 4.Age = 121. since there is no way that the property can return a value which indicates success or failure. the person performing the assignment would not be aware of this.
13. When we add an account to the bank we simply make one of the references refer to that account instance. The element at the start of the array contains a reference to the account instance. Each reference in the array can refer to an object which implements the IAccount interface. printing out a message if the storage worked. We never place an account "in" the array. In the code above we are creating a bank with enough room for references to 50 accounts. accounts Name : "Rob" Balance : 0 The diagram shows the state of the accounts array after we have stored our first account. The constructor creates an array of the appropriate size when it is called: private IAccount [] accounts .Creating Solutions Building a Bank A class which implements these methods can be used for the storage of accounts. What we have created is an array of references. The method to add an account to our bank has to find the first empty location in the array and set this to refer to the account that has been added: C# Programming © Rob Miles 2010 130 . they are all set to null. instead we put a reference to that account in the array. 0). When you create an instance of an ArrayBank you tell it how many accounts you want to store by means of the constructor.StoreAccount(account)) { Console. 4. But at the moment none of the references refer anywhere. The light coloured elements are set to null.1 Storing Accounts in an array The class ArrayBank is a bank account storage system which works using arrays. public ArrayBank( int bankSize ) { accounts = new IAccount[bankSize].WriteLine ( "Account stored OK" ). We have not created any accounts at all. IAccount account = new CustomerAccount("Rob". } The code above creates a bank and then puts an account into it. } Note that it is very important that you understand what has happened here. I can put an account into it and then get it back again: IBank friendlyBank = new ArrayBank (50). if (friendlyBank.
If it reaches the end of the array without finding a match it returns null. } } return null. position<accounts. otherwise it returns a reference to the account that it found. When we want to work on an account we must first find it.13. If it finds one it sets this to refer to the account it has been asked to store and then returns true. The bank interface provides a method called FindAccount which will find the account which matches a particular customer name: IAccount fetchedAccount = arrayBank. However.Length . position++) { if (accounts[position] == null) { accounts[position] = account. for (position=0 . } if ( accounts[position]. for (position = 0.13. 4. since it uses a technique which will take us straight to the required item. position++) { if ( accounts[position] == null ) { continue. but if there are thousands of accounts this simple search will much to slow. return true.3 Storing Accounts using a Hash Table Fortunately for us we can use a device called a "hash table" which allows us to easily find items based on a key This is much faster than a sequential search. or null if the account cannot be found. position<accounts. C# Programming © Rob Miles 2010 131 . 4. Each time we add a new account the searching gets slower as the FindAccount method must look through more and more items to find that one. If it does not find a null element before it reaches the end of the array it returns false to indicate that the store has failed.FindAccount("Rob"). If it finds an element which contains a null reference it skips past that onto the next one. and could be used as the basis of a bank. On a bank with only fifty accounts this is not a problem. it becomes very slow as the size of the bank increases.2 Searching and Performance The solution above will work fine. } } return false. } This code works its way through the accounts array looking for an entry with a name which matches the one being looked for. In the array based implementation of the bank this is achieved by means of a simple search: public IAccount FindAccount ( string name ) { int position=0 .Length. } This method works through the array looking for an element containing null.GetName() == name ) { return accounts[position]. This will either return the account with the required name.Creating Solutions Building a Bank public bool StoreAccount (IAccount account) { int position = 0.
This is poetically referred to as a "hash clash". In short. The name "Rob" could be converted to 82+111+98 = 291. C# Programming © Rob Miles 2010 132 . It turns out to be very easy to create a bank storage mechanism based on this: class HashBank : IBank { Hashtable bankHashtable = new Hashtable(). It is used in preference to the code: return (IAccount) bankHashtable[name].13. 4. return true. look up the ASCII code for each letter and then add these values up. } } The Hashtable class can be found in the System. but we can't completely avoid clashes. Since this is just what the caller of our FindAccount method is expecting this can be returned back directly. the hash function gives us a starting point for our search. For example. If we find the location we would like to use is not null we simply work our way down looking for the first free location on from that point. This will store items for us based on a particular object which is called the key. If a cast fails (i. rather than always looking from the beginning of the array in our simple array based code above. The as operator is a form of casting (where we force the compiler to regard an item as being of a particular type). It provides a method called Add which is given the value of the key and a reference to the item to be stored on that hash code. we could take all the letters in the account name string. or returns something of the wrong type.Creating Solutions Building a Bank The idea is that we do something mathematical (called "hashing) to the information in the search property to generate a number which can then be used to identify the location where the data is stored. We want to return a reference to an instance which implements the IAccount interface. account).4 Using the C# Hashtable collection Fortunately for us the designers of the C# have created a hash table class for us to use.e. Clashes can be resolved by adding a test when we are storing an account. } public bool StoreAccount(IAccount account) { bankHashtable. This greatly speeds up access to the data.. It also allows you to use a reference to the key (in this case the name) to locate an item: return bankHashtable[name] as IAccount.Collections namespace. The as operator has the advantage that if bankHashtable[name] does not return an account. Of course this hash code is not foolproof.GetName(). at run time the bank hash table returns the wrong thing) our program will fail with an exception.Add(account. the name "Rpa" would give the same total (82+112+97) and refer to the same location. the as operator will generate a null reference. We could look in location 291 for our account. public IAccount FindAccount(string name) { return bankHashtable[name] as IAccount. We have to use the "as" part of this coded as the collection will return a reference to an object.
Bank Notes: Key properties are important The action that is being performed here is exactly the same as what happens when you use your cash card to draw some money from the bank. The cash machine uses information on the card as a key to find your account record so that it can check your balance value and then update it when the money has been withdrawn. When gathering metadata about a system you will often need to consider which of the properties of an item will be key fields.Creating Solutions Building a Bank It is interesting to note that because we have implemented our bank behaviour using an interface. which is the name of the account holder. address or account number depending on the information they have available. In our simple bank we only have a single key. In a real bank the key will be more complex. and there may well be more than one. so that they can search for an account holder by name. C# Programming © Rob Miles 2010 133 . we can very easily change the way that the account storage part of the program works without changing anything else.
store. This statement probably doesn't tell you much about them or what they do. They sound a bit scary. in that the idea of them is that you specify a general purpose operation and then apply it in different contexts in a way appropriate to each of them. then it might be worth re-reading those bits of the book until they make sense.1 Generics and Collections Generics are very useful. This leads to a "straw that breaks the camel's back" problem. One way to solve this problem is to use a really big array. The ArrayList called storeFifty is initially able to store 50 references. we are instead making one element of the arraylist refer to that account. Creating an ArrayList It is very easy to create an ArrayList: ArrayList store = new ArrayList(). but we aren't that keen on that because it means that for smaller banks the program might be wasting a lot of memory. But we know that when an array is created the programmer must specify exactly how many elements it contains.1.000 and our program crashes. telling people you learned about "generics" probably conjures up images of people with white coats and test tubes. The class provides an Add method: Account robsAccount = new Account (). and some very clever code in the library makes sure that this works. Perhaps the best way to talk about generics is to see how they can help us solve a problem for the bank. C# Programming © Rob Miles 2010 134 . It lets us create something very useful. It is important to remember what is going on here. We are not putting an Account into the arraylist. but it does indicate that they are very useful. 5.Add(robsAccount).Collections namespace. If it doesn't.Advanced Programming Generics and Collections 5 Advanced Programming 5. In this respect the word Add can be a bit misleading. in that what it actually does is add a reference. We have just seen that we can store Account references in an Array. Adding Items to an ArrayList Adding items to an ArrayList is also very easy. Fortunately the C# libraries provide a number of solutions. because the array size was set at 10. Note that you don't have to set the size of the ArrayList. an array that can grow in size. starting with the simple ArrayList. although there are overloaded constructors that let you give this information and help the library code along a bit: ArrayList storeFifty = new ArrayList(50). but it can hold more or less as required. at least amongst those who can't spell very well. If this sounds a bit like abstraction and inheritance you are sort of on the right track. But I digress.001st customer to the bank is not actually a cause for celebration. We can always add new elements to the ArrayList.1 The ArrayList class The ArrayList is a cousin of the HashTable we have just seen. in that it lives in the same Systems. I think the root of Generics is probably "general". not the thing itself. where adding the 10.
PayInFunds(50). The designers of the ArrayList class had no idea precisely what type of object a programmer will want to use it with and so they had to use the object reference. The reason for this is that an arraylist holds a list of object references. Note that if the reference given is not actually in the arraylist (i. So.]. the list actually contains a reference to that item. Finding the size of an ArrayList You can use the property Count to find out how many items there are in the list: if (store.e.Count == 0) { Console. This means that I can't be sure that an arraylist you give me has nothing other than accounts in it: KitchenSink k = new KitchenSink(). To get a properly typesafe Account storage we have to take a look at generics in detail a bit later. Unfortunately this won't work. This puts a reference to a KitchenSink instance into our bank storage. it is not necessarily destroyed.WriteLine("The bank is empty"). This is not actually a huge problem. store. This is given a reference to the thing to be removed: store. It might be that the bank has many lists of customers. If you think about it. it is just no longer on that list. If you remove an item the size of the arraylist is decreased.Remove(robsAccount). It would be very nice if we could just get hold of the account from the arraylist and use it.PayInFunds(50). along with a list of "special" customers and perhaps another list of those who owe it the most money. This removes the first occurrence of the reference robsAccount from the store arraylist. an item "in" an arraylist is never actually in it. This will cause problems (and an exception) if we ever try to use it as an Account. Account a = store[0]. but with a tricky twist. A slightly larger problem is that an arraylist is not typesafe. just like your name can appear on multiple lists in the real world. Accessing Items in an ArrayList Items in arraylists can be accessed in just the same way as array elements. This would get the element at the start of the arraylist. When an item is removed from an arraylist. but the arraylist class provides a really useful Remove behaviour. a.Add(k). a. this is the only thing that it could hold. It will have a list of all the customers. cast it into an Account class and then pay fifty pounds into it. If you write this code you will get a compilation error. Removing Items from an ArrayList It is not really possible to remove things from an array. If the store contained more than one reference to robsAccount then each of them could be removed individually. You will no doubt remember from the discussion of object hierarchies that an object reference can refer to an instance of any class (since they are all derived from object) and so that is the only kind of reference that the arraylist works with.Advanced Programming Generics and Collections Remember that it would be perfectly possible to have robsAccount in multiple arraylists.
string. and provides you with some means to work with them. You could of course write this behaviour yourself. This is all to the good. we can sort that out when we actually want to work with something. 5. However. and because it is not quite as much a part of the language as an array is. but this can lead to programs which are dangerous. It doesn't matter what the thing I'm dealing with is. Generics and Behaviours If you think about it. It does this by using references to objects. being based on the generic features provided by a more recent version of the C# language. with the advantage that it is also typesafe. that is not what the designers of C# did. C# Programming © Rob Miles 2010 136 . C# can make sure that an array always holds the appropriate type of values. They also throw exceptions if you try to access elements that are not in the array. One way to solve this problem would have been to find a way of making the ArrayList strongly typed.Contains(robsAccount)) { Console. If you give me an array of Accounts I can be absolutely sure that everything in the array is an account. And I only really find out when I start trying to process elements as Accounts and my program starts to go wrong. if you give me an ArrayList there is no way I can be sure that accounts are all it contains. It is newer than the ArrayList class. Whether you have an int. However. float or Account array the job that it does is exactly the same. there is just no way that you can take an Account reference and place it in element in an array of integers. but having it built into the class makes it much easier.Advanced Programming Generics and Collections Checking to see if an ArrayList contains an item The final trick I'm going to mention (but there are lots more things an arraylist can do for you) is the Contains method. but the ArrayList breaks things a bit. It holds a bunch of things in one place. The abilities an array gives you with an array of integers are exactly the same as those you have with an array of Accounts. If you wish you can use arraylists in place of arrays and have the benefits of storage that will grow and shrink as you need it. it has to use a compromise to allow it to hold references to any kind of item in a program. } The Contains method is given a reference to an object and returns true if the arraylist contains that reference. The way that the system works. so that it because as much a part of C# as the array is. this can be fixed when you move over to the List class. Generics let me write code that deal with objects as "things of a particular type". This is simply a quick way of finding out whether or not an arraylist contains a particular reference. They both let you store a large number of items and you can use subscripts (the values in square brackets) to get hold of elements from either. ArrayLists and Arrays Arraylists and arrays look a lot the same. in that there is nothing to stop references of any type being added to an arraylist. The ArrayList was added afterwards. generics. not any particular class. if (a.1. the fundamental behaviours of arrays are always the same.WriteLine("Rob is in the bank"). the only problem that you have is that an arraylist will always hold references to objects. It could contain a whole bunch of KitchenSink references for all I know. And because each array is declared as holding values of a particular type.2 The List class The List class gives you everything that an arraylist gives you. However. Instead they introduced a new language feature. To understand how it works you have to understand a bit of generics.
robsAccount).Advanced Programming Generics and Collections This sounds a bit confusing. There is no need to cast the item in the list as the type has already been established. you could also use it to share out sweets. cousin called List. You could take your universal sharing algorithm and use it to share most anything. This allows the key to your hashtable. What the system works on is not particularly important. The above statements would cause a compilation error. how about an example. However. we have a string as the key and an Account reference as the value. generics can be regarded as another form of abstraction. In other words.Account> accountDictionary = new Dictionary<string. In other words statements like this would be rejected. The List class lives in the System. You now have a system that lets you share marbles. We can now add items into our dictionary: accountDictionary. This looks just like the way the HashTable was used (and it is). cakes or even cars.1. generically enhanced. this means that you can write code like this: accountList[0]. We can create a dictionary to hold these key/value pairs as follows: Dictionary<string. since the acountList variable is declared as holding a list of Account references. In this respect.Collections. The above statement creates a list called acountList which can hold references to Accounts.PayInFunds(50).Add("Rob". What the list stores is not important when making the list. just as long as you have a way of telling it what to store. We could create a List that can hold integers in a similar way: List<int> scores = new List<int>(). to be made typesafe. For example. Since the compiler knows that AccountList holds Account references. using a Dictionary has the advantage that we can only add Account values which are located by means of a string. the behaviour you want is that of a list. Count. so the HashTable has a more powerful cousin called Dictionary. and the items it stores. Something like: "Divide the number of marbles by the number of friends and then distribute the remainder randomly". The type between the < and > characters is how we tell the list the kind of things it can store. accountList.3 The Dictionary class Just as ArrayList has a more powerful. The C# features that provide generics add a few new notations to allow you to express this. Remove) that you can with an ArrayList. The sharing algorithm could have been invented without worrying about the type of the thing being shared. If you wanted to share out marbles amongst you and your friends you could come up with way of doing that. Generics and the List In the case of generics. it can be a general sharing behaviour that is then applied to the things we want to share.Generic namespace and works like this: List<Account> accountList = new List<Account>(). we might want to use the name of an account holder as a way of locating a particular account.Account>(). Because we have told the compiler the type of things the list can hold it can perform type validation and make sure that nothing bad happens when the list is used: KitchenSink k = new KitchenSink(). You can do everything with a List (Add. C# Programming © Rob Miles 2010 137 .Add(k). which makes them the perfect way to store a large number of items of a particular type. 5. However. and will not accept the kitchen sink.
We can create a class called CustomerAccount which implements the interface and contains the required methods. We can express the required account behaviour in terms of the following interface: public interface IAccount { void PayInFunds ( decimal amount ). bool WithdrawFunds ( decimal amount ). make a List.WriteLine("Rob is in the bank").Add("Glug". C# Programming © Rob Miles 2010 138 . How these features are used to create generic classes is a bit beyond the scope of this text. use a Dictionary. string GetName(). but you are strongly advised to find out more about generics as it can make writing code. The account that we are going to work with only has two members but the ideas we are exploring can be extended to handle classes containing much larger amounts of data. Programmer’s Point: Use Dictionary and List You don't really have to know a lot about generics to be able to spot just how useful these two things are. Don't have any concerns about performance. k). Then we can move on to consider the code which will save a large number of them. } The Dictionary class is simply wonderful for storing keys and values in a typesafe manner. and I recommend it strongly to you. This would find the element with the hash key "Rob" and then pay fifty pounds into it.1. The programmers who wrote these things are very clever folks . You can get around this by asking the dictionary if it contains a particular key: if (d. } All the accounts in the bank are going to be managed in terms of objects which implement this interface to manage the balance and read the name of the account owner. and then save them when the program completes. a lot easier. If we want to our program to be able to process a large number of accounts we know that we have to create an array to manage this. To start with.4 Writing Generic Code The List and Dictionary classes were of course written in C# and make use of the generic features of the language. 5.ContainsKey("Rob")) { Console. The only problem with this use of a dictionary is that if there is no element with the key "Rob" the attempt to find one will result in a KeyNotFoundException being thrown. Every time you need to hold a bunch of things. This means that our data storage requirements are that we should load all the accounts into memory when the program starts. accountDictionary. we'll consider how we save one account. particularly library routines. decimal GetBalance ().Advanced Programming Storing Business Objects KitchenSink k = new KitchenSink(). A further advantage is that we do not need to cast the results: d["Rob"]. If you want to be able to find things on the basis of a key.2 Storing Business Objects For our bank to really work we have to have a way of storing the bank accounts and bringing them back again. It also has a constructor which allows the initial name and balance values to be set when the account is created. 5.PayInFunds(50).
} public string GetName() { return name. public virtual bool WithdrawFunds ( decimal amount ) { if ( balance < amount ) { return false.2.1 Saving an Account The best way to make achieve the saving behaviour is to make an account responsible for saving itself. this is the only way that we can save an account. so it is not what I would call "production" code. } public decimal GetBalance () { return balance. decimal initialBalance) { name = newName. } } Note that this version of the class does not perform any error checking of the input values.Advanced Programming Storing Business Objects public class CustomerAccount : IAccount { public CustomerAccount( string newName. } balance = balance . if you think about it. since any save mechanism would need to save data in the account which is private and therefore only visible to methods inside the class. In fact. balance = initialBalance. 5. private string name. } private decimal balance = 0.amount . We can add a Save method to our CustomerAccount class: C# Programming © Rob Miles 2010 139 . } public void PayInFunds ( decimal amount ) { balance = balance + amount . return true. but it is just here to illustrate how the data in the class can be saved and restored.
IO.ReadLine(). } return true. } This would ask the account referred to by Rob to save itself in a file called "outputFile.WriteLine ("Saved OK").Advanced Programming Storing Business Objects public bool Save ( string filename ) { try { System.ReadLine(). } catch { return false. } finally { if (textIn != null) textIn.2 Loading an Account Loading is slightly trickier than saving. It writes out the name of the customer and the balance of the account.txt". textOut.StreamWriter(filename). } catch { return null.TextReader textIn = null. C# Programming © Rob Miles 2010 140 . When we save an account we have an account which we want to save. So I could do things like: if (Rob. textOut. } This method opens a file.2.IO.balance). Note that I have written the code so that if the file output fails the method will return false. } return result.txt")) { Console. A way to get around this is to write a static method which will create an account given a filename: public static CustomerAccount Load(string filename) { CustomerAccount result = null. textOut. fetches the balance value and then creates a new CustomerAccount with the balance value and name. } This method is given the name of the file that the account is to be stored int. try { textIn = new System.StreamReader(filename). decimal balance = decimal.Save ("outputFile.Close() .WriteLine(name).IO. string balanceText = textIn. to indicate that the save was not successful. System. string nameText = textIn.IO. 5.WriteLine(balance).Parse(balanceText). When we load there will not be an account instance to load from.Close().TextWriter textOut = new System. The Load method above takes great pains to ensure that if anything bad happens it does a number of things: It does not throw any exceptions which the caller must catch. result = new CustomerAccount(nameText.
It makes sure that the file it opens is always closed. We could create a new file for each account. and is something you should aim for when writing code you are going to sell. in that it creates an instance of a class for us.TextWriter textOut = new System.Load( "test. A stream is the thing that the C# library creates when we open a connection to a file: System.IO.2.StreamWriter( "Test. This is what I would call a "professional" level of quality. since that makes sure that a failure is brought to the attention of the system much earlier. your part doesn’t break. you can argue this either way. Using streams A better solution is to give the file save method a stream to save itself.3 Multiple Accounts The above code lets us store and load single accounts. The reference textOut refers to a stream which is connected to the file Test. We can create a save method which accepts the stream reference as a parameter instead of a filename: public void Save(System.IO.WriteLine( "Load failed" ). whatever happens. Actually. you just have to make sure that.WriteLine(balance). textOut.Advanced Programming Storing Business Objects It returns null to indicate that the load failed if anything bad happens. And they will probably try and blame me for the problem (which would be very unfair). at the moment we can only store one account in a file.WriteLine(name).TextWriter textOut) { textOut.txt" ). However. If the factory fails (because the file cannot be found or does not contain valid content) it will return a null result. } Programmer’s Point: There is only so much you can do Note that if an incompetent programmer used my Load method above they could forget to test the result that it returns and then their program would follow a null reference if the customer is not found. as I grow older I become more inclined to make my programs throw exceptions in situations like this. This means that their program will fail in this situation. the best place to do it is at the pub.txt. The way around this is to make sure that you document the null return behaviour in big letters so that users are very aware of how the method behaves. At the end of the day though there is not a great deal you can do if idiots use your software.txt" ). These scan programs for situations where the results of methods are ignored and flag these up as potential errors. but this would be confusing and inefficient. We can use this as follows: test = CustomerAccount. 5. However. You can also get code analysis tools which are bit like "compilers with attitude" (a good one is called FxCop). This kind of method is sometimes called a ―factory‖ method. which we can test for: if (test == null) { Console. rather than a filename. } This save method can be called from our original file save method: C# Programming © Rob Miles 2010 141 .IO. with large numbers of file open and close actions being required (bear in mind that our bank may contain thousands of accounts).
} This method creates a stream and then passes it to the save method to save the item. For example. This means that if you make your business objects save and load themselves using streams they can then be sent over network connections with no extra work from you. } catch { return null.IO. The load method for our bank account can be replaced by one which works in a similar way.TextReader textIn) { CustomerAccount result = null. try { textOut = new System. This will open a stream and save all the accounts to it: C# Programming © Rob Miles 2010 142 . } This method is supplied with a text stream.TextWriter textOut = null. It reads the name and the balance from this stream and creates a new CustomerAccount based on this data. Saving and loading bank accounts Now that we have a way of saving multiple accounts to a single stream we can write a save method for the bank. The C# input/output system lets us connect streams to all manner of things.ReadLine(). balance). try { string name = textIn. } finally { if (textOut != null) { textOut. decimal balance = decimal.Parse(balanceText). string balanceText = textIn. Programmer’s Point: Streams are wonderful Using streams is a very good idea. Save(textOut).IO. you can create a stream which is connected to a network port. not just files on a disk.ReadLine(). } catch { return false.Close(). } return result.StreamWriter(filename). Note that this is an example of overloading in that we have two methods which share the same name.IO.Advanced Programming Storing Business Objects public bool Save ( string filename ) { System. result = new CustomerAccount(name. } } return true. public static CustomerAccount Load( System.
Bank Notes: Large Scale Data Storage What we have done is created a way that we can store a large number of bank account values in a single file. in that only the CurrentAccount class is responsible for the content. A production version of the program would check that each account was loaded correctly before adding it to the hash table. string countString = textIn. i < count.Count). We have done this without sacrificing any cohesion.Add(account. in that everything is written in terms of the CurrentAccount class. 5.. The reason that it is here is for completeness.TextReader textIn) { HashBank result = new HashBank().IO. but this would not allow us to detect if the file had been shortened. we have seen that our customer needs the program to be able to handle many different kinds of account. We could just write out the data and then let the load method stop when it reaches the end of the file.Advanced Programming Storing Business Objects public void Save(System. Note that this load method does not handle errors. int count = int.TextWriter textOut) { textOut. The Load method for the entire bank is as follows: public static HashBank Load(System. This is very useful when dealing with collections of data. and supplies each item in turn. We do this is so that when the bank is read back in the load method knows how many accounts are required. in this case the Values property of the bankHashtable. Health Warning This is complicated stuff.ReadLine(). } } This is the Save method which would be added to our Hashtable based bank.Save(textOut). Note that before it writes anything it writes out the number of customers in the bank.4 Handling different kinds of accounts The code above will work correctly if all we want to save and load are accounts of a particular type. result. for (int i = 0.2.bankHashtable. It works its way through a collection. foreach (CustomerAccount account in bankHashtable. account). However. i++) { CustomerAccount account = CustomerAccount.Load(textIn).Parse(countString). This can be obtained via the Count property of the Hashtable. foreach.Values) { account.WriteLine(bankHashtable. I don't expect you to understand this at first reading. } This reads the size of the bank and then reads each of the accounts in turn and adds it to the hash table. } return result.GetName(). We have also been very careful to make sure that whenever we save and load data we manage the way that this process can fail. Note that we are using a new C# loop construction here. It gets each account out of the hash table and saves it in the given stream. This material is provided to give you an idea of C# Programming © Rob Miles 2010 143 .IO.
It contains an additional property. This turns out to be very easy. The customer has also asked that the BabyAccount class contains the name of the "parent" account holder. } return base. } public override bool WithdrawFunds(decimal amount) { if (amount > 10) { return false. We could implement such behaviour by creating an account which extends the CustomerAccount class and adds the required behaviours and properties: public class BabyAccount : CustomerAccount { private string parentName. we have previously discussed the BabyAccount. 20. I can create a BabyAccount as follows: BabyAccount babyJane = new BabyAccount ("Jane". The good news is that when you do understand this stuff you really can call yourself a fully-fledged C# programmer. Saving a child class When we want to save a BabyAccount we also need to save the information from the parent class. a special account for young people which limits the amount that can be withdrawn to no more than 10 pounds. as long as we use the save method which sends the information to a stream: C# Programming © Rob Miles 2010 144 . string inParentName) : base(newName. "John"). As an example. method overriding/overloading and constructor chaining. and overrides the WithdrawFunds method to provide the new behaviour. some of which will be based on others. This would create a new BabyAccount instance and set the reference babyJane to refer to it. Note that I have created a constructor which is supplied with the name of the account holder. initialBalance) { parentName = inParentName.Advanced Programming Storing Business Objects how you really could make a working bank. This makes use of the constructor in the parent to set the balance and name.WithdrawFunds(amount). but it assumes a very good understanding of class hierarchies. } public BabyAccount( string newName. the starting balance and the name of the parent. Banks and Flexibility We know that when our system is actually used in a bank there will be a range of different kinds of account class. } } This is a complete BabyAccount implementation. decimal initialBalance. and then sets the parent name. public string GetParentName() { return parentName. parentName.
Loading a child class We could create a static load method for the BabyAccount which reads in the information and constructs a new BabyAccount: public static BabyAccount Load( System. What we do is create constructors for the CustomerAccount and BabyAccount classes which read their information from a stream that is supplied to them: public CustomerAccount(System. } return result.ReadLine().ReadLine(). parent).. balance = decimal. Then it performs the save behaviour required by the BabyAccount class. and it can be passed information to allow it to do this.Parse(balanceText).ReadLine().WriteLine(parentName). } catch { return null. } This constructor sets up the new CustomerAccount instance by reading the values from the stream that is supplied with. } However.IO. string parent = textIn. string balanceText = textIn.Save(textOut). What we really want to do is make the CustomerAccount responsible for loading its data and the BabyAccount just look after its content. try { string name = textIn. string balanceText = textIn.TextWriter textOut) { base. } This method overrides the Save method in the parent CustomerAccount. This is very good design. The way to do this is to go back to the construction process. as it means that if the data content and save behaviour of the parent class changes we don't need to change the behaviour of the child.Parse(balanceText). A constructor can be used to set up the data in the instance. This method breaks one of the rules of good design. In the code above there is a constructor for the BabyAccount class which accepts the three data items that the BabyAccount holds and then sets the instance up with these values.TextReader textIn) { name = textIn. textOut. result = new BabyAccount (name.Advanced Programming Storing Business Objects public override void Save(System. I'm not particularly keen on this approach.ReadLine(). balance.TextReader textIn) { BabyAccount result = null. I can therefore write code like this: C# Programming © Rob Miles 2010 145 . decimal balance = decimal.ReadLine().IO. it first calls the overridden method in the parent to save the CustomerAccount data. in a similar way to the way the save method uses the base keyword to save the parent object. We know that a constructor is a method which gets control when an instance of a class is being created. If I forget to do this the program will compile.IO. However. but when it runs it will not work correctly.
} } C# Programming © Rob Miles 2010 146 . This is a good idea. decimal GetBalance (). This creates a new CustomerAccount from the stream. but it could be updated to include them: public interface IAccount { void PayInFunds ( decimal amount ).TextReader textIn) : base (textIn) { parentName = textIn.Close().IO.Values) { textOut. things get a little trickier.TextReader textIn = new System. Also. bearing mind we are reading from a stream of data.IO. Note that these constructors do not do any error checking. If the behaviour of the CustomerAccount constructor changes we do not have to change the BabyAccount at all.WriteLine(account. You might think it would be sensible to add load methods to the IAccount interface. account. However. The solution to this problem is to identify the type of each instance in the steam when we save the classes. } This removes the dependency relationship completely.ReadLine().Advanced Programming Storing Business Objects System. textIn. they just throw exceptions if something goes wrong. in that when we are loading the accounts we don't actually have an instance to call any methods on.StreamReader(filename).WriteLine(bankHashtable. Interfaces and the save operation When we started this account development we set out an interface which describes all the things which an instance of an account should be able to do. Now I can create a constructor for the BabyAccount which uses the constructor of the parent class: public BabyAccount(System. Bearing in mind that the only way that a constructor can fail is to throw an exception anyway. void Save(System. string GetName(). Loading and factories When it comes to loading our classes back.Save(textOut). foreach (CustomerAccount account in bankHashtable. bool WithdrawFunds ( decimal amount ). there is a problem here. it just has to call the save method for the particular instance. result = new CustomerAccount(textIn).Name). The save method for our bank could look like this: public void Save(System. At the start this did not include the save behaviours. since the account container will not have to behave differently depending on what kind of account it is saving.IO. bool Save(string filename).IO. this is reasonable behaviour.TextWriter textOut) { textOut. we don't actually know what kind of item we are loading. so that we can ask instances of a particular kind of account to load themselves. } We can now ask any item which implements the IAccount interface to save itself to either a file or a stream. This is very useful when we store our collection of accounts.TextWriter textOut).Count).IO.GetType().
This writes out the name of the class. } } } This class only contains a single method. The method is given two parameters. It uses the name to decide which item to make. i < count. creates one.TextReader textIn) { switch (name) { case "CustomerAccount": return new CustomerAccount(textIn).ReadLine(). if the account is of type CustomerAccount the program will output: CustomerAccount Rob 100 The output now contains the name of the type of each class that has been written. this looks very like our original load method. It involves writing code which will search for C# classes which implement particular interfaces and creating them automatically. The bank load method can use this factory to create instances of accounts as they are loaded: public static HashBank Load(System. The neatest way to do this is to create a factory which will produce instances of the required class: class AccountFactory { public static IAccount MakeAccount( string name. There is in fact a way of removing the need to do this.MakeAccount(className. result.IO. which is static. C# Programming © Rob Miles 2010 147 . which has been highlighted.bankHashtable. It makes use of the method GetType(). } return result. If we ever add a new type of account we need to update the behaviour of the factory so that it contains a case to deal with the new account type. } Again.ReadLine(). System. If the name is not recognized it returns null.GetName(). string countString = textIn.IO. Factory Dependencies Note that we now have a genuine dependency between our system and the factory class.Advanced Programming Storing Business Objects This looks very like our original method. int count = int. However this kind of stuff is beyond the scope of this text. account). textIn). IAccount account = AccountFactory. i++) { string className = textIn. case "BabyAccount": return new BabyAccount(textIn).Parse(countString). except that it uses the factory to make account instances once it has read the name of the class from the stream.TextReader textIn) { HashBank result = new HashBank(). Having got the type we can then get the Name property of this type and print that. except that it has an additional line. and then returns that to the caller. the name of the class to be created and a stream to read from. This means that when the stream is read back in this information can be used to cause the correct type of class to be created. which can be called on an instance of a class to get the type of that class. In other words. for (int i = 0. default: return null.Add(account.
This is because classes like CustomerAccount are what is called business objects. The job of the business object is to make sure that the data that it holds is always correct. If it is going to reject names it would be very useful to the user if they could be told why a given name was not valid. 5. so the validation process should provide feedback as to why it did not work. This might make the examples a bit more complex that you might like. by providing a user interface which lets people interact with our business objects to run the bank.3 Business Objects and Editing We have seen how to design a class which can be used to hold information about the customers in our bank. there is more to it than just changing one string for another. The way that we manage the saving of items (by using a method in the class) loading (by using a constructor) is not symmetrical. This means that the business object must provide a way that the name can be changed. and the problems you are grappling with. We now also know how to save the information in a class instance. 5. It is important that this is always stored safely but people may want to change their name from time to time. This is code which I would be happy to have supplied in a product. However. A good software engineer would provide something like this: C# Programming © Rob Miles 2010 148 .Advanced Programming Business Objects and Editing Bank Notes: Messy Code You might think that the solutions above are rather messy. However.3. This means that the account must be able to reject names it doesn't like. Managing a bank account name As an example.1 The role of the Business Object We have taken a very strict line in our banking system to stop any of the bank account components from actually talking to the user. It is not their job to talk to users. and also perform this for a large number of items of a range of different types. This means that I will be considering what things you should look at when you are writing code for real customers. they are strictly concerned with keeping track of the information in the bank account of the customer. Programmer’s Point: Production Code From now on all the code examples are going to be given in the context of production code. When you want to move from objects to storage and back you will find that you hit these issues and this solution is as good as any I've found. The new name must be a valid one. Now we need to consider how we can make our account management system genuinely useful. consider the name of the bank account holder. there is no dishonour in this way of working. but I reckon this is worth doing since it is important you start to understand that what you are writing now. are just those that "real" programmers are up against. The editing behaviours should make use of the methods that the business object exposes.
Length == 0 ) { return "No text in the name". The validate method will reject a name string which is empty. I’ve also made this method static so that names can be validated without needing to have an actual instance of the account. once we have these methods. if ( trimmedName. There may be several reasons why a name is not valid. the string is rejected. since I also use the method myself when I validate the name. } public bool SetName ( string inName ) { string reply . } The name is stored as a private member of the account class. or just contains spaces. } this. } public static string ValidateName ( string name ) { if ( name == null ) { return "Name parameter null". This does not involve me in much extra work. There is a method to get the name. public string GetName() { return this. The programmer has provided three methods which let the users of my Account class deal with names. Testing Name Handling Of course.Advanced Programming Business Objects and Editing private string name.name. reply = ValidateName(inName). the natural thing to do is create tests for them: C# Programming © Rob Miles 2010 149 .Length > 0 ) { return false. if ( reply. It trims off all the spaces before and after the name text and then checks to see if the length of the resulting string is empty. The validate method is called by the set method so that my business object makes sure that an account never has an invalid name.Trim(). } return "".Trim(). The validate method returns a string which gives an error message if the string is rejected.name = inName. at the moment I've just given two. If it is. return true. The reasons why a name is invalid are of course part of the metadata for the project. } string trimmedName = name. I provide the validate method so that users of my class can check their names to make sure that they are valid. another to set it and another to validate it.
errorCount++. errorCount++. } if (errorCount > 0 ) { SoundSiren(). errorCount++. Editing the Name We now have a business object that provides methods which let us edit the name value.WriteLine("Jim GetName failed"). } reply = CustomerAccount. This is because they are much easier to compare in tests and it also means that my program could be made to work in a foreign language very easily.WriteLine("Null name test failed"). Programmer’s Point: Use Numbers Not Messages There is one issue which I have not addressed in my sample programs which stops them from being completely perfect. reply = CustomerAccount. } CustomerAccount a = new CustomerAccount("Rob". errorCount++. You should consider issues like this as part of the metadata in your project. string reply. errorCount++.WriteLine("Pete trim SetName failed"). } if ( a. } These are all the tests I could think of.ValidateName(""). And that is the matter of error handling.WriteLine("Pete GetName failed"). First I test ValidateName to make sure that it rejects both kinds of empty string.ValidateName(null). 50).ValidateName(" "). } if (!a. In a genuine production environment the errors would be numeric values. if (reply != "No text in the name") { Console.GetName() != "Jim" ) { Console. I can now write code to edit this property: C# Programming © Rob Miles 2010 150 . if (!a. All I would need is a lookup table to convert the message number to an appropriate string in the currently active language. } if ( a. At the moment the errors supplied by my validation methods are strings.WriteLine("Blank string name test failed").SetName("Jim")) { Console. The fact that the system must work in France and Germany is something you need to be aware of right at the start. if (reply != "No text in the name") { Console.WriteLine("Empty name test failed"). Finally I check that the space trimming for the names works correctly.GetName() != "Pete" ) { Console.SetName(" Pete ")) { Console. errorCount++. if (reply != "Name parameter null") { Console. } reply = CustomerAccount. Then I make sure that I can set the name on an account. errorCount++.WriteLine("Jim SetName failed").Advanced Programming Business Objects and Editing int errorCount=0.
public AccountEditTextUI(Account inAccount) { this. When I want to edit an account I create an editor instance and pass it a reference to the account instance: public class AccountEditTextUI { private IAccount account. string reply. } public void EditName () { string newName. string reply. newName = Console. while (true) { Console. If the name is valid the loop is broken and the name is set. This is not the most elegant solution.WriteLine( "Invalid name : " + reply ).WriteLine( "Name Edit" ). } Console. Creating an Editor class The best way to do this is to create a class which has the job of doing the editing.ValidateName(newName). There will be a dependency between the editor class and the account class. This class will work on a particular account that needs to be edited.SetName(newName).account.ValidateName(newName).WriteLine( "Invalid name : " + reply ).ReadLine(). This code will perform the name editing for an account instance referred to by account. if ( reply. } Console.Write ( "Enter new name : " ) .ReadLine(). in that if the account class changes the editor may need to be updated. It will read a new name in.Advanced Programming Business Objects and Editing while (true) { Console. } } C# Programming © Rob Miles 2010 151 . } account. Now that we have our edit code we need to put it somewhere.Write ( "Enter new name : " ) . If the name is not valid the message is printed and the loop repeats. newName = Console. if ( reply.Length == 0 ) { break.SetName(newName).Length == 0 ) { break. Console. but it does keep the user informed of what it is doing and it does work.account. reply = this.account = inAccount. but this is something we will just have to live with. reply = account. } this.
The class keeps track of the account it is editing.WriteLine ( " Enter exit to exit program" ). I pass it a reference to this account when I construct it. do { Console. If I want to "give" a class something to work on I will do this by calling a method in that class and passing the reference as a parameter to this method. Note that I trim the command string and convert it to lower case before using it to drive the switch construction which selects the command. Console.. command = command.3. Note that the editor class is passed a reference to the IAccount interface. switch ( command ) { C# Programming © Rob Miles 2010 152 . but I will add other edit methods later. This means that anything which behaves like an account can be edited using this class.Trim().2 A Text Based Edit System We now have a single method in our editor class which can be used to edit the name of a bank account.ToLower(). AccountEditTextUI edit = new AccountEditTextUI(a). Programmer’s Point: Get used to passing references around It is important that you get used to the idea of passing references between methods. This code creates an instance of a customer account. command = command. Console.Advanced Programming Business Objects and Editing This is my account editor class. not a references to the account class.WriteLine ( "Editing account for {0}".WriteLine ( " Enter draw to draw out funds" ). My edit class contains a method which does this: This is my edit method which repeatedly reads commands and dispatches them to the appropriate method. Console. It then creates an editor object and asks it to edit the name of that account. 50). The edit method is passed a reference to the account which is being edited.EditName(). You will use this technique when you create different editing forms 5. public void DoEdit (CustomerAccount account) { string command. I would use the name editor as follows: CustomerAccount a = new CustomerAccount("Rob".Write ("Enter command : ").GetName() ). At the moment it can only edit the name. account.WriteLine ( " Enter name to edit name" ). It then passes that reference to the service methods which will do the actual work. Console. edit. I've extended the account class to manage the account balance and added edit methods which pay in funds and withdraw them.ReadLine(). Note also that the editor remembers the account class that is being edited so that when I call EditName it can work on that reference. Console.WriteLine ( " Enter pay to pay in funds" ). command = Console.
This question is not the responsibility of the front end. case "draw" : WithDrawFunds(account). This class can be found in the System. case "pay" : PayInFunds(account). The user interface must always work on the basis that it will use the business object to perform this kind of validation. Everything should be managed in terms of message numbers. Note that we never do things like allow the user interface code to decide what constitutes a valid name. } } while ( command != "exit" ). } Programmer’s Point: Every Message Counts You should remember that every time your program sends text to the user you may have a problem with language. When we are dealing with windows on the screen our program is actually calling methods in the objects to make them do things like change size and colour. The C# libraries contain a set of resources which help you manage the internationalization of your programs. break. break. The only exception to this is the situation where the customer has assured you that the program will only ever be written for use in a particular language. I can create an instance of this class and ask it to do things for me: C# Programming © Rob Miles 2010 153 . a customer on a mobile phone and a customer at a cash machine. break.Advanced Programming A Graphical User Interface case "name" : EditName(account). In a properly written program this would be managed in terms of message numbers to make it easier to change the text which is output. Bank Notes: More Than One User Interface The bank may have a whole range of requirements for editing account details. These will range from an operator in a call centre. The menu for my bank account edit method sample code prints out text which is hard wired to English.1 Creating a Form If I want a form on the screen for the user to interact with. The object that I create is a Form. As a general rule in a production system you should never write out straight text to your user (this includes the names of commands that the user might type in). 5. The only thing that can decide on the validity of a name is the account object itself.4. 5.Windows. I need to create an instance of an object to do this for me. I hope that you can see that the only way we can manage all these different ways of interacting with the bank account is to separate the business object (the account itself) from the input/output behaviour.Forms namespace.4 A Graphical User Interface It should come as no surprise that a graphical user interface on the screen is represented by objects. an operator on a dial up terminal.
If I run the program above the following appears on the screen: When the window is closed with the red button. Label title = new Label (). f. class FormsDemo { public static void Main () { Form f = new Form(). it disappears and the program ends. We must create the components and add them to the form to make our user interface. } } This creates a label. f.Windows. For example. f. Adding Components to a Form A form is a container.Advanced Programming A Graphical User Interface using System.Text="Hello".ShowDialog(). to add a label to the form we can do the following: using System. sets the text property of the label to ―Hello‖ and then adds it to the controls which are contained by the frame. title.Add(title).Forms.Forms.ShowDialog().Windows. It can 'contain' a number of graphical components which are used to build the user interface. } } The Form class provides a method called ShowDialog. The result of this code is a form which looks like this: I can fiddle with the properties of a component to move it around on the screen and do lots of interesting things: C# Programming © Rob Miles 2010 154 . class FormsDemo { public static void Main () { Form f = new Form(). This asks the form to show itself and pause the program until the form is closed.Controls.
f. It lets the user cut and paste text in and out of the box using the Windows clipboard.Left=50. but what I want to do is provide a way that the name text can be edited.Controls. The TextBox gives me a great deal of functionality for very little effort on my part. it behaves like every text field you've ever used on a windows screen.Drawing. The program above would display a form as below: By adding a number of labels on the form and positioning them appropriately we can start to build up a user interface.Advanced Programming A Graphical User Interface using System. title. Editing Text with a TextBox Component Displaying labels is all very well. I can create and use a TextBox in my program as follows: C# Programming © Rob Miles 2010 155 .ForeColor = Color.Add(title). This is a component just like a label. title. In short.Forms. The Windows Forms library provides a TextBox component which is used for this.Red. It provides a whole set of static colour values and also lets you create your own colours by setting the intensity of the red.BackColor = Color. The origin (i. green and blue components. I can then read the text property back when I want the updated value. } } The position on the screen is given in pixels (a pixel being an individual dot on the screen).Yellow. The user can then enter text into the textbox and modify it. This is because it is actually the same thing as every text field you've ever used.Text="Hello". Label title = new Label (). I can set the text property of the TextBox to the text I want to have edited.e.Drawing namespace. The Color class is found in the System. It lets the user type in huge amounts of text and scrolls the text around to make it fit in the box.0) is in the top left hand corner of the screen. title. title. using System.Windows. class FormsDemo { public static void Main () { Form f = new Form(). the pixel at 0. but it provides text edit behaviour. title. f.ShowDialog().Top=50.
but it is not bad for 25 or so lines of code. class FormsDemo { public static void Main() { Form f = new Form().Advanced Programming A Graphical User Interface using System. } } I've fiddled slightly with the position of the label and given it a more sensible name.Forms. nameLabel. I've also set the name text we are editing to be Rob. f.Add(nameTextBox). Now we are going to find out how to make one work. For that we need a button which we can press to cause an event. This will trigger my program to store the updated name and close the form down. TextBox nameTextBox = new TextBox(). nameLabel. f. You have pressed buttons like these thousands of times when you have used programs. nameTextBox. just to show how the components work.Text = "Rob". The Button Component What we want is a button that the user can press when they have finished editing the name.Left=100.Controls. nameTextBox.Text="Name". I can place it on the form and manage its position just like any other: C# Programming © Rob Miles 2010 156 . nameLabel. Label nameLabel = new Label().Add(nameLabel).Top=50.Controls.Windows.Top=50. A Button is just like any other component. using System. f. nameTextBox. But at the moment we have no way of signalling when the edit has been finished.Left=0. If you run this program you get a form as follows: This is not particularly flashy.ShowDialog(). It also lets you change the text in the name for whatever you want.Drawing.
2 Events and Delegates Events are things that happen.ShowDialog(). nameTextBox.Controls.Text="Finished". Rather than waiting for the user to do something our programs must respond when an event is generated. Label nameLabel = new Label().Drawing. nameTextBox. f. nameLabel. C# Programming © Rob Miles 2010 157 .Top=50. nameLabel. nameLabel. Up until now our programs have run from beginning to end. Nowadays program use is quite different. TextBox nameTextBox = new TextBox(). To get this to work we have to bind a method in our program to the event which is generated when the button is pressed. finishButton.Add(finishButton).Add(nameLabel).Top=80. 5.Forms.Left=0. f. duh).Controls. The windows forms system uses delegates to manage this. f.Add(nameTextBox). In the early days of computers this is how they were all used. } } This gives me a button on the form which I can press: However at the moment nothing happens when the button goes down.Controls.Left=100.Windows. Users expect to interact with items on a screen by pressing "buttons" and triggering different actions inside the program. finishButton.Advanced Programming A Graphical User Interface using System. f.Text = "Rob".Text="Name". When the program wants something from the user it waits patiently until that information is supplied (usually by means of a call of the ReadLine method). The upshot of this is that the programming language must provide some means by which events can be managed. nameTextBox. finishButton. At any given instant the program was either running through code or waiting for input. Button finishButton = new Button(). using System.Top=50. (well.Left=100. This means that the way our programs work has to change. class FormsDemo { public static void Main() { Form f = new Form().4.
to window closing. C# Programming © Rob Miles 2010 158 . nameLabel. f. nameTextBox. so we can use this class every time we need to create a delegate.Controls. We just need to create an instance of this class to get a delegate to give to the button. So. The signature of the method that is called when the event occurs is the same for every kind of event.Add(nameLabel). when the user clicks on the button on our form this is registered by the Windows operating system and then passed into the form as an event. class FormsDemo { public static void Main() { Form f = new Form().Controls. store it if it was OK and then close down the edit form.Windows.Text="Finished". Label nameLabel = new Label(). The form decides which of the components on the form should be given the event and calls a method in that component to tell it "you've been pressed". from mouse movement. nameLabel. In this respect you can regard an event and a message as the same thing. finishButton. Button Events To get back to the problem we are solving. This method would validate the new name. finishButton.Text="Name". to button press.Top=50. The button keeps a list of people to tell about events.Forms.Add(nameTextBox). to get a button to run a method of ours we need to create a delegate object and then pass that to the button so that it knows to use it when the event occurs.Drawing. TextBox nameTextBox = new TextBox(). using System. finishButton.Text = "Rob".Left=100. f.ShowDialog(). In the case of our button. nameTextBox.Click += new EventHandler(finishButton_Click).Top=50. using System.Controls.Left=100.Advanced Programming A Graphical User Interface Events and method calls In C# an event is delivered to an object by means of a call to a method in that object. We pass the button a reference to this delegate and it can then call the method it represents when the button is pressed. finishButton.Left=0.Top=80. nameTextBox. the delegate is going to represent the method that we want to have called when the button is pressed. nameLabel. A delegate is an object which can be used to represent a particular method in an instance of a class. The list is actually a list of delegates. The actual code to create a delegate and assign it to a method is as follows: using System. Then it looks for people to tell about the event. f. From the point of view of our name editing form we would like to have a particular method called when the "Finished" button is pressed by the user. f. The good news is that creating a delegate instance for a windows component is such a common task that the forms library has provided a delegate class which does this for us. The button then does its animation so that it moves in and out. Button finishButton = new Button().Add(finishButton).
If you remember our text editing code you will recall that we had an object which did the editing for us. Extending the Windows Form class It turns out that the best way to create a class to do this job is to extend the Form class to make a new form of our own. This is a standard technique for using windows components. Our form can then be regarded as a customised version of an empty form. However. C# Programming © Rob Miles 2010 159 . And the way that you create customised versions of classes is to extend them. 5. To make a proper account editor we need to create a class which will do this job for us. If you compile the above program and run it you will find that each time you press the Finish button the program prints out a message. sometimes. but it is not production code. EventArgs e) { Console.Advanced Programming A Graphical User Interface } private static void finishButton_Click( object sender. Note that we don’t actually have to use the parameters.3 An Account Edit Form My example code above is OK for showing how the forms work and components are added to them. } } The highlighted code is the bit that ties a delegate to the click event. we might want to use them to provide information such as the mouse coordinates.4. This is because I have made everything by hand and there is no edit object as such.WriteLine ("Finish Pressed"). The EventHandler delegate class is in the System namespace and can refer to methods which are void and accept two parameters. for example when we are capturing mouse movement events. Instead it prints out a message each time the button is pressed. In the code above I have an event handler method called finishButton_Click which accepts these parameters (but doesn't do anything with them). The idea is that when the form is created the constructor in the form makes all the components and adds them to the form in the appropriate places. This will be used in almost exactly the same way as the text editor. often our methods will ignore the values supplied. a reference to the object which caused the event and a reference to an EventArgs instance which contains details about the event which occurred. returning when the edit was complete. In the completed editor this method will finish the edit off for us. We passed it a reference to our account and it managed the edit process.
nameLabel. } } The form will be passed a reference to the account instance which is being edited.Controls.Form { private Label nameLabel.Text) . using System.finishButton.Forms.nameLabel = new Label(). this.account = inAccount.Text="Name". this.nameTextBox = new TextBox(). All the form components are created in the constructor for the form. If it is the name of the account class should be set and the form must then dispose of itself.Controls.account. } this.nameTextBox.Show(reply) .Text="Finished".finishButton.nameTextBox).Windows.GetName(). If the name is invalid it uses a static method in the windows forms system to pop up a message box and report an error: C# Programming © Rob Miles 2010 160 .Forms. public AccountEditForm (IAccount inAccount) { this. this. this.Advanced Programming A Graphical User Interface using System. this. return. if ( reply.Forms.Add(this.nameTextBox.finishButton).nameLabel.MessageBox.Top=50. This code is the windows equivalent of the AccountEditTextUI method that we created previously. It then gets the properties out of the form and displays them for editing.Top=50.Dispose().Windows.Left=100. this.account. this. this. private TextBox nameTextBox. private Button finishButton.EventArgs e) { string reply = account.Windows. } private void finishButton_Click(object sender.nameLabel). The finishButton_Click method gets the name out of the text box and validates it. this. this. this.Add(this.finishButton. IAccount account. this.Left=100.Top=80.Controls. public class AccountEditForm : System.EventHandler(finishButton_Click).Length > 0 ) { System.nameTextBox.SetName( nameTextBox. When the user presses the finish button the form must make sure that the name is valid. this.Text = this. this.Click += new System. this.finishButton = new Button(). System.Text).finishButton. this. this.Add(this.nameLabel.Left=0.ValidateName(nameTextBox.
C# Programming © Rob Miles 2010 161 . Never. Once we have disposed of a form we can never use it again. Using the Edit form To use the edit form we must first construct an account instance. Account a = new Account(). a.WriteLine ( "Name value : " + a.ShowDialog(). the fundamental principles that drive the forms it produces are exactly the same.SetName("Rob"). edit. All the components on the form are destroyed and the form is removed from the screen. it is important to remember that although it automates a lot of the actions that I have performed by hand above. These can then be shown to the customer (get them signed off even) to establish that you are doing the right thing. Visual Studio and Form Editing The Visual Studio application can take care of all the hard work of creating forms and adding components to them. I have had to spend more time re-working user interface code than just about any other part of the system. Console. In the code above the WriteLine is not performed until after the edit form has been closed. The design of this should start at the very beginning of the product and be refined as it goes. This means that while the form is on the screen the rest of the system is paused. Programmer’s Point: Customers really care about the user interface If there is one part of the system which the customer is guaranteed to have strong opinions about it is the user interface. If we just removed a reference to the form object it will still remain in memory until the garbage collector gets around to noticing it. We then pass a reference to the account into the constructor of an AccountEditForm. The Dispose method is important because we must explicitly say when we have finished with the instance. The good news is that with something like Visual Studio it is very easy to produce quite realistic looking prototypes of the front end of a system. AccountEditForm edit = new AccountEditForm (a). There are a number of different forms of this Show method which you can use to get different forms of message box and even add extra buttons to it. ever assume you know that the user interface should work in a particular way. However. Modal Editing The call of ShowDialog in the edit form is modal. Disposing of forms The Dispose method is used when we have finished with this form and we want it to get rid of it. It will also look after the creation of delegates for button actions.Advanced Programming A Graphical User Interface This is how we tell the user that the name is not correct. It then creates an edit form and uses that to edit the name value in the account. We will need to create a new form instead. This piece of test code creates an account and sets the name of the account holder to Rob.GetName()).
1 Type safe delegates The phrase type safe in this context means that if the method accepts two integer parameters and returns a string. for example we provided a custom WithdrawFunds for the BabyAccount class which only lets us draw out a limited amount of cash. Note that I've not created any delegates yet.. If you call the delegate it calls the method it presently refers to. 5. depending on the type of customer and the status of that customer. Delegates are useful because they let us manipulate references to methods. Using a Delegate As an example. I call a delegate ―A way of telling a piece of program what to do when something happens‖. Therefore you should read this text carefully and make sure you understand what is going on.5. A delegate is a "stand in" for a method. This means that you can call them in the wrong way and cause your program to explode. the delegate for that method will have exactly the same appearance and cannot be used in any other way. This word is used to distinguish a delegate from things like pointers which are used in more primitive languages like C. The bank will have a number of different methods which do this. These techniques are very useful. The way that C# does this is by allowing us to create instances of delegate classes which we give the event generators. Delegates are an important part of how events are managed in a C# program. A posh description would have the form: A delegate is a type safe reference to a method in a class.5 Using Delegates Events and delegates are a very important part of C#. I've just told the compiler what the delegate type CalculateFee looks like. Just remember that delegates are safe to use. This delegate can stand in for a method which accepts a single decimal parameter (the balance on the account) and returns a decimal value (the amount we are going to charge the customer). They include stuff like people pressing buttons in our user interface. It might want to have a way in which a program can choose which fee calculation method to use as it runs. In each case we need to tell the system what to do when the event occurs. consider the calculation of fees in our bank. Don’t worry about this too much. We have seen that things like overriding let us create methods which are specific to a particular type of object. This means I can use it as a kind of method selector. Events are things that happen which our program may need to respond to. In C you can create pointers to methods. A delegate type is created like this: public delegate decimal CalculateFee (decimal balance).Advanced Programming Using Delegates 5. but they are hard wired into the code that I write. Once I've compiled the class the methods in it cannot change. but the C environment does not know (or even care) what the methods really look like. An example of a method we might want to use with this delegate you could consider this one: C# Programming © Rob Miles 2010 162 . clocks going tick and messages arriving via the network.
Now when I "call" calc it will run the FriendlyFee method.Advanced Programming Threads and Threading public decimal RipoffFee (decimal balance) { if ( balance < 0 ) { return 100. it is best just to consider them in terms of how we use delegates to manage the response of a program to events. The calc delegate presently refers to a delegate instance which will use the RipoffFee method. where the speed of computer processors is going to be limited by irritating things like the speed of light and the size of atoms. I don’t use them much beyond this in programs that I write. If I want to use this in my program I can make an instance of CalculateFee which refers to it: CalculateFee calc = new CalculateFee (RipoffFee). so I can build structures which contain delegates and I can also pass delegates in and out of methods. If you are overdrawn the fee is 100 pounds.6 Threads and Threading If you want to call yourself a proper programmer you need to know something about threads. In the same way that you can put more than one train on a C# Programming © Rob Miles 2010 163 . You can regard a list of delegates as a list of methods that I can call. 5. Now I can "call" the delegate and it will actually run the ripoff calculator method: fees = calc(100). Programmer’s Point: Use Delegates Sensibly Allowing programs to change what they do as they run is a rather strange thing to want to do. 5. This gives us another layer of abstraction and means that we can now design programs which can have behaviours which change as the program runs. Delegates are used a lot in event handlers and also to manage threads (as you will see below). You can visualise a thread as a train running along a track. I can change that by making another delegate: calc = new CalculateFee (FriendlyFee). In the future. The track is the statements that the thread is executing. } } This is a rather evil fee calculator. I’m presenting this as an example of how delegates let a program manipulate method references as objects. An instance of a delegate is an object like any other.6. They can make programs much easier to create.1 What is a thread? At the moment our programs are only using a single thread when they run. For now however. but they can also be the source of really nasty bugs. they are the way that we will be able to keep on improving the performance of our computer systems. If you are in credit the fee is 1 pound. This of course only works if FriendlyFee is a method which returns a value of type decimal and accepts a single decimal value as a parameter. rather than as a good way to write programs. This means that it can be managed in terms of references. The thread usually starts in the Main method and finishes when the end of this method is reached. } else { return 1.
rather than try interleaving the second task with the first. it makes sense to share this ability amongst several tasks. This is how your program can be active at the same time as other programs you may wish to use alongside it. count < 1000000000000L. Threads provide another level of ―abstraction‖. giving each thread the chance to run for a limited time before moving on to run another.2 Why do we have threads? Threads make it possible for your computer to do something useful while one program is held up. 5. The second way to support multiple threads is to actually have more than one processor. If we wrote a word processor we might find it useful to create threads to perform time consuming tasks like printing or spell checking. You have seen that a ―click‖ event from a Button component can be made to run an event handler method. I’m going to give some tips on how to make sure that your programs don’t fall foul of threading related bugs. in that if we wish to do more than one thing at the same time it is very useful just to send a thread off to perform the task. These could be performed ―in the background‖ while the user continues to work on the document. A computer can support multiple threads in two ways. The programs that you have been writing and running have all executed as threads in your computer. programs that use threads can also fail in spectacular and confusing ways. The first computers had only one processor and so were forced to use ―time slicing‖ to support multiple threads. waiting for its turn to run. It is possible for systems to fail only when a certain sequence of events causes two previously well behaved threads to “fight” over a shared item of data. 5. Newer machines now have ―dual core‖ or even ―quad core‖ processors which can actually run multiple threads simultaneously.6. but in reality a thread may only be active for a small fraction of a second every now and then. The Windows system actually creates a new thread of execution which runs the event handler code.3 Threads and Processors Consider the following method: static private void busyLoop() { long count. count = count+1) { } } C# Programming © Rob Miles 2010 164 . A modern computer can perform many millions of instructions per second. a computer can run more than one thread in a single block of program code. The first is by rapidly switching between active threads. Bugs caused by threading are amongst the hardest ones to track down and fix because you have to make the problem happen before you can fix it. When a thread is not running it is held in a ―frozen‖ state.Advanced Programming Threads and Threading single track. You have not been aware of this because the operating system (usually Windows) does a very good job of sharing out the processing power. Programmer’s Point: Threads can be dangerous In the same way that letting two trains share the same railway track can sometimes lead to problems. Threads are also how Windows forms respond to events. and the circumstances that cause the fault may only occur every now and then.6. for (count = 0. As far as the thread is concerned it is running continuously. Your system can play music and download files while your program waits for you to press the next key. and I suggest that you follow these carefully.
If I stop my program running I get a display like the one below. From the look of the above graph.Threading. Programmer’s Point: Multiple Threads Can Improve Performance If you can work out how to spread your program over several threads this can make a big difference to the speed it runs at. When we start using more than one thread we should see more of the graphs climbing up. One job of the operating system is to manage threads on your computer and decide C# Programming © Rob Miles 2010 165 . We have used namespaces to locate resources before when we used files. You can see little graphs under the CPU (Central Processor Unit) Usage History part of the display showing how busy each processor is. The Thread class provides a link between your program and the operating system.4 Running a Thread An individual thread is managed by your program as an instance of the Thread class. which means that it can run four threads at a time. the leftmost processor and the rightmost processor are quite busy but the middle two processors are not doing anything. If I run a program that calls this method the first thing that happens is that the program seems to stop.Advanced Programming Threads and Threading This method does nothing. Now all the processors are just ticking over. This class lives in the System namespace. but it does do it many millions of times. 5. The method above can only ever use a maximum of 25% of my system. The easiest way to make sure that we can use all the threading resources is to add a using directive at the start of our program: using System. since it only runs on one of the four available processors. Then the fan in my laptop comes on as the processor starts to heat up as it is now working hard. as my programs run on multiple processors.6. If I start up Windows Task Manager I see the picture below: My laptop has four processor cores.
class ThreadDemo { static private void busyLoop() { long count. The delegate type used by threads is the ThreadStart type. Creating a Thread Once you have your start point defined you can now create a Thread value: Thread t1 = new Thread(busyLoopMethod).Advanced Programming Threads and Threading exactly when each should get to run. If you take a look at the busyLoop method above you will find that this method fits the bill perfectly. Starting a Thread The Thread class provides a number of methods that your program can use to control what it does. Thread t1 = new Thread(busyLoopMethod). busyLoop(). You do this by using delegates. When we start running t1 it will follow the delegate busyLoopMethod and make a call to the busyloop method. it is waiting to be started.Start(). This delegate type can refer to a method that does not return a value or accept any parameters. By calling methods provided by the Thread class you can start and stop them.Start(). Selecting where a Thread starts running When you create a thread you need to tell the thread where to start running. To start the thread running you can use the Start method: t1. count = count+1) { } } static void Main() { ThreadStart busyLoopMethod = new ThreadStart(busyLoop). A delegate is a way of referring to a method in a class. This is like telling your younger brother where on the track you’d like him to place your train. Note that at the moment the thread is not running. It also calls busyLoop directly from the Main method. t1. } } The above code creates a thread called t1 and starts it running the busyLoop method. You can create a ThreadStart delegate to refer to this method as follows: ThreadStart busyLoopMethod = new ThreadStart(busyLoop). This changes the Task Manager display: C# Programming © Rob Miles 2010 166 . This means that there are two processes active. count < 1000000000000L. for (count = 0. The variable t1 now refers to a thread instance. This is the point at which the thread begins to run.
Advanced Programming Threads and Threading Now more of the usage graphs are showing activity and the CPU usage is up from 25% to 50% as our program is now using more processors. all running the busyLoop method. In fact. Fortunately Windows boosts the priority of threads that deal with user input so you can usually get control and stop such wayward behaviour. i < 100. Now our computer is really busy: All the processors are now maxed out. If you run too many threads at once you will slow everything down. This makes your computer unusable by starting a huge number of threads which tie up the processor. i = i + 1) { Thread t1 = new Thread(busyLoopMethod). Programmer’s Point: Two Many Threads Will Slow Everything Down Note that nothing has stopped your program from starting a large number of threads running. This is potentially dangerous.Start(). } This loop will create 100 threads. t1. and that all the cooling fans come on full blast. C# Programming © Rob Miles 2010 167 . called a Denial of Service attack. Making lots of Threads From the displays above you can see that if we create an additional thread we can use more of the power the computer gives us. we can create many more threads than this: for (int i = 0. and the CPU usage is up to 100%. If you run this code you might actually find that the machine becomes slightly less responsive. This is actually the basis of a type of attack on your computer.
If you are still thinking about threads as trains. Thread 1 fetches the value of the count variable so that it can add 1 to it. This is because the variable is local to the busyLoop method: static private void busyLoop() { long count. count = count+1) { } } The count variable is declared within the body of the method. When they entered the single track they were given the token. Thread 1 is stopped and Thread 20 is allowed to run. Because of the way that Thread 1 was interrupted during its calculation. count < 1000000000000L. Both are dangerous. When the train left single track section the track the driver handed the token back. Before the addition can be performed. 4. it has overwritten the changes that Thread 20 made. but now every thread running busyLoop is now sharing the same count variable. 2. Using Mutual Exclusion to Manage Data Sharing Allowing two threads to share the same variable is a bit like allowing two trains to share the same piece of track. It is now very hard to predict how long this multi-threaded program will take to finish. What we need is a way of stopping the threads from interrupting each other. We could make a tiny change to this code and make the count variable a member of the class: static long count. Mutual exclusion works in just the same way by using an instance of an object to play the role of the token. Consider the following sequence of actions: 1. must be allowed to complete without being interrupted. We can return to our train analogy here.5 Threads and Synchronisation You might be wondering why all the threads don’t fight over the value of count that is being used as the loop counter. This means that each method has its own copy of this local variable. adds 1 to the value it fetched before it was stopped and stores the result back in memory. it is as if the data for each thread is held in trucks that are pulled along behind the train. Anyone wanting to enter the track had to wait for their turn with the token. The statement count = count + 1. 3. static object sync = new object(). count < 1000000000000L. This is potentially disastrous.6. Thread 20 fetches the value of count. incrementing and storing the value of count and overwriting changes that they have made. As the threads run they are all loading. count = count + 1) { } } The method looks very similar. Sometime later Thread 1 gets control again. static private void busyLoop() { for (count = 0.Advanced Programming Threads and Threading 5. adds one to it and stores it back in memory. The single track problem was solved by using a single brass token which was held by the engine driver. for (count = 0. You can do this by using a feature called mutual exclusion or mutex. C# Programming © Rob Miles 2010 168 .
Advanced Programming Threads and Threading This object doesn’t actually hold any data.Join(). It is just used as the token which is held by the active process. Monitor. These let you pause threads. This is a really good way to make your programs fail. wait for a thread to finish. this will stop other threads from running if they need that object. Another one.6. perhaps to allow the user to read the output or to wait a little while for something to happen you should use the Sleep method which is provided by the Thread class: Thread. In our examples above. Joining Threads You might want to make one thread wait for another to finish working. This queue is held in order. In other words. called the “Deadly Embrace” is where thread a has got object x and is waiting for object y. Thread Control The Thread class provides a set of methods that you can use to control the execution of a thread. Monitor. The above call would pause a program for half a second. 5. This is the computer version of “I’m not calling him to apologise. we don’t need to know how it works. You can abort a thread by calling its Abort method: t1. I’m going to wait for him to call me”. This will certainly pause your program. there is no chance of Windows interrupting the increment statement and switching to another process.6 Thread Control There are a number of additional features available for thread management. A thread instance provides a Join method that can be called to wait for another thread to complete operation.Exit(sync).Enter(sync).Abort(). each thread will end when the call of busyloop finishes. Once execution leaves the statements between the Monitor calls the thread can be suspended as usual. This method is given the number of milliseconds (thousandth’s of a second) that the execution is to pause. The code between the Monitor. one way to ―pause‖ a thread is to create a loop with an enormous limit value. If you just want your program to pause. Threads that aren’t able to run are ―parked‖ in a queue of waiting threads. Programmer’s Point: Threads can Totally Break your Program If a thread grabs hold of a synchronisation object and doesn’t let go of it. This would cause the executing thread to wait until the thread t1 finishes. and thread b has got object y and is waiting for object x. with the other threads lining up for their turn. C# Programming © Rob Miles 2010 169 . count = count + 1. Pausing Threads As you can see above. The Monitor class looks after all this for us. A thread finishes when it exits the method that was called when it started.Sleep(500).Enter and Monitor.Exit calls can only be performed by one thread at a time. but at the expense of any other threads that want to run. This asks the operating system to destroy that thread and remove it from memory. see if a thread is still active and suspend and remove threads. so the first thread to get to the entry point will be the first to get the token. All the increment operations will complete in their entirety. t1.
Often the only way to investigate the problem is to add lots of write statements so that the program makes a log that you can examine after it has failed. Up until now our programs have been single threaded and we have been able to put in the data which causes the problem. threads can also be a great source of frustration.WaitSleepJoin the thread is running the thread has finished executing the thread method the thread has been suspended the thread is executing a Sleep. The most useful are: ThreadState.6. This is mostly because we have done something wrong.Advanced Programming Threads and Threading If you don’t want to destroy a thread. If variables sometimes get ―out of step‖ then this is a sure sign that you have several threads fighting over data items.999% of the time may fail spectacularly. This makes the code easier to manage and also means that your program can make the best use of the processing power available.Running ) { Console. This will stop inadvertent data corruption. The thread is put to sleep until you call the Resume method on that thread. They let your program deal with tasks by firing off threads of execution.WriteLine("Thread Running"). for example a web server. to display a message if thread t1 is running: if ( t1. waiting to join with another thread or waiting for a Monitor As an example. Synchronisation problems like the ―Deadly Embrace‖ described above may only appear when two users both request a particular feature at exactly the same time. Finding the state of a thread You can find out the state of a thread by using its ThreadState property. Of course.Stopped ThreadState. you can call the Suspend method on the thread: t1. } 5. This will cause the program to fail. at which point we can begin to fix it. vanish completely.ThreadState == ThreadState. or just lock up completely. when a specific set of timing related events occur. We know that our programs sometimes produce errors when they run. A program which works fine for 99. but simply make it pause for a while. When you have problems with a multi-threaded system the biggest difficultly is always making the fault occur so you can fix it.Resume().Running ThreadState. However. is to create a multi-threaded application which starts up a thread to deal with each incoming request. if you are very lucky. You should protect any variables shared between threads by using the Monitor class as described above. If consumers are always waiting for producers C# Programming © Rob Miles 2010 170 .Suspend ThreadState. You should try to avoid any ―Deadly Embrace‖ situations by making your threads either producers or consumers of data. When we get a problem we look at what has happened and then work out what the fault is.Suspend().7 Staying Sane with Threads Threads are very useful. Unfortunately when you add multi-threading to a solution this is no longer true. This is an enumerated value which has a number of possible values. time spent writing the log output affects the timing of events in the program and can often cause a fault to move or. The best way to create a system that must support many users. t1.
You can also create Process instances that you can control from within your program in a similar manner to threads.8 Threads and Processes You can regard different threads as all living in the in computer together in the same way that a number of trains can share a particular railway. or a Parse method is given an invalid string.7 Structured Error Handling By now I hope that you are starting to think very hard about how programs fail. To start a program on your system you can use the Start method on the Process class: Process. The key to achieving this is to think about making your own custom exceptions for your system.Diagnostics.exe"). You can also use the Process class to start programs for you.Diagnostics namespace. the system will throw an exception to indicate that it is unhappy. so you can add a Using statement to make it easier to get hold of the class: using System. Your word processor may fire off several threads that run within it (perhaps one to perform spell checking).6. 5. in that each process has its own memory space which is isolated from other processes. This means that potentially badly behaved code like this has to be enclosed in a try – catch construction so that our program can respond sensibly. This class is held in the System. 5. Programmer’s Point: Put Threads into your Design I think what I am really saying here is that any thread use should be designed into your program. When something bad happens the program must deal with this in a managed way. In programming terms this is a move from threads to processes.. and not tacked on afterwards. This is actually a very important part of the design process.Advanced Programming Structured Error Handling (and producers never wait for consumers) then you can be sure that you never get the situation where one thread waits for a thread that is waiting for it. The Start method is supplied with the name of the program that you want to start. but nothing in the word processor program can ever directly access the variables in the browser. If you want to use threads the way that they are managed and how they communicate should be decided right at the start of your design and your whole system should be constructed with them in mind. Now we are going to take a closer look at exceptions and see about creating our own exception types.Start("Notepad. Processes are different from threads. In a C# program you can create a process and start it in a similar way to starting a thread. The above line of C# would start the Notepad program. When you are using a word processor and a web browser at the same time on your computer each of them is running on your computer as a different process. We have been on the receiving end of exceptions already. We have seen that if something bad happens whilst a file is being read. You should also be thinking that when you build a system you should consider how you are going to manage the way that it will fail. C# Programming © Rob Miles 2010 171 . The next step up is to have more than one railway.
3 Throwing an Exception The throw keyword throws an exception at that point in the code. in that the specification will give you information about how things can fail and the way that the errors are produced. You can generate System.Length == 0 ) { throw new BankException( "Invalid Name" ). If I want to use this with my bank exception I have to sort out the constructor chaining for my exception class and write code as follows: public class BankException : System. However.Exception when something goes wrong. I can catch the exception myself as follows: C# Programming © Rob Miles 2010 172 . At this point the execution would transfer to the ―nearest‖ catch construction. 5.7.Exception class: public class BankException : System. I can do this with the code: if ( inName.Advanced Programming Structured Error Handling 5. can just use this to make an Exception instance. If you want your code to be able to explicitly handle your errors the best way forward is to create one or more of your own exceptions.Exception { public BankException (string message) : base (message) { } } This makes use of the base keyword to call the constructor of the parent class and pass it the string message. For example. This can be picked up and used to discover what has gone wrong. or it might be one supplied by the system. To create a standard exception with a message I pass the constructor a string. In the code above I make a new instance of the bank exception and then throw that.7. along with everything else in your system. However. } The throw keyword is followed by a reference to the exception to be thrown. This all (of course) leads back to the metadata which you have gathered. This means that. I might want to throw an exception if the name of my account holder is an empty string.1 The Exception class The C# System namespace holds a large number of different exceptions. but they are all based on the parent Exception class. The thing that is thrown must be based on the System.2 Creating your own exception type Creating your exception type is very easy. This might be a catch of mine.Exception class has a default constructor which takes no parameters. you will need to design how your program will handle and generate errors. but this means that exceptions produced by your code will get mixed up with those produced by other parts of the system. It can be done by simply extending the System.7.Exception class. there is a version of the Exception constructor which lets us add a message to the exception. The default constructor in BankException (which is added automatically by the compiler). 5.Exception { } This works because the System. If you want to throw your own exceptions you are strongly advised to create your own exception type which extends the system one. If the exception is caught by the system it means that my program will be terminated.
This means that if I try to create an account with an empty name the exception will be thrown.WriteLine( "Error : " + exception. i. and the catch will be matched up to the type of exception that was thrown: public class BankExceptionBadName : System. Errors should be numbered. This helps a great deal in working with different languages. It can contain a text message which you can display to explain the problem to the user.e. We can have many catch constructions if we like. If doing this causes an exception to be thrown. the catch invoked. try { a = new Account(newName. } catch (BankException exception) { Console.Exception { public BankExceptionBadName (string message) : base (message) { } } public class BankExceptionBadAddress : System. The reference exception is set to refer to the exception which has been thrown. 5.4 Multiple Exception Types It is worth spending time thinking about how the exceptions and errors in your system are to be managed. and the message printed. Note that. you need to design in your handling of errors.Exception { public BankExceptionBadAddress (string message) : base (message) { } } Now I can use different catches. newAddress). Programmer’s Point: Design your error exceptions yourself An exception is an object which describes how things have gone wrong. depending on how the code fails: C# Programming © Rob Miles 2010 173 . However. The Message member of an exception is the text which was given. you should seriously consider extending the exception class to make error exceptions of your own which are even more informative. the code in the exception handler is obeyed. If the customer can say “Error number 25” when they are reporting a problem it makes it much easier for the support person to respond sensibly.Advanced Programming Structured Error Handling Account a.Message). } The code tries to create a new account.7. as with just about everything else. your exceptions should be tagged with an error number.
since the code doesn’t get exercised as much as the rest of the system. The two problems are distinct and separate and C# provides mechanisms for both.WriteLine("Invalid name : " + nameException. When you create the system you decide how many and what kind of errors you are going to have to manage. error handlers are rather hard to test.1 Using Separate Source Files In a large system a programmer will want to spread the program over several different source files.8. } catch (BankExceptionBadAddress addrException) { Console. This means that errors are more likely to get left in the error handlers themselves. } catch (System. it is worth the effort! Error handling should be something you design in.WriteLine("System exception : " + exception.Advanced Programming Program Organisation Account a.8 Program Organisation At the moment we have put the entire program source that we have created into a single file. and most of the time you will be using test data which assumes everything is OK. which we compile and run. This will be called if the exception is not a name or an address one.WriteLine("Invalid address : " + addrException. At the very end of the list of handlers I have one which catches the system exception.Message). try { a = new Account("Rob". in that the error handler is supposed to put things right and if it fails it will usually make a bad situation much worse. Programmer’s Point: Programs often fail in the error handlers If you think about it. 5. 5. When you design your solution to a problem you need to decide where all the files live. They only get run when something bad happens. } catch (BankExceptionBadName nameException) { Console. This is especially important when you consider that a given project may have many people working on it. Of course this is a recipe for really big disasters. This might mean that you have to create special test versions of the system to force errors into the code.Message). As a professional programmer you must make sure that your error handling code is tested at least as hard as the rest of the system. ""). C# Programming © Rob Miles 2010 174 . but now we are starting to write much larger programs and we need a better way to organise things. To do this we have to solve two problems: how we physically spread the code that we write around a number of files how we logically identify the items in our program. } Each of the catches matches a different type of exception.Exception exception ) { Console. In this section we are going to see how a large program can be broken down into a number of different chunks. This is fine for teeny tiny projects.Message). Believe me.
exe' does not have an entrypoint defined The compiler is expecting to produce an executable program. These have an entry point in the form of the Main method. If I look at what has been created I find that the compiler has not made me an executable. Options are a way of modifying what a command does. The compiler can tell that it is being given an option because options always start with a slash character: csc /target:library AccountManagement. Generally speaking your classes will be public if you want them to be used in libraries.cs The compiler will not now look for a Main method. instead it has made me a library file: C# Programming © Rob Miles 2010 175 . Our bank account class does not have a main method because the program will never start by actually running an account. } } } This is a fairly well behaved class in that it won't let us withdraw more money than we have in the account. we might want to create lots of other classes which will deal with bank accounts. the compiler cannot make an executable file. Note that I have made the Account class public. } public bool WithDrawFunds ( decimal amount ) { if ( amount < 0 ) { return false . public void PayInFunds ( decimal amount ) { balance = balance + amount. So. The class will be called Account. } if ( balance >= amount ) { balance = balance . since it does not know where the program should start. Consider a really simple Account class: public class Account { private decimal balance = 0. This is so that classes in other files can make use of it. So instead I have decided to put the class into a file called "AccountManagement. We could put it into a file called "Account. You can apply the protection levels to classes in the same way that you can protect class members.Advanced Programming Program Organisation In our bank management program we have identified a need for a class to keep track of a particular account. Creating a Library I solve this problem by asking the compiler to produce a library instead.cs" if we wanted to. Instead other programs will run and create accounts when they need them.As I add more account management The problem is that the compiler now gets upset when I try to compile the file: error CS5001: AccountManagement. because it has been told to produce a library rather than a program. I use the target option to the compile command. } public decimal GetBalance () { return balance. return true. } else { return false .amount .cs". However.
not when it is built.PayInFunds (50).cs(5.cs. Library References at Runtime We have now made two files which contain program code: AccountManagement. which causes further errors. puts 50 pounds in it and then prints out the balance. It means that library is only loaded when the program runs. If I try to compile it I get a whole bunch of errors: AccountTest. Firstly I'm going to create another source file called AccountTest.cs The reference option is followed by a list of library files which are to be used.cs(7. This because of the "dynamic" in dynamic link library. and so it can build the executable program. In this case there is just the one file to look at.GetBalance()).WriteLine ("Balance:" + test.cs to find the Account class.37): error CS0246: The type or namespace name 'test' could not be found (are you missing a using directive or an assembly reference?) The problem is that the compiler does not know to go and look in the file AccountManagement. which is the library that contains the required class.dll The language extension dll stands for dynamic link library.dll AccountTest. class AccountTest { public static void Main () { Account test = new Account(). test. This contains a Main method which will use the Account class: using System.Advanced Programming Program Organisation AccountManagement. Using a Library Now I have a library I next have to work out how to use it.dll file and then run the program this causes all kinds of nasty things to happen: C# Programming © Rob Miles 2010 176 . This means that the content of this file will be loaded dynamically as the program runs. Console. This means that it fails to create test.3): error CS0246: The type or namespace name 'test' could not be found (are you missing a using directive or an assembly reference?) AccountTest.cs(6. } } This makes a new account. Deleting System Components This means that if I do something horrid like delete the Acccountmanagement.exe the library containing the Account class code the executable program that creates an Account instance Both these files need to be present for the program to work correctly.3): error CS0246: The type or namespace name 'Account' could not be found (are you missing a using directive or an assembly reference?) AccountTest. To solve the problem I need to tell the compiler to refer to AccountManagement to find the Account class: csc /reference:AccountManagement. The compiler now knows where to find all the parts of the application.dll AccountTest.
If you are not sure what I mean by this. Or both. There is a special phrase. It may well wish to keep track of these accounts using a computer system. and then make sure you use it. Perhaps the programmers might decide that a sensible name for such a thing would be Account. But this would be messy. was not found. The bad news is that you have to plan how to use this technology. If I modify the AccountManagement class and re-compile it. or one of its dependencies. Which would be bad. File name: "AccountManagement" at AccountTest. The good news is that there are ways of making sure that certain versions of your program only work with particular program files. We don't just want to break things into physical chunks. Of course this only works as long as I don't change the appearance of the classes or methods which AccountTest uses. Windows itself works in this way.8. If this sounds boring and pedantic then I'm very sorry.IO.Main() … lots of other stuff This means that we need to be careful when we send out a program and make sure that all the components files are present when the program runs. A far better way would be to say that we have a CustomerBanking namespace in which the word Account has a particular meaning. If the two systems ever meet up we can expect a digital fight to the death about what "Account" really means. The good news is that I can fix the broken parts of the program without sending out an entire new version. 5. We can also have an C# Programming © Rob Miles 2010 177 . "dll hell". The bad news is that this hardly ever works. But if you consider the whole of the bank operations you find that the word "account" crops up all over the place. Unless the fixed code is exactly right there is a good chance that it might break some other part of the program. When you think about selling your application for money you must make sure that you have a managed approach to how you are going to send out upgrades and fixes. We also want to use logical ones as well. reserved for what happens. But we also have another problem. The bank will buy things like paper clips. little pens on chains (pre-supplied with no ink in of course) and the like from suppliers.FileNotFoundException: File or assembly name AccountManagement. but if you don't do this you will either go mad or bankrupt. Updating System Components Creating a system out of a number of executable components has the advantage that we can update part of it without affecting everything else. We have decided that Account is a sensible name for the class which holds all the details of a customer account. rubber stamps. We could solve the problem by renaming our account class CustomerBankAccount. and the number of times that I've installed a new program (or worse yet an upgrade of an existing one) which has broken another program on the computer is too numerous to happily remember. You could say that the bank has an account with such a supplier. the new version is picked up by AccountTest automatically.2 Namespaces We can use library files to break up our solution into a number of files. And here we are again. consider the situation in our bank. and mean that at design time we have to make sure that we name all our classes in a way which will always be unique.Advanced Programming Program Organisation Unhandled Exception: System. Programmer’s Point: Use Version Control and Change Management So many things end up being rooted in a need for good planning and management. Arrgh! We are now heading for real problems. This makes management of the solution slightly easier.
If I want to use the Account class from the CustomerBanking namespace I have to modify my test class accordingly. CustomerBanking. A given source file can contain as many namespace definitions and each can contain as many classes as you like. A name like this. one created outside any namespace) can just be referred to by its name.Account(). is known as a fully qualified name. Putting a Class in a Namespace Up until now every name we have used has been created in what is called the global namespace. If we want to create an instance of the class we use the fully qualified name again: test = new CustomerBanking. This prevents the two names from clashing. they are very easy to set up: namespace CustomerBanking { public class Account { private decimal balance = 0. This creates a variable which can refer to instances of the Account class. This is because we have not explicitly set up a namespace in our source files. } } } } I have used the namespace keyword to identify the namespace. in that they are not defined in the same namespace. This is followed by a block of classes. in this case CustomerBanking. C# Programming © Rob Miles 2010 178 . } if ( balance >= amount ) { balance = balance . } public bool WithDrawFunds ( decimal amount ) { if ( amount < 0 ) { return false . However. The Account class we use is the one in the CustomerBanking namespace. } else { return false . public void PayInFunds ( decimal amount ) { balance = balance + amount. Every class declared in this block is regarded as part of the given namespace.Account test. return true. Using a Class from a Namespace A Global class (i.e. If you want to use a class from a namespace you have to give the namespace as well. } public decimal GetBalance () { return balance.amount . with the namespace in front.Advanced Programming Program Organisation EquipmentSupplier namespace as well.
You get to use the items in the System. This means that the programmer can just write: Console. it is common for most programs to have the line: using System. If it finds one. Nesting Namespaces You can put one namespace inside another. Of course the namespaces that you use should always be carefully designed.8. You have to make sure that the files you want to use contain all the bits are needed. When the compiler sees a line like: Account RobsAccount. 5. Console then all is well and it uses that. If it finds two Console items (if I was an idiot I could put a Console class in my CustomerBanking namespace I suppose) it will complain that it doesn't know which to use. This allows you to break things down into smaller chunks.IO . and only one.RudeLetters .3 Namespaces in Separate Files There is no rule that says you have to put all the classes from a particular namespace in a particular file. I'll go and have a look for a thing called Console in all the namespaces that I've been told to use".at the very top. It is perfectly OK to spread the classes around a number of different source files. We can use these by means of fully qualified names: System. . However. We do this with the using keyword: using CustomerBanking . We have already used this technique a lot.WriteLine ( "Hello World" ). The compiler goes "ah. you'd probably figured that one out already.WriteLine ( "Hello World" ). . If there is it uses that.it automatically looks in the CustomerBanking namespace to see if there is a class called Account. The System namespace is where a lot of the library components are located.Advanced Programming Program Organisation Using a namespace If you are using a lot of things from a particular namespace C# provides a way in which you can tell the compiler to look in that namespace whenever it has to resolve the name of a particular item. and this means of course more planning and organising.Console. In terms of declaring the namespace you do it like this: namespace CustomerBanking { namespace Accounts { // account classes go here } namespace Statements { // statement classes go here } namespace RudeLetters { // rude letter classes go here } } Now I can use the classes as required: using CustomerBanking. The System namespace is like this. C# Programming © Rob Miles 2010 179 . there is a namespace which is part of the System namespace which is specifically concerned with Input/Output.IO namespace with an appropriate include: using System. But then again.
and we are going to explore some of these here. C# Programming © Rob Miles 2010 180 . Not everyone is good at debugging. you will not be supplied with a sequence of steps which cause the fault to appear. Having said that there are techniques which you can use to ease the process. This is not however how must bugs are caused. Programmer’s Point: Design Your Fault Reporting Process Like just about everything else I've ever mentioned. You can spell out the complete location by using a Fully Qualified Name (CustomerBanking.9 Debugging Some people are born to debug. However. this approach will not make you popular with users. debugging is working very hard to find out how stupid you were in the first place. causing it to fail. but it means that when I'm reading the code I can see exactly where a given resource has come from. 5. It is important to stress to users that any fault report will only be taken seriously if it is well documented. the way in which you manage your fault reports should be considered at the start of the project. Faults which always happen are easy. the steps taken to manifest it will be well recorded. but there will still be some things that need to be fixed. I know that this makes the programs slightly harder to write.OverdraftWarning) or you can get hold a items in a namespace with using. if a user reports a fault the evidence may well be anecdotal. The good news is that if you use a test driven approach to your development the number of faults that are found by the users should be as small as possible.9. The number of faults that are reported. the reason why problems with programs are called bugs is that the original one was caused by an actual insect which got stuck in some contacts in the computer. However. you should set up a process to deal with faults that are reported. Of the two I much prefer the fully qualified name. if you formalize (or perhaps even automate) the fault reporting process you can ensure that you get the maximum possible information about the problem. If I just see the name OverdraftWarning in the code I have no idea where that came from and so I have to search through all the namespaces that I'm using to find it. you can perform the sequence which always causes the bug to manifest itself and then use suitable techniques to nail it (see later). assigned to programmers and tracked very carefully. In a large scale development fault reports are managed.1 Fault Reporting We have already seen that a fault is something which the user sees as a result of an error in your program.RudeLetters. The two types of Fault Faults split into two kinds. those which always happen and those which sometimes happen. is valuable information about the quality of the thing that you are making.e. 5. If a program fails as part of a test. Incidentally. I've been programming for many years and only seen this in a handful of occasions.Advanced Programming Debugging Programmer’s Point: Fully Qualified Names are Good There are two ways you can get hold of something. The sad thing is that most of the bugs in programs have been put there by programmers. some will always be better than others. It is very rarely that you will see your program fail because the hardware is faulty. you will simply be told "There's a bug in the print routine". There is a strong argument for ignoring a fault report if you have not been given a sequence of steps to follow to make it happen. and the time taken to deal with them. Faults are uncovered by the testing process or by users. In other words. i. Also. In other words.
Look for: use of un-initialised members of classes typographical errors (look for incorrectly spelt variable names. Here are some tips: Don't make any assumptions. improperly terminated comments) logical errors (look for faults in the sequence of instructions. Look at all possible (if seemingly unrelated) factors in the manifestation of the bug. Surprisingly. Rather than make assumptions. invalid loop termination's. A fault may change or disappear when the program itself is changed. You might track this down to the number of pages printed. for example a program may fail when an item is removed from a database. or the amount of text on the page. or the size of the document which is being edited when the print is requested. incorrect comparison operators. This can lead to the most annoying kind of fault. They usually point to: a state which is not catered for (make sure that all selection statements have a default handler which does something sensible and that you use defensive programming techniques when values are passed between modules) programs that get stuck into loops. or the loading department turn on the big hoist and inject loads of noise into the mains. This does not mean that there is no sequence (unless you are suffering from a hardware induced transient of some kind – which is rather rare) but that you have not found the sequence yet. errors which overwrite memory will corrupt different parts of the program if the layout of the code changes. If the fault changes in nature this indicates problems with program or data being corrupted. An example would be a print function which sometimes crashes and works at other times. If you assume that "the only way it could get here is through this sequence" or "there is no way that this piece of code could be obeyed" you will often be wrong. where the program crashes (i. and the problem promptly disappears! If you suspect such an error. some folks are just plain good at finding bugs. wrongly constructed logical conditions) As I said above. Explain the problem to someone else .e.2 Bugswatting You can split faults into other categories. do – while constructions which never fail. find out if another department uses the machine to do a payroll run at that time and fills up all the scratch space. 5. for loops which contain code which changes the control variable. If the bug appears on Friday afternoons on your UNIX system.Advanced Programming Debugging Faults which sometimes happen are a pain. The manifestation of a fault may be after the error itself has actually occurred. C# Programming © Rob Miles 2010 181 . crashes are often easier to fix. where you put in extra print statements to find out more about the problem. add extra code to prove that what you think is happening is really happening. this can be harder to find. What this means is that you do not have a definite sequence of events which causes the system to fail. your first test is to change the code and data layout in some way and then re-run the program. methods that call themselves by mistake and recurse their way into stack overflow an exception that is not caught properly If your program does the wrong thing.9. or in code which overwrote the memory where the database lives. but the error may be in the routine which stored the item.even if it is just the cat! The act of explaining the problem can often lead you to deduce the answer. stops completely) or when it does the wrong thing. This is particularly important if the bug is intermittent. It is best if the person you are talking to is highly sceptical of your statements.
A stopper is a fault which makes the program un-saleable. Rip it up and start again In some projects it is possible that the effort involved in starting again is less than trying to find out what is wrong with a broken solution that you have created. in that it can tell you exactly what changes have been made from one version to the next. outputs and some behaviours. explained the code to a friend and checked all your assumptions then maybe. This does not mean that every program that I write is useless. Alternatively you may find the answer as soon as you come back to the problem. Part of the job of a project manager in a development is deciding when a product is good enough to sell. or one of your assumptions that it is impossible is wrong! Can you get back to a state where the bug was not present. just like throwing a bunch of electrical components at the wall and expecting a DVD player to land on the floor is also not going to work. This means that either the impossible is happening. and whether or not a fault in the code is a "stopper" or not. try to move back to a point where the bug is not there. just that it will not be perfect. or sometimes destroys the filestore of the host computer. and then look at the changes made since? If the system is failing as a result of a change or. in that every bug fix will introduce two brand new bugs. I have found statistics which indicate that "two for one" is frequently to be expected. and then introduce the changes until the bug appears. Remember that although the bug is of course impossible. with inputs. This is because when people change the program to make one bit of it work the change that they make often breaks other features of the system. Such efforts are always doomed. If you have taken some time off from debugging. such programs will be very small and therefore not be good for much. If the program crashes every third time you run it. 5. However. it is happening. a bug fix. Programmer’s Point: Bug Fixes Cause Bugs The primary cause of bugs is probably the bug fixing process. In other words you must know how the program is supposed to work before you try and fix problems with what it actually does. Go off and do something different and you may find that the answer will just appear.3 Making Perfect Software There is no such thing as perfect software. I have been nearly moved to tears by the sight of people putting in another loop or changing the way their conditions to "see if this will make the program work". But if it does something like always output the first page twice if you do a print using the Chinese font and a certain kind of laser printer this might be regarded as a problem most users could live with. Alternatively. this is probably the behaviour of a stopper bug. heaven forbid. just maybe this might be the best way forward. This at least makes sure that the fix has not broken anything important. When considering faults you must also consider their impact. A good Source Code Control System is very valuable here. look carefully at how the introduction of the feature affects other modules in the system. prioritise them and manage how they are dealt with. In other words I can write programs that I can guarantee will contain no bugs. As soon as I create a useful program.9. One thing that I should make clear at this point is that the process of debugging is that of fixing faults in a solution which should work. This means that you need to evaluate the impact of the faults that get reported to you. I start introducing bugs. You also need to be aware of the C# Programming © Rob Miles 2010 182 . The only way round this is to make sure that your test process (which you created as a series of lots of unit tests) can be run automatically after you've applied the fix. One of the rules by which I work is that "any useful program will have bugs in it".Advanced Programming Debugging Leave the problem alone for a while.
5. How to be a programmer This web site is also worth a read. as it covers the behaviours of a programmer very well indeed: Further Reading Code Complete Second Edition: Steve McConnell Published by Microsoft: ISBN 0-7356-1967-0 Not actually a book about C#. a fault in a video game is much less of a problem than one in an air traffic control system. but there are quite a few things missing from this text.1 Continuous Development A good programmer has a deliberate policy of constantly reviewing their expertise and looking at new things. And I've never stopped programming. It covers a range of software engineering and programming techniques from the perspective of "software construction".10. For example. Read some of the recommended texts at the end of this document for more on this aspect of programming. If you have any serious intention to be a proper programmer you should/must read/own this book.edu/howto/HowToBeAProgrammer. 5.10 The End? This is not all you need to know to be a programmer. because we don't have time to teach them all. It is not even all you need to know to be a C# programmer. If you are serious about this business you should be reading at least one book about the subject at any one time. However.html C# Programming © Rob Miles 2010 183 . The key to making software that is as perfect as possible is to make sure that you have a good understanding of the problem that you are solving.Advanced Programming The End? context of the development. reading books about programming and looking at other people's code. it is quite a good start. I have been programming for as long as I can remember but I have never stopped learning about the subject. More a book about everything else. that you know how to solve it before you start writing code and that you manage your code production process carefully.10. You should take a look at the following things if you want to become a great C# programmer: serialisation attributes reflection networking 5.mines.
When writing programs we use the word to mean "an idealised description of something". or the return statement. cheque receipt. but you can use it as the basis of. You can't make an instance of an abstract class. or template for. Accessor An accessor is a method which provides access to the value managed within a class. In the case of component design an abstract class contains descriptions of things which need to be present. When a method is called the sequence of execution switches to that method. a concrete one. Whenever you need to collect a number of things into a single unit you should think in terms of creating a class. or if it contains one or more method which is marked as abstract. In C# terms a class is abstract if it is marked as such.Glossary of Terms The End? 6 Glossary of Terms Abstract Something which is abstract does not have a "proper" existence as such. wholesaler receipt etc. Effectively the access is read only. you call it. For example. it can be treated as a Receipt) but it works in its own way. abstract one. An accessor is implemented as a public method which will return a value to the caller. When the end of the method. It can be used to represent a real world item in your program (for example bank account). Each "real" receipt class is created by extending the parent. Class A class is a collection of behaviours (methods) and data (properties). but we do know those behaviours which it must have to make it into a receipt.e. in that the data is held securely in the class but code in other classes may need to have access to the value itself. If the object is not to be changed it may be necessary to make a copy of the object to return to the caller. It is also used in overriding methods to call the method which they have overridden. starting at the first statement in its body. This means that it is a member of the receipt family (i. is reached the sequence of execution returns to the statement immediately following the method call. C# Programming © Rob Miles 2010 184 . We can therefore create an abstract Receipt class which serves as the basis of all the concrete ones. It is used in a constructor of a child class to call the constructor in the parent. Call When you want to use a method. we may decide that we need many different kinds of receipt in our transaction processing system: cash receipt. We don't know how each particular receipt will work inside. Base base is a C# keyword which has different meanings depending on the context in which it is given. Note that if the thing being given access to is managed by reference the programmer must make sure that it is OK for a reference to the object is passed out. but it does not say how they are to be realised.
Glossary of Terms The End? Code Reuse A developer should take steps to make sure that a given piece of program is only written once. One form of a collection is an array. This is usually achieved by putting code into methods and then calling them. A compiler is a large program which is specially written for a particular computer and programming language. they used to be written in assembly language but are now constructed in high level languages (like C#!). The use of class hierarchies is also a way of reusing code. Collection The C# library has the idea of a collection as being a bunch of things that you want to store together. Their interactions are expressed in the interfaces between them. rather than repeating the same statements at different parts of a program. The final phase is the code generator.Collections namespace. Component A component is a class which exposes its behaviour in the form of an interface. for example all the players in a football team or all the customers in a bank. If a class is a member of a hierarchy. the pre-processor. which produces the executable file which is later run by the host. Programmers use constructors to get control when an instance is created and set up the values inside the class. Writing compilers is a specialised business. Constructor A constructor is a method in a class which is called as a new instance of that class is created. and the parent class has a constructor. The collection classes can be found in the System. A collection class will support enumeration which means that it can be asked to provide successive values to the C# foreach construction. This means that rather than being thought of in terms of what it is (for example a BabyCustomerAccount) it is thought of in terms of what it can do (implement the IAccount interface to pay in and withdraw money). C# Programming © Rob Miles 2010 185 . When creating a system you should focus on the components and how they interact. Whenever you want to store a number of things together you should consider using a collection class to do this for you. Otherwise the compiler will refuse to compile your program. You only need to override the methods that you want to update. Most compilers work in several phases. The compiler will produce an executable file which is run. Cohesion A class has high cohesion if it is not dependent on/coupled to other classes. Compiler A compiler takes a source file and makes sense of it. which allows you to easily find a particular item based on a key value in that item. it is important when making the child that you ensure the parent constructor is called correctly. Another is the hashtable. takes the source which the user has written and then finds all the individual keywords. The first phase. identifiers and symbols producing a stream of program source which is fed to the "parser" which ensures that the source adheres to the grammar of the programming language in use.
Many modern programs work on the basis of events which are connected to methods. It can then be directed at a method in a class which matches that signature. Dependency In general. When the event occurs the method is called to deliver notification. since it makes it harder to update the system. windows being resized. A dependency relationship exists between two classes when a change in code in one class means that you might have to change the other as well. where you try and pick up existing code. However. structuring the design so that you can get someone else to do a lot of the work is probably the best example of creative laziness in action. Event An event is some external occurrence which your program may need to respond to. The fact that a delegate is an object means that it can be passed around like any other. Delegates are used to inform event generators (things like buttons. Coupling is often discussed alongside cohesion. Windows components make use of delegates (a delegate is a type safe reference to a method) to allow event generators to be informed of the method to be called when the event takes place. As an example see the discussion of the CustomerAccount and ChildAccount Load method on page 145. A delegate is created for a particular method signature (for example this method accepts two integers and returns a float). keys being hit. Exception An exception is an object that describes something bad that has just happened. However. timers and the like) of the method which is to be called when the event they generate takes place. Creative Laziness It seems to me that some aspects of laziness work well when applied to programming. Dependency is often directional. it is unlikely that changes to the way that the user interface works will mean that the business object needs to be altered. Exceptions are part of the way that a C# program can deal with errors. in that you should aim for high cohesion and low coupling.Glossary of Terms The End? Coupling If a class is dependent on another the two classes are said to be coupled. Making sure the spec. a reference to the instance/class which contains the method and a reference to the method itself. It usually means that you have not properly allocated responsibility between the objects in your system and that two objects are looking after the same data. buttons being pressed. timers going tick etc. too much dependency in your designs is a bad thing. Generally speaking a programmer should strive to have as little coupling in their designs as possible. When a running C# Programming © Rob Miles 2010 186 . is a good example of this. Delegate A delegate is a type safe reference to a method. Code reuse. For example a user interface class may be dependent on a business object class (if you add new properties to the business object you will need to update the user interface). Events include things like mouse movement. Note that the delegate instance holds two items. is right before you do anything is another way of saving on work.
The Exception object contains a Message property that is a string which can be used to describe what has gone wrong.Glossary of Terms The End? program gets to a position where it just can’t continue (perhaps a file cannot be opened or an input value makes no sense) it can give up and ―throw‖ an exception: throw new Exception("Oh Dear").. from the initial meeting right up to when the product is handed over. or FDS. GUID creation involves the use of random values and the date and time. In the above example the message would be set to ―Oh Dear‖. whether the exception // was thrown or not } A try – catch construction can also contain a finally clause. amongst other things. all developments must start with a description of what the system is to do.. and is often called the Functional Design Specification.. It gives an identifier by which something can be referred to. If the exception is not ―caught‖ the program will end at that point. Most operating systems and programmer libraries provide methods which will create GUIDs. You can make a program respond to exceptions by enclosing code that might throw an exception in a try – catch construction. which contains code that is executed whether or not the exception is thrown. Extending the child produces a further level of hierarchy. Immutable An immutable object cannot be changed. This is the most crucial item in the whole project. The classes at the top of the hierarchy should be more general and possibly abstract (for example BankAccount) and the classes at the lower levels will be more specific (for example ChildBankAccount). Functional Design Specification Large software developments follow a particular path. however. The precise path followed depends on the nature of the job and the techniques in use at the developer.
C# Programming © Rob Miles 2010 188 . It operates at all kinds of levels. Interface An interface defines a set of actions. If a method is public it can be called by code other classes. Inheritance Inheritance is the way in which a class extends a parent to allow it to make use of all the behaviours and properties the parent but add/customise these for a slightly different requirement. which means that machine code written for one kind of machine cannot be easily used on another. A class which implements an interface can be referenced purely in terms of that interface. This gives strings a behaviour similar to value types. Metadata must be gathered by the programmer in consultation with the customer when creating a system. The string class is immutable. Interfaces make it possible to create components.dll (dynamic link library) and will not contain a main method. as long as it implements the interface it can be thought of purely in terms of that ability. Each particular range of computer processors has its own specific machine code. A message is delivered to an object by means of a call of a method inside that object. The actions are defined in terms of a number of method definitions. Member A member of a class is declared within that class. The fact that the age value is held as an integer is metadata. Methods are sometimes called behaviours. or add one to an item in the processor. It contains a number of very simple operations. A public method is how an object exposes its behaviours. for example move an item from the processor into memory. Method A method is a block of code preceded by a method signature. It can either do something (a method) or hold some data (variable). They are also used to allow the same piece of program to be used in lots of places in a large development. For more detail see the description of hierarchy. The difference between a library and a program is that the library file will have the extension . The fact that it cannot be negative is more metadata. We don't care precisely what the component is. The method has a particular name and may return a value. A class which implements an interface must contain code for each of the methods.Glossary of Terms The End? remains in memory. Metadata Metadata is data about data. Data members are sometimes called properties. Library A library is a set of classes which are used by other programs. It may also accept a parameter to work on. Machine code Machine Code is the language which the processor of the computer actually understands. Methods are used to break a large program up into a number of smaller units. each of which performs one part of the task. which makes them easier to use in programs.
the new method is called. High Level languages tend to be portable. overloaded. In that case the SetDate method could be said to have been overloaded. Methods are overloaded when there is more than one way of providing information for a particular action. Portable When applied to computer software. The change will hopefully be managed. methods could be provided to set the date. A programmer creating a namespace can use any name in that namespace.Glossary of Terms The End? Mutator A mutator is a method which is called to change the value of a member inside an object. C# provides the using keyword to allow namespaces to be "imported" into a program. year information or by a text string or by a single integer which is the number of days since 1st Jan. This may entail providing updated versions of methods in the class. the more portable something is the easier it is to move it onto a different type of computer. Override Sometimes you may want to make a more specialized version of an existing class. Computers contain different kinds of processors and operating systems which can only run programs specifically written for them. A fully qualified name of a resource is prefixed by the namespace in which the name exists. month. Private A private member of a class is only visible to code in methods inside that class. When the method is called on instances of the child class. in that invalid values will be rejected in some way. each with the same name. Overload A method is overloaded when one with the same name but a different set of parameters is declared in the same class. Three different. This is implemented in the form of a public method which is supplied with a new value and may return an error code. The programmer can then provide methods or C# properties to manage the values which may be assigned to the private members. allowing hierarchies to be set up. You do this by creating a child class which extends the parent and then overriding the methods which need to be changed. The only reason for not making a data member private is to remove the performance hit of using a method to access the data. for example a date can be set by providing day. not the overridden one in the parent. Note that a namespace is purely logical in that it does not reflect where in the system the items are physically located. A portable application is one which can be transferred to a new processor or operating system with relative ease. It is conventional to make data members of a class private so that they cannot be changed by code outside the class. You can use the base keyword to get access to the overridden method if you need to. A namespace can contain another namespace. machine code is much harder to transfer. Namespaces let you reuse names. Namespace A namespace is an area within which a particular name has a particular meaning. C# Programming © Rob Miles 2010 189 . it just gives the names by which they are known.
int b) – has the signature of the name Silly and two int parameters. Protected A protected member of a class is visible to methods in the class and to methods in classes which extend this class. It lets you designate members in parent classes as being visible in the child classes. 2) . Another would be the name of the account holder. The signature is the name of the method and the type and order of the parameters to that method: void Silly(int a. . whereas: Silly(1. It is kind of a half way house between private (no access to methods outside this class) and public (everyone has access). Static In the context of C# the keyword static makes a member of a class part of a class rather than part of an instance of the class. The reference has a particular name. void Silly(float a. A public method is how a class provides services to other classes. .Glossary of Terms The End? Property A property is an item of data which is held in an object. 2) . Source file You prepare a source file with a text editor of some kind. It is conventional to make the method members of a class public so that they can be used by code in other class. An example of a property of a BankAccount class would be the balance of the account. It is text which you want to pass through a compiler to produce a program file for execution.would call the first method. Public A public member of a class is visible to methods outside the class.0f. Reference A reference is a bit like a tag which can be attached to an instance of a class. int b) – has the signature of the name Silly and an float parameter followed by an integer parameter.would call the second. One reference can be assigned to another. If you do this the result is that there are now two tags which refer to a single object in memory. Signature A given C# method has a particular signature which allows it to be uniquely identified in a program. C# uses a reference to find its way to the instance of the class and use its methods and data. This means that the code: Silly(1. The C# language has a special construction to make the management of properties easy for programmers. Note that the type of the method has no effect on the signature. This means that you don’t need to create an C# Programming © Rob Miles 2010 190 .
The movement might be to a disk file. and there is nothing in the actual C# source file that determines the colour of the text. This means that if you create a four element array you get hold of elements in the array by subscript values of 0. Streams remove the need to modify a program depending on where the output is to be sent or input received from. Structures are also passed by value into methods. for example interest rates for all the accounts in your bank. Subscripts in C# always start at 0 (this locates.2 or 3. C# Programming © Rob Miles 2010 191 . Stream A stream is an object which represents a connection to something which is going to move data for us. Structures are useful for holding chunks of related data in single units. This this is a C# keyword which has different meanings depending on the context in which it is given. Test harness The test harness will contain simulations of those portions of the input and output which the system being tested will use. You put your program into a test harness and then the program thinks it is in the completed system. strings in red and comments in green. This means that the first element in the array must have a subscript value of 0. It is used in a constructor of a class to call another constructor. They are not as flexible as objects managed by reference. A test harness is very useful when debugging as it removes the need for the complete system (for example a trawler!) when testing. It also means that static members are accessed by means of the name of their class rather than a reference to an instance. Structure A structure is a collection of data items. the first element of the array) and extend up to the size of the array minus 1. confusingly.1. Keywords are displayed in blue. The best way to regard a subscript is the distance down the array you are going to move to get the element that you want. It must be an integer value.Glossary of Terms The End? instance of a class to make use of a static member. Subscript This is a value which is used to identify the element in an array. but they are more efficient to use in that accessing structure items does not require a reference to be followed in the same way as for an object. and structures are copied on assignment. Note that the colours are added by the editor. for use in non-static methods running inside that instance. It is also used as a reference to the current instance. to a network port or even to the system console. Syntax Highlighting Some program editors (for example Visual Studio) display different program elements in different colours. Static members are useful for creating class members which are to be shared with all the instances. It is not managed by reference. to make it easier for the programmer to understand the code.
In that case I may want to replace (override) the method in the parent with a new one in the child class. if you really want to impose your will on the compiler and force it to compile your code in spite of any type safety issues you can do this by using casting. C# is very keen on this (as am I). This is why not all methods are made virtual initially. For this to take place the method in the parent class must have been marked as virtual. Making a method virtual slightly slows down access to it.. x = y causes the value in y to be copied into x.e. Only virtual methods can be overridden. Note that this is in contrast to reference types where the result of the assignment would make x and y refer to the same instance. Unit test A unit test is a small test which exercises a component and ensures that it performs a particular function correctly. I think it is important that developers get all the help they can to stop them doing stupid things. Sometimes I may want to extend a class to produce a child class which is a more specialized version of that class. in that the program must look for any overrides of the method before calling it. One of these mistakes is the use of values or items in contexts where it is either not meaningful to do this (put a string into a bool) or could result in loss of data or accuracy (put a double into a byte). C# Programming © Rob Miles 2010 192 . Unit tests should be written alongside the development process so that they can be applied to code just after (or in test drive development just before) the code is written. Value types are passed as values into method calls and their values are copied upon assignment. Value type A value type holds a simple value.Glossary of Terms The End? Typesafe We have seen that C# is quite fussy about combining things that should not be combined. and work on the basis that the programmer knows best. that thing must be the right thing. Of course. and a language that stops you from combining things in a way that might not be sensible is a good thing in my book. not afterwards when it has crashed. Changes to the value in x will not affect the value of y. i. Some other languages are much more relaxed when it comes to combining things. They assume that just because code has been written to do something. Try to put a float value into an int variable and the compiler will get cross at this point. This kind of fussiness is called type safety and C# is very big on it.
.Glossary of Terms Index ( () 20.. 124 case 125 Glossary of Terms 193 . 26 data protection 112 default 70 default constructor 98 delegates 162 pointers 162 Dictionary 137 double 20 B base method 112. 22 / /* 38 . 21 { { 20 + + 23 A abstract classes and interfaces 116 methods 115 references to abstract classes 118 accessor 93..
35 loops 43 break 46 continue 46 do . 52 base method 112 Main 17 overriding 111 replace 113 sealed 114 stopping overriding 114 virtual 111 mutator 91. 89.while 43 for 44 while 44 P parameters 22. 159 Dispose 161 modal 161 fridge 6 fully qualified name 73 G Generics 134. 98 H hash table 131 Hashtable 132 I identifier 17. 136 global namespace 178 gozzinta 21 graphical user interface 153 GUID 109 N namespace 19. 177 global 178 nesting 179 separate files 179 using 179 namespaces 73 narrowing 34 nested blocks 58 nesting namespaces 179 new 85.. 31 if 39 immutable 124 information 7 inheritance 109 integers 27 interface abstraction 104 design 108 implementing 106 implementing multiple 108 reference 106 O object class 119 object oriented 15 objects 83. 127 F files streams 141 foreach 143 Form 153. 53 parenthesis 23 Parse 22 pause 169 plumber 9 pointers 162 print formatting 50 Glossary of Terms 194 .Glossary of Terms operands 33 operators 33 M member protection 91 MessageBox 161 metadata 11 methods 17.
92 program Main 19 program flow 38 programmer 6 Programmers Point Always provide an equals behaviour 122 Avoid Many Dimensions 65.Glossary of Terms print placeholders 50 priority 33 private 91. 67. 103 Data Structures are Important 89 Delegates are strong magic 164. 124 comparison 125 editing 125 immutable 124 Length 125 literal 23 StringBuilder 126 structures 79 accessing 80 defining 79 subscripts 62 switch 68. 126 in interfaces 128 public 92 punctuation 25 R ReadLine 21 recipie 16 reference 84. 93. 68 Block Copy is Evil 110 Break Down Your Conditions 41 Bug fixes cause bugs 182 Casts Add Clarity 36 Check your maths 27 Choose Variable Types Carefully 31 Clever is not always Clever 46 Construction Should Be Planned 102.. 94 data 95 methods 96 story telling 37 stream 71 streams 141 StreamWriter 72 string 29.. 85.. 78 Every Message Counts 153 Flipping Conditions 47 Fully Qualified Names are Good 180 Give Your Variables Sensible Names 32 Good Communicators 13 Great Programmers 16 Importance of Hardware 8 Importance of Specification 10 Interfaces are just promises 109 Internationalise your code 104. 69 case 70 System namespace 19 Glossary of Terms 195 . 182 programming languages 13 properties 90. 180. 87 parameters 56 to abstract class 118 replacing methods 113 return 53 S scope 76. .
This action might not be possible to undo. Are you sure you want to continue? | https://www.scribd.com/doc/53282996/Rob-Miles-CSharp-Yellow-Book-2010-1 | CC-MAIN-2015-48 | refinedweb | 80,250 | 75.1 |
Stephan T. Lavavej - Core C++, 9 of n
- Posted: Jun 11, 2013 at 6:30 AM
- 73,745 Views
- 35 Comments
Something went wrong getting user information from Channel 9
Something went wrong getting user information from MSDN
Something went wrong getting the Visual Studio Achievements
Right click “Save as…”
In part 9, STL digs into lambdas and other expressions. Lambdas are very useful and you've know doubt been enjoying them in your modern C++ programming. As you can imagine, STL will go deep and teach you things about lambdas that you may not know. You'll also learn a lot about order of precedence and associativity for expressions in only the way Stephan can teach you (thorough treatment). Tune in.
See part 8: do-while loop, casts, one definition glad it's back!
Very pleased to see Stephen again, I imagine he's been busy with Visual C++ 2013 ahead of the BUILD conference, so i guess we can forgive him for disappearing from the C9 radar screens for a while
I believe lamdas are explained very well here and, to some extend, in depth. Some hard things -to unexperienced programers, not
acquainted with lamdas- are easy if explained well! Well done!
Glad you are back ! Great one as always.
Welcome back STL... cant wait to watch this...
Tom: Yep, I was super busy getting the STL ready for VS 2013 Preview. I've got a VCBlog draft with a detailed changelog that I'll be able to publish after the Build conference.
Welcome back! We missed your talks!
Great to see you back in action....
@STL:Can't wait to read your blog update post BUILD Stephan. I usualy diff the sources, but having to insights will help upgrade confidence considerably.
Just wanted to say I totally respect the work that engineers like James McNellis and yourself do for the Visual C++ team Stephan, and I imagine this decision was probably made higher up - but is there any chance of retro-fitting the C++ 11 stuff from Visual Studio 2013 back to VisualStudio 2012? You folks kindly u-turned on Windows XP and I was wondering if once some of the VS2013 testing pressure was off you could 'finish the job' in VS2012? I had hoped that VS2013 would look forward to C++ 14, rather than back to pick up the pieces of '11 (which should IMO have been addressed in '12.)
I do not mean to sound ungrateful here, I love Visual C++, it's practically been my desktop for the past 20 years, but getting new compilers installed - particularly for enterprise ISVs where multiple products and teams are at work on a shared code base is difficult and swallowing a VS2012 Update 4 (?) would be less painful than having to jump to VS2013 - which of course we will do in time, but I feel shouldn't have to do in order to pick up the bits that where promised for '12 (more than 7 months ago now...)
Just wanted to comment on the return type deduction with multiple return statements. My understanding is that the semantics of what VS implements are slightly different to what C++14 will support. I guess VS2012 implements something similar to what was originally proposed in Core Issue 975, but for C++14 the semantics are different and described in N3638, although there is some overlap.
Finally some more, thank you for doing this. Great bed time stories.
One thing though: At 51:15 you say that your ++n lambda is “totally allowed by the STL”. I would disagree after reading the box here because you're causing side effects. And in a parallel transform version I would expect n to be indeterministically changed.
It also says “until C++11”, but how would C++11 cope with this??
long awaited delight.
At some length documentation starts feeling dry to me. When I get examples to lay hands-on, then its more comfortable for me to look into documentation over and over.
I prefer your presentations as the examples are cleanly related with the topic, and when consuming the topic for making app solution for some particular domain (say games) then I'm free to innovate than be induced by another software architect's choices- that's bad as too many chefs spoil the broth. Every choice is like sequence point following which I collect peer reviews of choices, whose responsibility is with me.
So awaiting your presentations is definitely worth the wait..
(This is STL, really - something weird happened where I can't view this page logged in under my account, even though I was able to when I posted my first comment here. I can view Part 8, just not this one. If anyone doesn't believe it's me, mail me - my address is easy to find, it's in the STL11: Magic && Secrets slides.)
Tom> is there any chance of retro-fitting the C++ 11 stuff from Visual Studio 2013 back to VisualStudio 2012?
This will be addressed in my VCBlog post. In fact, my draft has an FAQ at the end, where this is question #3.
(I'm not allowed to talk about 2013's features yet - while I could *probably* get away with answering this question now, I prefer to avoid annoying my bosses and boss-like entities.)
cmeerw> Just wanted to comment on the return type deduction with multiple return statements. My understanding is that the semantics of what VS implements are slightly different to what C++14 will support.
The rules appear to be exactly the same to me (although I'm not a Core Language guru, I just play one on TV).
VC doesn't support this in normal functions, and (except for trailing return types) it doesn't support auto or decltype(auto) return types, and it doesn't support the recursion rules (because lambdas can't be recursive). But as far as multiple return statements are concerned, I believe we follow the "all the types have to be the same" rules.
primfaktor> At 51:15 you say that your ++n lambda is "totally allowed by the STL". I would disagree after reading the box here because you're causing side effects.
N3690 25.3.4 [alg.transform]/2 prohibits transform's functor from invalidating iterators to the elements being traversed, and prohibits modifying elements in the sources/destination, but other side effects are invisible as far as the STL is concerned. (transform() specifically does not guarantee that the elements will be transformed in order. It was probably a bad idea for me to demonstrate concatenating to_string(n) with transform().)
Similarly, 25.1 [algorithms.general]/8-9 prohibits Predicates and BinaryPredicates from modifying their arguments, but they can modify other state (subject to the restriction that in certain contexts, like sort(), they must return consistent answers over time; you can't say that X is less than Y at one point, then later that it's not-less-than Y).
> And in a parallel transform version I would expect n to be indeterministically changed.
The STL is forbidden from performing autoparallelization except when it's unobservable. For example, count(const int *, const int *, const int&) could be autoparallelized unobservably, but invoking a user-defined functor is observable. This is 17.6.5.9 [res.on.data.races]/8: "Unless otherwise specified, C++ standard library functions shall perform all operations solely within the current thread if those operations have effects that are visible (1.10) to users."
> It also says "until C++11", but how would C++11 cope with this?
Sorry, what are you referring to?
geeyef> One thing that eludes me is the purpose of the pointer-to-member operators. They're easy enough to use by why bother since I can just reference the member directly from the object itself. Is this something that simplifies template programming?
Pointers to members are especially useful when you have a container of objects and want to select a particular member function or data member from each of them and have an STL algorithm do something with it. If you're writing a loop yourself, you can just access the member directly, but with an STL algorithm you need a way to say "please select this member".
Here's a full example:
C:\Temp>type meow.cpp
#include <algorithm>
#include <functional>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class NPC {
public:
NPC(const string& name, const int hp)
: m_name(name), m_hp(hp) { }
friend ostream& operator<<(ostream& os, const NPC& npc) {
return os << "(" << npc.m_name << ", " << npc.m_hp << ")";
}
void damage(const int n) {
m_hp -= n;
}
bool dead() const {
return m_hp <= 0;
}
private:
string m_name;
int m_hp;
};
template <typename C> void print(const C& c) {
for (const auto& e : c) {
cout << e << " ";
}
cout << endl;
}
int main() {
vector<NPC> v;
v.emplace_back("Walton Simons", 100);
v.emplace_back("Joseph Manderley", 10);
v.emplace_back("Bob Page", 500);
v.emplace_back("Paul Denton", 50);
print(v);
v[0].damage(100);
v[2].damage(1729);
v[3].damage(47);
v.erase(remove_if(v.begin(), v.end(), mem_fn(&NPC::dead)), v.end());
print(v);
}
C:\Temp>cl /EHsc /nologo /W4 /MTd meow.cpp
meow.cpp
C:\Temp>meow
(Walton Simons, 100) (Joseph Manderley, 10) (Bob Page, 500) (Paul Denton, 50)
(Joseph Manderley, 10) (Paul Denton, 3)
VSChawathe: Thanks!
STL, I have question not related to this session. Maybe you would like to not pollute this post with a random question like that. Could I ask your opinion via e-mail then?
My question is about 'using namespace std;' vs 'std::_name_'. I am well aware of the StackOverflow discussions where the majority of programmers think std::_name_ is the way to go and pulling the whole namespace into the global one is bad. However in my company my team leader praises omitting std:: for cleaner visuals. I am still not used to it, I just want to write std::. Not just to write it, but to avoid name conflicts.
How would you comment on this? What do you prefer?
@meow I've 2 profiles on Microsoft sites as well and strangely using my live account makes me use the new one.. I've to discard for So much for provenance. If you find related way by inside-out approach, submit my example to get both my profiles merged. Thnx.
Bow Wow (& that's doggie barks).
Hi Stephan, you mention that the original motivation for lambdas in C++ was when working with the Standard Library (that is as inputs to higher order functions), but I find them an incredibly useful tool to avoid code duplication *within* a function, often in a way that better preserves function level encapsulation (better that is than say a module level function the the anonymous namespace). A classic example of this occurs when writing exception catch handler logic. Do you consider this an 'abuse' of lambdas? When do you use them outside of higher-order functions like those found in <algorithms> ?
Thank you. That's makes complete sense now. I've been indirectly using it the whole time via the STL I didn't realize it. Never really had to write my own generic algorithms or containers since the STL pretty much has everything I need.
(I'm still unable to view this page while logged in, but I guess I can say MSFT instead of meow for uniqueness.)
John> My question is about 'using namespace std;' vs 'std::_name_'.
(Terminology note: "using namespace std;" is a using-directive, while "using std::tuple;" is a using-declaration.)
The only absolute rule here is that using-directives and using-declarations should never appear at global scope in headers, because that'll affect any source files including that header (and any other headers included afterwards) whether they want it or not. (Within headers, you should think carefully before putting using-directives and using-declarations at namespace scope, because users might want to say "using namespace YourNamespace;" and they might not want that to drag in stuff from other namespaces. Note that block scope within headers is totally isolated.)
Aside from that, it's mostly a matter of personal preference. Relying on using-directives means that your code might fail to compile in the future, if new names are added to any of those namespaces (or even if your TU ends up dragging in headers it wasn't dragging in before). I've dealt with this problem in my code at home, where I relied on "using namespace std; using namespace boost;" and Boost ended up being a victim of its own success when shared_ptr appeared in std. And as you know, explicitly qualifying everything is verbose.
I'm leaning towards using-declarations myself; they're more verbose than using-directives, but less than qualifying everything everywhere, and they aren't vulnerable to new stuff appearing in namespaces because they're so targeted.
Tom> A classic example of this occurs when writing exception catch handler logic.
Well, you shouldn't be writing too many of those. (At home, I've recently started using Boost.ScopeExit now that it's powered by lambdas - which I believe happened after I filmed an STL video demonstrating ScopeExit - because it's a terse alternative to writing one-time-use RAII classes for old-style APIs. I'd rather write a wrapper class for anything used repeatedly, though.)
> Do you consider this an 'abuse' of lambdas? When do you use them outside of higher-order functions like those found in <algorithms> ?
I wouldn't say that using lambdas outside of their traditional habitats (customizing STL algorithms, initializing std::functions/threading stuff, converting to function pointers for C-style callback APIs, etc.) is abusive, but there are definitely limits when named functions or function objects should be preferred. If your lambdas start to get really big, you should consider making them named functions/functors. (JonCaves once told me about finding a multi-hundred-line lambda in a codebase that I won't name.) If you need recursion, absolutely give it a name, don't attempt crazy hacks (I have seen people do unspeakable things).
One cute use is for complicated initialization of something that can be const afterwards - writing a lambda and immediately invoking it is one way to achieve this. Fortunately, C++11 initializer lists are a better way to initialize containers, so that replaces some uses.
By the way, <algorithm> doesn't contain any higher-order functions. bind() is a higher-order function (it consumes and emits functors). sort() is just a sort whose behavior you can control via an ordinary functor - it doesn't emit functors.
Yay, the C9 team fixed my profile (there was a "duplicate record" in the database).
Truly outstanding presentation, clear, concise, precise, to the point.
Can you please please post the excel file with operators order, it'll make for a nice bookmark?
I uploaded it to my SkyDrive:
@STL
one small offtopic Q related to STL:
AFAIK all STL containers in VS11 are optimally small considering their current representation. Does this cover string? From what I know it could be as big as vector, but it is bigger. I guess it is so that SSO kicks in more often. How far from truth am I? :D
And one trivia/opinion Q:
what is your personal opinion on extra () changing meaning of decltype? I personally hate it with passion and I think there should be declref for easier readability but most ppl seem to be fine with decltype.
I love this lectures!
Ivan> AFAIK all STL containers in VS11 are optimally small considering their current representation. Does this cover string?
Yes, see . (I'm aware of bloat in bind() and std::function that I need to fix, but those aren't containers.)
> From what I know it could be as big as vector, but it is bigger. I guess it is so that SSO kicks in more often.
Yes. We activate the Small String Optimization for 15 chars or 7 wchar_ts.
> what is your personal opinion on extra () changing meaning of decltype?
It's there for a good reason. decltype's behavior for arbitrary expressions is exactly right - if your return type is decltype(foo()) because you're returning foo(), you really want the answer to be X for prvalues, X& for lvalues, and X&& for xvalues. But it would be weird if int i = 1729; decltype(i) gave you int&. (It would be especially undesirable if you were returning i from a function.)
@STL
tnx for the answers, but decltype beside simple stuff like decltype(i) or decltyping based on vector element type is beyond my ability to comprehend. :) All I was here talking about was that decltype is the only AFAIK example of C++ code where ((something is different from (something)-
x3 and x4 in this Q:
So I wondered if you think that is bad for readability(mental parsing by programmer :)).
But at least now you have material for another episode ;)
auto and decltype -IDK why but they kind of fit together for me in same episode- I guess because they both deal with type deduction.
@STL
I forgot to ask one more question... again opinion based :)
Would you like to have ability to give custom comparator to map as a lambda? I know about decltype hackery :P but this is one of those things I just feel are limitations while most ppl say write the damn named function. :)
> decltype is the only AFAIK example of C++ code where ((something is different from (something)
Yeah, this was extensively debated in the Committee.
> Would you like to have ability to give custom comparator to map as a lambda?
You can do that through decltype (which currently doesn't work in VC due to a known STL bug), or by declaring the comparator's type as a function pointer and constructing your map from a stateless lambda. I recommend against that, though (it will be less efficient).
@STL again tnx
I didnt know Committee had the same concerns. :)
I knew about "decltype hackery" how I called it, I just find named function less ugly, so my question is would you like to have ISO C++ support constructing comparator from lambda without decltype... and making sure that types of 2 maps constructed from same lambdas(same == same code ignoring spacing and newline) are same.
I have personal hate :P for decltype where it doesnt feel right(aka 2.1 in this example )
I REALLY hope current draft dropped that. :)
@STL
one more thing I forgot to ask... now you can talk about VS 2013... are clocks are now fixed... Afaik there was a bug with steady clock not being steady. And I didnt find anything about that in your huge huge blog post(BTW congrats on fixing all those bugs)
> would you like to have ISO C++ support constructing comparator from lambda without decltype...
I don't know what that would mean. A lambda expression constructs an object (of a non-default-constructible type), so you need to provide that object during map construction in addition to either the lambda's actual type (via decltype), a function pointer type (for stateless lambdas), or std::function (with the associated runtime costs).
At least two restrictions would have to be lifted to accomplish this through the type alone - stateless lambdas would have to be default-constructible and decltype(lambda expression) would have to be permitted, and you'd still have to say decltype to get a type.
> and making sure that types of 2 maps constructed from same lambdas(same == same code ignoring spacing and newline) are same.
That is essentially asking compilers to "hash" implementations which is tricky in the way you're asking.
> I REALLY hope current draft dropped that.
I believe that is permitted by N3690 although I haven't kept careful track of all the stuff that Core voted in.
As always, if you don't like it, don't write it. There's lots of things in C++ I avoid using (e.g. virtual inheritance) even if they don't rise to the level of abominations.
> are clocks are now fixed... Afaik there was a bug with steady clock not being steady.
No, sorry. I just didn't have time to fix steady_clock not being steady and high_resolution_clock not being high resolution (I need an uninterrupted week to rip out and rewrite their implementations).
> (BTW congrats on fixing all those bugs)
Thanks!
@STL
again tnx for the answers... it is really interesting to speak to somebody so skilled. I mean it is you know like Nobel prize winner answering your physics question. :)
regarding lambdas in maps I was talking more from my perspective(code monkey :P ), you are approaching it more from language side. Im not saying you are wrong to do that but I was wondering what do you think about that addition from usability perspective not from how hard is to do it(aka ISO has infinite power and compiler devs have infinite coffee supply) .
Aka would you like to say something like
map<string, double, [](const auto& a, const auto& b) {return a.size() < b.size();}>
I hope it is clear, if not here is the problem explained:
"As always, if you don't like it, don't write it."
Point is that I would like core language support for something like Boost Lambda magic... those things are more magical than unicorns. :)
aka
accumulate(s, s + size, char(), (_1 ^ _2));
If you ask why not use just boost lambda... I kind of fear that they arent as good when it comes to perf as core lang stuff, but I might be wrong, if you know the definite answer(I care only about runtime perf, not compile time) please share. :)
regarding clocks... I thought that Win API has all that implemented(aka you are just providing C++11 wrappers for "good" old C functions) so it is trivial to do. :)
Please feed us more details about C++ 14/17 .
thank you ,
Stephan.
Thank you for your talk! I would highly appreciate some talk about custom allocators. I found your article about Mallocator but some things have changes since then, for example allocator_traits got added into c++11. I did some research and many people are interested in it (especially game developers using custom allocators for small objects, pool, stack etc) while it's really hard to find some comprehensive info (even in working draft).
Remove this comment
Remove this threadclose | http://channel9.msdn.com/Series/C9-Lectures-Stephan-T-Lavavej-Core-C-/Stephan-T-Lavavej-Core-C-9-of-n | CC-MAIN-2014-42 | refinedweb | 3,757 | 62.17 |
Nim performance tuning for the uninitiated
UPDATE 2017-06-04: Corrected some slight misinformation regarding link time optimisations and the {.inline.} pragma, some stylistic improvements, added more references.
Overview
This post documents the trials and tribulations I encountered during my foray into the wonderful world of low-level performance optimisation. For those intimately familiar with modern optimising compilers and CPU architectures, this will be kindergarten stuff. Although I have done my share of low-level C and assembly coding in my high-spirited teenager years, that was more than 20 years ago on a then-state-of-the-art 486 DX-2/66, so naturally it didn’t prevent me from running into some quite embarrassing mistakes as things are vastly different today, as we’ll shortly see…
Some of you might know that I’m writing a ray tracer (veeeeeery slowly), so it’s no surprise that I’m quite a bit obsessed with raw numerical performance. Don’t bother with what people tell you about Moore’s Law, falling GFLOP prices, programmer productivity and the “evils” of optimisation—anybody who writes or uses ray-tracing software can tell you that nothing is ever fast enough for this task (we’ll come back to this at the end in more detail). The de facto language choice for writing such high-performance applications has always been C++, potentially with some assembly thrown in for good measure. One of the main reasons why I have chosen Nim for this project was that it promises C-level performance without having to resort to any weird tricks (and, of course, it prevents me from having to use C++). I have a very annoying habit that I don’t just believe other people’s statements unless I can verify them myself, so I thought it was high time to put Nim’s efficiency claims to test… which, as we’ll see, led me into some trouble.
First attempts
The whole performance test idea came up when I was implementing the ray-triangle intersection routine in my ray tracer. My plan was simple: implement the same algorithm in C++ and Nim and measure if there’s any performance penalty for using Nim. Theoretically, there would be very little to no difference in runtime speed as Nim code gets transformed to plain C first, which then gets run through the same optimising C++ compiler. I was a bit unsure though if Nim objects would map directly to C structs and what magnitude of performance degradation (if any) would the GC introduce.
As my first slightly misguided attempt I tried to execute the intersection routine with the same static input a few million times, then calculate an average intersections per second figure from that. To my greatest shock, the C++ version measured to be about 40-50 times faster!
Now, there were a couple of serious problems with this naive approach. Firstly, I used a simple direct implementation of the Möller–Trumbore intersection algorithm. Notice that the algorithm can terminate early in multiple places? Therefore, it would make much more sense to test with a dataset large and varied enough so that the different execution paths would be exercised with roughly the same probability, allowing for a meaningful average to be calculated for the whole algorithm. Secondly—and this is the worse problem!—by using static data defined at the time of compilation, we’re giving the compiler a free license to optimise the whole code away and just replace it with a constant! This might come as a surprise to some—and it certainly did surprise me!—but it turns out that modern optimising compilers like gcc and clang are really good at constant folding!
So why don’t we just turn the compiler optimisations off for the tests then? Well, that would defeat the whole purpose of the performance measurements, so that’s out of the question. We must always use the optimised release builds for such tests. But then how can we ever be certain that the compiler hasn’t pulled some tricks behind our backs, rendering the whole test scenario invalid? Well, the only way to do that reliably is to inspect the final output produced by the compiler, namely the resulting binary. Luckily, we don’t have to do exactly that, as there’s a second-best (and much more convenient) option: most compilers can be instructed to emit the post-optimisation stage assembly sources that are used for generating the final binary.
While this might sound a little intimidating for non-assembly programmers (which is probably at least 99.9999% of all programmers in the world today), in practice we don’t need to be expert assembly coders to assert whether the compiler has done what we wanted. Moreover, this is definitely a useful skill to have because sometimes we can “nudge” the compiler into the right direction to come up with more efficient assembly-level structures by re-arranging the high-level code a bit and maybe adding a few inlining hints here and there. Again, the only foolproof way to see if such tricks have really worked is to inspect the assembly output.
Test setup
The two most obvious solutions to prevent constant folding is to either load the test data from a file or to generate it at runtime. I chose the latter because I’d have to write the test data generation code anyway, so why not do it at runtime then.
The tests execute the following steps:
Precalculate T number of random triangles so that all points of the triangles lie on the surface of the unit sphere.
Precalculate R number of random rays so that each ray goes through two points randomly selected on the surface of the unit sphere.
Intersect each ray with the whole set of triangles, so there will be R ✕ T intersection tests in total.
The only tricky thing is to make sure that the random points we pick on the sphere are uniformly distributed. A straightforward solution to this problem can be found here.
All tests were performed on a MacBook Pro (Mid 2014), 2.2 GHz Intel Core i7, 16 GB RAM running OS X El Capitan 10.11.6.
Round 1 — Nim vs C++
0. C++
The “gold standard” for our daring enterprise will be the performance of the single-threaded orthodox C++ implementation. You can check out the source code here. As we can see in the results below, our testing method gives us a roughly 5% hit rate. The exact hit rate does not actually matter as long as it’s not too close to zero and if it hovers around the same value in all tests.
Total intersection tests: 100,000,000 Hits: 4,994,583 ( 4.99%) Misses: 95,005,417 (95.01%) Total time: 1.93 seconds Millions of tests per second: 51.87
So ~51.9 millions of ray-triangle tests per second it is. I guess that’s not too bad for a straightforward C implementation! It turns out that Nim can easily match that, but you have to know exactly what you’re doing to get there, as I’ll show below.
Memory layout
One very important thing to note is how the triangle data is laid out in memory. For every single ray we’re going to mow through all the triangles in a linear fashion, checking for intersections, so we must store the triangles contiguously in a big chunk of memory to best utilise the CPU data caches. This is straightforward to do in C:
struct Vec3 { float x; float y; float z; }; Vec3 *allocTriangles(int numTriangles) { return (Vec3 *) malloc(sizeof(Vec3) * numTriangles * 3); }
Inspecting the assembly output
Before progressing any further, let’s take a quick look at a typical number crunching function in assembly form! This is the command to compile the C++ source into the final executable:
clang -std=c++11 -lm -O3 -o perftest perftest.cpp
And the command to emit the corresponding assembly output:
clang -std=c++11 -S -O3 -o perftest.s perftest.cpp
Now we can do a full text search in the resulting
.s file for the function we want to inspect (
rayTriangleIntersect in this case). As I said, we don’t really need to understand assembly on a deep level for our purposes; it’s enough to know that a healthy-looking number crunching function should resemble something like this:
.globl __Z20rayTriangleIntersectP3RayP4Vec3S2_S2_ .align 4, 0x90 __Z20rayTriangleIntersectP3RayP4Vec3S2_S2_: # decorated function name .cfi_startproc # function starts here pushq %rbp # some init stuff Ltmp15: .cfi_def_cfa_offset 16 Ltmp16: .cfi_offset %rbp, -16 movq %rsp, %rbp Ltmp17: .cfi_def_cfa_register %rbp movq (%rdx), %xmm14 movq (%rsi), %xmm15 ... # omitted mulss %xmm6, %xmm11 movaps %xmm1, %xmm2 mulss %xmm0, %xmm2 subss %xmm2, %xmm11 movaps %xmm13, %xmm4 # actual function body mulss %xmm0, %xmm4 movaps %xmm5, %xmm2 mulss %xmm7, %xmm2 addss %xmm7, %xmm2 ... # omitted jmp LBB5_9 # some cleanup stuff LBB5_2: movss LCPI5_0(%rip), %xmm6 jmp LBB5_9 LBB5_4: movss LCPI5_0(%rip), %xmm6 jmp LBB5_9 LBB5_6: movss LCPI5_0(%rip), %xmm6 LBB5_9: movaps %xmm6, %xmm0 popq %rbp retq .cfi_endproc # the end
The init and cleanup stuff we’re not really interested about, but the fact that they are there is actually a good sign; this means that the compiler has not optimised away the whole function. The function body for numerical calculations involving floating point numbers will be basically lots of mucking around with the SSE registers1 (XMM1 to XMM15). For those who have never seen assembly listings before,
movaps moves values between registers,
mulss multiplies two registers,
addss adds them together and so on. Even for a relatively short numerical function like ours, the function body will go on for pages. This is good, this is what we wanted—it looks like we have the real function here, not just some constant folded version of it.
For those wanting to delve further into the dark art of assembly programming, make sure to check out the two excellent articles in the further reading section at the end of the article.
1. Nim — using GLM
I started out with nim-glm in my ray tracer, which is more or less a port of the GLM OpenGL mathematics library. The original version of the code used nim-glm’s
Vec3[float32] type and its associated methods for vector operations.
To my greatest shock, the performance of my initial Nim code was quite abysmal, barely 1-2 millions of tests per second! After much head scratching and debugging it turned out that nim-glm was the culprit: the vector component getter and setter methods were not inlined by the compiler. After a few strategically placed inline pragmas the situation got somewhat better, but still a 10-fold performance degradation compared to the C++ version:
Total intersection tests: 100,000,000 Hits: 4,703,478 ( 4.70%) Misses: 95,296,522 (95.30%) Total time: 19.86 seconds Millions of tests per second: 5.04
At this point I decided to give up on nim-glm altogether and write my own vector routines. The thing is, nim-glm is a fine general purpose vector maths library, but when it’s time to get into serious performance optimisation mode, you want complete control over the codebase, and using an external component that heavily uses macros is just asking for trouble.
2. Nim — custom vector class (object refs)
Okay, so using my own vector maths code resulted in some improvement, but not by much:
Total intersection tests: 100,000,000 Hits: 5,718,606 ( 5.72%) Misses: 94,281,394 (94.28%) Total time: 11.41 seconds Millions of tests per second: 8.76
What went wrong here? It turns out that for some reason I used object references instead of plain objects for my
Vec3 and
Ray types:
type Vec3 = ref object x, y, z: float32 type Ray = ref object dir, orig: Vec3
Inspecting the corresponding C code in the
nimcache directory makes the problem blatantly obvious (I cleaned up the generated symbol names for clarity):
struct Vec3ObjectType { NF32 x; NF32 y; NF32 z; }; struct RayObjectType { Vec3ObjectType* dir; // indirection! Vec3ObjectType* orig; // indirection! }; struct SeqVec3Type { TGenericSeq Sup; Vec3ObjectType* data[SEQ_DECL_SIZE]; // indirection! (array of pointers) }; SeqVec3Type* vertices;
So instead of having a contiguous block of triangle data, we ended up with a contiguous block of pointers to each of the points making up the triangles. This has disastrous performance implications: all the points are randomly scattered around in memory so the cache utilisation will be really terrible as it is evident from the results.
3. Nim — custom vector class (objects)
Fortunately, the fix is very simple; we only need to remove the
ref keywords:
type Vec3* = object x*, y*, z*: float32 type Ray* = object dir*, orig*: Vec3
This will make the resulting type definitions be in line with our original C++ code:
struct RayObjectType { Vec3ObjectType dir; Vec3ObjectType orig; }; struct SeqVec3Type { TGenericSeq Sup; Vec3ObjectType data[SEQ_DECL_SIZE]; // array of structs };
And the moment of truth:
Total intersection tests: 100,000,000 Hits: 5,206,370 ( 5.21%) Misses: 94,793,630 (94.79%) Total time: 1.96 seconds Millions of tests per second: 50.93
Awww yeah! This is basically the same performance we had with the C++ version. Comparing the assembly outputs of the Nim and C++ versions (exercise to the reader) reveals that they are basically the same, which is no great surprise as ultimately we’re using the same compiler to generate the binaries.
4. Nim — vector module
Alright, so time to extract the vector maths stuff into its own module. Pretty trivial task, right? Let’s run the tests again:
Total intersection tests: 100,000,000 Hits: 5,237,698 ( 5.24%) Misses: 94,762,302 (94.76%) Total time: 2.89 seconds Millions of tests per second: 34.55
Shit, what went wrong here?
To figure this out, we’ll need to understand how the Nim compiler works. First Nim generates a single C file for every module in the project, then from that point everything gets compiled and linked as if it were a regular C codebase (which technically it is): C files get compiled into objects files which then get linked together into the final binary. Inlining functions across objects files at link time is generally not performed by default by most compilers, and although gcc and clang can be instructed to do link time optimisations (LTO) by specifying the
-flto flag, Nim doesn’t use this flag by default. Therefore, if we want to inline functions across module boundaries in a robust way—even when LTO is turned off—we need to explicitly tell the Nim compiler about it with the
{.inline.} pragma. This pragma will force the inlining of the functions decorated with it into all generated C files where the functions are referenced on the Nim compiler
(preprocessor) level.
5. Nim — vector module (with inlines)
Fixing this is very easy; as explained above, we’ll just need to decorate every method in our module with
{.inline.} pragmas. For example:
proc `-`*(a, b: Vec3): Vec3 {.inline.} = result = vec3(a.x - b.x, a.y - b.y, a.z - b.z)
And we’re done, the performance of version 3 has been restored:
Total intersection tests: 100,000,000 Hits: 4,640,926 ( 4.64%) Misses: 95,359,074 (95.36%) Total time: 1.96 seconds Millions of tests per second: 51.12
Round 2 — Nim vs Java, JavaScript & Python
At this point I was really curious how some other languages I use regularly would stack up against our current benchmarks kings (look, there’s even a crown in the Nim logo, surely that can’t be just a coincidence!). I didn’t try to do any nasty tricks to increase performance in any of these tests (e.g. using simple arrays of primitives instead of objects in Java); I just did a straightforward idiomatic port in each case (you can check out the code here). Let’s see the final results:
I was quite disappointed with the Java results at only 60% of the performance of C++/Nim. JavaScript, on the other hand, did surprise me a lot; it’s basically on par with the performance of Java. I expected much less numerical performance from JavaScript! Taking into consideration that JavaScript has only doubles while in Java I was able to switch to floats for a slight performance bump makes this result even more impressive. Another surprise was that running the tests as standalone programs with NodeJS or in a browser (Chrome and Firefox was tested) yielded basically the same results. (Of course, all this doesn’t make JavaScript suddenly a good language, but it’s good to know that at least it’s not horribly slow!)
The CPython figures are, however, rather pathetic. I like Python a lot, it’s one of my favourite languages, but it’s clearly in no way suited to numerical computing (note we’re talking about the core language here, not NumPy and such). Fortunately, PyPy brings the performance back from absolutely abysmal (0.4% of the speed of the C code) to quite reasonable for a dynamic interpreted language (20% of the C code). That’s an impressive ~50x speedup (!) achieved by just switching from CPython to PyPy! Interestingly, CPython3 is about 30% slower than CPython2 in these tests. I don’t know if this a general trend with CPython3’s performance, but it’s discouraging, to say the least…
JIT warmup
There’s another thing to note that can confuse rookie benchmarkers and has implications on runtime performance, namely that JIT compiled languages need a “warm up” period before they can reach peak performance. In our current benchmark, that’s Java, JavaScript and PyPy (CPython employs no JIT whatsoever). While the performance of C++ and Nim scale linearly with the size of the dataset, for JITed languages the performance is roughly a logarithmic function of the dataset size, as summarised by the below table:
Conclusion
Unsurprisingly, Nim is capable of reaching C/C++ performance when you know what you’re doing. Because there’s an extra layer of indirection when using Nim (Nim source code needs to be translated to C first) and Nim in general is further from the “metal” than C (in other words, it’s more high-level and less of a portable assembly language like C), one needs to be careful. But the most important thing to note is that Nim allows the programmer to take control over low-level details such as memory layout when necessary. This is in stark contrast with other high-level languages such as Java, Python and JavaScript which do not give the programmer this freedom. Having said that, the aforementioned languages have fared quite admirably in the benchmarks, JavaScript being the biggest surprise with a numerical performance on par with Java.
The greatest lesson for me in this experiment was that with modern compilers and CPU architectures a naive approach to benchmarking is almost always bound to fail. For performance critical applications one must establish a suite of robust automated performance tests and run them periodically as it’s very easy to introduce quite severe performance degradations even with the most innocent looking refactorings (e.g. think of the inlining problem after we extracted the vector operations into a module). Without a systematic approach to performance regression testing, such problems can be quite frustrating and time consuming to locate and fix (or even just detect, in case on non-trivial applications!). Also, when benchmarking there’s nothing like inspecting the actual assembly output; that’s the only foolproof way to catch the compiler red-handed at optimising away your test code.
Does it all matter?
I already hear some people repeating the common wisdom that hardware is cheap, programmers (and their time) are expensive, and with so much power to spare on modern CPUs, all this micro-optimisation exercise is just waste of time, right? Well, that depends. I tend to agree that performance is not so critical for lots (maybe even the majority) of programming tasks and in those cases it makes sense (commercially, at least) to optimise for programmer productivity by using a high-level language2 . But when speed matters, you are definitely going to hit a brick wall with a language that doesn’t make low-level optimisations possible.
Let’s pretend for a moment that our relative performance results would be valid for the entire ray-tracer (oversimplification, but not entirely impossible). Then if it would take 3 hours for the C and Nim implementations to render a single frame, the Java and JavaScript versions would require 5 hours, the PyPy version 15 hours, and finally the CPython implementations over 30 and 40 days (!) for versions 2 and 3, respectively. Java and JavaScript seem to be worthy contenders at first—until we start looking into taking advantage of multiple CPU cores and SIMD instructions. Only Java, C/C++ and Nim have proper multi-threading support, so assuming 4 CPU cores (fairly typical nowadays) and a very conservative 2x speedup by introducing multi-threading, the performance gap widens. From our list of languages only Nim and C/C++ make utilising SIMD instructions possible, so assuming another 2x speed bump thanks to this (again, staying quite conservative), the final figures would look like this:
This is actually more in-line with real-life experience; a well-optimised C++ renderer can easily outperform a similarly well-optimised Java implementation by a factor of 2 to 3, and JavaScript and Python basically don’t even have a chance. As I said, this is not a Python bashing contest, I really like the language and use it all the time for writing scripts and small tools, but one needs to have a solid understanding of the limitations of one’s tools and sometime do a reality check… I always find it amusing when people attempt to “defend” their favourite inefficient high-level languages by saying that algorithmic optimisations are the most important. Well, of course, no sane person would argue with that! But if you took the same optimal algorithm and implemented it in a language that offered greater low-level control over the hardware (well, or had multi-threading and SIMD support at all), it is not unrealistic for the performance gain factor to be in the 2 to 1000 range!
As for myself, I will happily continue using Nim, safe in the knowledge that I won’t hit an insurmountable brick wall in the future, because whatever is possible in C in terms of performance, there’s a way to replicate that in Nim too, and with careful coding the runtime efficiency of both languages can be virtually identical.
Further links of interest
The SSE2 instruction set was introduced in 2001 with the Pentium 4, so virtually every x86 family processor supports it today. Note that this is 64-bit code, which you can easily spot because registers XMM8 through XMM15 are only available for 64-bit. ↩
Not that I would consider Nim a low-level language, quite on the contrary! It’s as enjoyable and fast to code in Nim as in Python, but with the added benefit of type safety which is not a hassle thanks to Nim’s excellent type inference. I think of Nim as a high-level language with the possibility of going low-level when necessary, which is exactly what I want from a general purpose programming language. ↩ | http://blog.johnnovak.net/2017/04/22/nim-performance-tuning-for-the-uninitiated/ | CC-MAIN-2017-30 | refinedweb | 3,916 | 57.81 |
I’d like to get the last line from a big gzipped log file, without having to iterate on all other lines, because it’s a big file.
I have read Print Last Line of File Read In with Python and in particular this answer for big files, but it does not work for gzipped file. Indeed, I tried:
import gzip with gzip.open(f, 'rb') as g: g.seek(-2, os.SEEK_END) while g.read(1) != b'n': # Keep reading backward until you find the next break-line g.seek(-2, os.SEEK_CUR) print(g.readline().decode())
but it already takes more than 80 seconds for a 10 MB compressed / 130 MB decompressed file, on my very standard laptop!
Question: how to seek efficiently to the last line in a gzipped file, with Python?
Side-remark: if not gzipped, this method is very fast: 1 millisecond for a 130 MB file:
import os, time t0 = time.time() with open('test', 'rb') as g: g.seek(-2, os.SEEK_END) while g.read(1) != b'n': g.seek(-2, os.SEEK_CUR) print(g.readline().decode()) print(time.time() - t0)
Answer
If you have no control over the generation of the gzip file, then there is no way to read the last line of the uncompressed data without decoding all of the lines. The time it takes will be O(n), where n is the size of the file. There is no way to make it O(1).
If you do have control on the compression end, then you can create a gzip file that facilitates random access, and you can also keep track of random access entry points to enable jumping to the end of the file. | https://www.tutorialguruji.com/python/how-to-efficiently-read-the-last-line-of-very-big-gzipped-log-file/ | CC-MAIN-2021-43 | refinedweb | 286 | 79.9 |
2.8 Method Invocation
One of the most hotly debated topics within the JSTL expert group was whether the expression language should let you invoke arbitrary methods.
The major point of contention was whether that ability fit the philosophy of the expression language and whether it would encourage Java code in JSP pages. As you may have discerned so far and as you will learn more about as you explore JSTL actions throughout the rest of this book, the expression language and JSTL actions are implemented so that developers don't need to be concerned with types; for example, you iterate over a list, array, or comma-separated string in exactly the same fashion, without regard to their types, with the <c:forEach> action and EL expressions. If you could also invoke arbitrary methods on objects, that capability could compromise that intent and would open the door to another kind of expression language that contains EL expressions and Java statements.
The final decision for JSTL 1.0 was to disallow direct method invocation in the expression language.16 You can only indirectly invoke a strict subset of methods for certain kinds of objects by specifying JavaBeans property names or array, list, or map indexes; see "A Closer Look at the [] Operator" on page 56 for more information.
Although that decision was probably for the best, you can still run into the need for method invocation pretty quickly; for example, consider the JSP page shown in Figure 211, which accesses the first item in a list.
Figure 211 Accessing the First Item in a List
The JSP page shown in Figure 211 is listed in Listing 2.24.
Listing 2.24 Accessing the First Item in a List
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Invoking Methods</title> </head> <body> <%@ taglib</b> </body> </html>
The preceding JSP page is simple: In a scriptlet, it creates a linked list and stores that list in page scope under the name list. Subsequently, the expression ${list[0]} is used to access the first item in the list, and the output is item one.
So far, so good. But what if you want to access the last item in the list? To do that, you need to know how many items are in the list so that you can specify the proper position in the list. If you look at the Java documentation for the LinkedList class, you'll see that it has a size method that returns the number of items in the list. You might try to access the last item in the list like this:
<%-- Beware! this code will throw an exception --%> The list starts with <b><c:out</b> and ends with <b><c:out</b>
As you might guess, the preceding code fragment will throw an exception like the one shown in Figure 212.
Figure 212 Trying to Access the Last Item in a List
The problem is that we are trying to invoke the list's size method (which is a valid LinkedList method), but it's not a JavaBeans-compliant getter method, so the expression list.size-1 cannot be evaluated.
There are two ways to address this dilemma. First, you can use the RT Core library, like this:
<c_rt:out
Second, if you want to avoid Java code in your JSP pages, you can implement a simple wrapper class that contains a list and provides access to the list's size property with a JavaBeans-compliant getter method. That bean is listed in Listing 2.25.
Listing 2.25 WEB-INF/classes/beans/ListWrapper.java
package beans; import java.util.List; public class ListWrapper { private List list; // JavaBean accessors for first name public ListWrapper(List list) { this.list = list; } public List getList() { return list; } public int getSize() { return list.size(); } }
The preceding wrapper class has two JavaBeans properties: list and size; the former provides access to the list, and the latter provides access to the list's size. Listing 2.26 lists a JSP page that uses one of those wrappers.
Listing 2.26 Using a Wrapper to Access an Object's Properties
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Invoking Methods</title> </head> <body> <%@ taglib</b> and the last item is <b> <c:out </b> <p> Here are all the items in the list: <p> <ul> <c:forEach <li><c:out</li> </c:forEach> </ul> </body> </html>
Like the JSP page listed in Listing 2.24 on page 87, the preceding JSP page creates a list and populates it. But this time, the list is stored in a wrapper and the wrapper is stored in page scope. The JSP page accesses the list with the expression listWrapper.list and accesses the list's size with the expression listWrapper.size.
The JSP page listed in Listing 2.26 is shown in Figure 213.
Figure 213 Using a JavaBeans Wrapper to Access a List's
Size
The JSP page shown in Figure 213 and listed in Listing 2.26 displays the first and last items in the list and iterates over all of the items in the list. See "Iteration Actions" on page 150 for more information about iterating over collections. | http://www.informit.com/articles/article.aspx?p=30946&seqNum=8 | CC-MAIN-2018-30 | refinedweb | 875 | 68.3 |
I can't understand how these 'nested' loops work. Can anyone try explain to me in the most simplest form why they are needed and how they work?
Printable View
I can't understand how these 'nested' loops work. Can anyone try explain to me in the most simplest form why they are needed and how they work?
What is printed out when the code is executed?
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
How is the value of the variable: star changed to the digits that you posted as the program's output?
Sorry wrong code, edited now.
Looks the same to me.
Thats it now,
Have you tried playing computer with the code? Use a piece of paper to write down the values of the variables as each statement is executed.
I just need to know what happens in nested loops, not that particular program, I mean if a loop loops something 10 times and a loop outside it loops 5 times does this mean that the inside is looped 50 times?
5*10 = 505*10 = 50Quote:
inside is looped 50 times
The compiler reads from top-down, so it will enter the outer for-loop and executes the code inside of it (i.e. inner for-loop). Once the inner for-loop has finished iterating, the outer for-loop iterates once more and executes the inner for-loop again. This continues until the outer for-loop has finished iterating.
Here's a very simple example I made on the spot:
Code Java:
import java.util.Scanner; public class something { public static void main(String[] args) { Scanner input = new Scanner(System.in); while(true) { System.out.println("Enter 'play' to play or 'no' to not play"); String data = input.nextLine(); if(data.equalsIgnoreCase("no")) { break; } while(data.equalsIgnoreCase("play")) { // more code } } } }
If the user enters "no", then the outer loop ends and the code within the inner loop is never executed. On the other hand, if the user enters, "play", then the code within the inner loop is executed. If the user enters anything else, then the inner loop is not executed and since there is no else statement with the if-statement, the outer loop re-iterates until the user enters valid input.
Not all programs will use nested loops, you only have nested loops in your program if it requires them. There generally are many ways of writing code to achieve the same functionality. | http://www.javaprogrammingforums.com/%20java-theory-questions/24149-nested-loops-printingthethread.html | CC-MAIN-2015-48 | refinedweb | 416 | 72.16 |
JavaOne: A lot of hype, not a lot of technical details. That was my impression of the four days following the third-year anniversary of Java's Internet debut for public consumption (March 23, 1995). And yet, one thing stood out at the conference and captured my imagination: The Ring. Not just any ring, mind you. No, this was the Java Ring, and unlike the umpteen million bulky class rings from forgotten alma maters that it might resemble, the Java Ring ring is special. It runs Java code. Yup, read that again: It runs Java code.
The mind whirls and disbelief sets in. "You mean it stores code that can be run by another program, right?" No, I mean it actually executes its own form of Java bytecode, right there on the ring. I'll pause for a moment and let that sink in...
OK, welcome back. Yes, it's a nerd's holiest-of-holy toys. It's a secret decoder ring that actually decodes. And then the second bombshell hits: It does world-class encryption. Not that letter-substitution stuff that the ring you got out of yesterday's Cheerios box did. It can do 1024-bit RSA public key encryption. Whoa, the head spins. (No, not like the infamous spinning-heads applet. I feel the spinning.)
A sordid tale of sleepless nights (in four acts)
Day 1: The beginning
I live in the "south bay," that part of the San Francisco Bay Area that really isn't on the peninsula but still wants to seem more upscale than San Jose. We call it the south bay, and its only 45 miles or so from the Moscone Center, the site of JavaOne. Of course, most tourists tend to think San Francisco is the Bay Area -- but Silicon Valley is the true heart of the Bay Area, and north of here is the City.
What that means for me is that JavaOne is close enough that I can't get my company to put me up in a hotel, and far enough that it takes some planning to get there on time. For that, we've got the Caltrain. A commuter rail service that runs up through the southern part of the Bay Area to a train station that's just far enough away from the Moscone Center to make for an annoying walk or an overpriced cab ride. I walked on Tuesday morning and got to Moscone on time, only to realize that the line out the door was for pre-registered folks such as myself: So much for making the beginning of the keynote speech. So I stand in line, get my badge and finally rush into the "overflow" room to watch the keynote on TV. Now, I don't know about you, but I'm not a big fan of paying ,200 to go to a conference just to watch the keynote address on TV. All the same, halfway through James Gosling's talk (voted Best Keynote by yours truly), he asked who among the audience had their ring.
"What ring?" I said.
"The one that runs Java," said James.
Well, out the door in a flash, and back to the materials center. "Have you heard about the ring?!?" I present my badge and ticket and voilà!, I'm looking at my new Java Ring. Back to the big TV room just in time to catch James explaining how the ring can hold your business card information and we'll all soon be running the Fractal game on it.
Now my curiosity is really piqued and I can't find out any more about this thing, so after the first technical session I'm off to the Java Pavilion (read: hype bazaar). And there, in an innocuous-looking booth, is Dallas Semiconductor, and -- lo and behold! -- its reps are selling something that looks like it goes with the Java Ring. They are! It's the reader and adapter for your computer. Only 5. So I plunk down the plastic and walk out with a Blue Dot reader. Nearly beside myself with excitement, I find that you can download the demo code from. Which, when I get home that night (after the Java Pavilion cocktail party), I promptly attempt.
Of course, if life were fair I'd be done, but it isn't, and I wasn't. The Web site had been misconfigured; my browser assumed the tarred and gzipped file was text, and downloading it resulted in el-junko. Sigh. I remembered, however, that the machines in the Hackers' Lab had ring readers, and the next morning I resolved to set about finding out how they worked.
Day 2: To ask permission is to seek denial
It's Wednesday morning. I listen half-heartedly to the keynote address (the Ed-and-Scott show); Zander and McNealy are remarkably composed given the injunction handed down the day before. (See the JavaWorld news article, "Sun's Scott McNealy and Alan Baratz discuss preliminary ruling in MS/Sun suit," referenced in the Resources section below.) As soon as the talk is over I go out to the Hackers' Lab and start exploring one of the machines. Sure enough, there's a file called jibkit07.tar on the machine, and therein I find a bunch of Java source code related to the Java Ring (conveniently located in a directory called javaring).
Exploring further, I found the source to the BusinessCard applet and the Fractal applet. Unfortunately, whenever I plugged my ring into the button, a bogus applet came up with only the show choices. Hmmm, not good. So (like any good hacker) I used the copy of Netscape that was running on the box and mailed the .tar file to my home machine. So much for the download problem.
I then trekked across the pavilion to catch the tail-end of the talk Dallas Semiconductor was giving about the ring. I was too late to catch the whole thing, but good info nonetheless.
Wednesday evening was the JavaWorld party. Quite fun, and I was glad to meet many readers and some of the other authors I knew of only by name, and my editor, Jill Steinberg, whom I'd never met face to face. But on my mind was the ring, always the ring.
At home, around midnight, I fired up my development environment and started hacking. I immediately ran into problems, however. Suspecting my JDK 1.1.2 release, I started downloading the 1.1.5 release over a 33-kilobit per second modem -- ugh! About 15 minutes into the download I remembered that all JavaOne attendees were given the Java Developer CD at the show, so I dug it out. There was the 1.1.5 JDK. Whoo-hoo! Back in business.
I struggled unsuccessfully for another hour and a half trying various things to get my Java Ring to respond to the
apduGUI program in the Toolkit. No joy. Couldn't even get it to start. My classpath was full of so many jar files it couldn't be typed in the DOS command line. Then a typo got the
apduGUI program to come up. It turns out the Developer Kit has an extra copy of
java.lang.Object in it, whoops. After fixing that I got the programs to come up, but they still wouldn't talk to my ring. I resigned in disgust at about 3:30 a.m. Up at 6:00 a.m. for day three.
Day 3: He went thatta way!
Day three started a bit slowly. I actually woke up at 6:00 a.m., turned off my alarm and then got out of bed around 9:00 a.m. So much for the panel of experts on the future of Java. That was OK; I arrived in time to attend JavaWorld columnist and Sun engineer Rinaldo Di Giorgio's talk on smart cards. That was helpful and explained what some of the terms -- such as APDU -- I'd been reading about in the ring docs meant. Armed with new knowledge, I went hunting for a Dallas Semiconductor application engineer.
These guys turned out to be harder to find than I would have expected. I finally tracked one down in the Hackers' Lab and talked to him about my lack of success so far. Once we got down to specifics, we discovered I had hooked my ring to COM3, but the library only knows about COM1 and COM2. For those of you who don't have Windows-based computers, these are serial ports. For those of you who work at Sun, the answer to your next question is, Yes, you can have up to four serial ports.
This points out something rather annoying: Sun doesn't know all that much about Wintel machines. Now, it wouldn't be so bad for Sun to claim ignorance on this topic, but JavaSoft is supposed to be a cross-platform company, supporting everything from jewelry to supercomputers. Guess it will just have to fill in a few gaps.
Thursday night, of course, was the big JavaOne party, dubbed "Retro & Beyond." Given that somebody made 0-million on JavaOne, the party sucked. For what I was paying, I would have expected to see the Starship playing on the Retro side of the house while Nine Inch Nails blasted through the Beyond side. No such luck. At least the conversation was good, and the video games on the Retro side were fun as well. More ring discussions were pursued, and by the time I got home, just after midnight, I had a couple more tricks to try.
I moved my Blue Dot reader over to COM2 and downloaded the freshly released java.comm package from the Java Developer Connection Web site. I wrote the following simple class:
import javax.comm.*; import java.util.*; import java.io.*; public class test { public static void main(String args[]) { CommPort te = null; for (Enumeration e = CommPortIdentifier.getPortIdentifiers(); e.hasMoreElements(); ) { CommPortIdentifier cp = (CommPortIdentifier) e.nextElement(); if (cp.getName().compareTo("COM2") == 0) { try { te = cp.openPort("Test", 500); } catch (Exception ee) { System.out.println("Port in use, sorry.\n"); te = null; } } System.out.println("Available port : "+cp.getName()); } if (te != null) { OutputStream os; try { os = te.getOutputStream(); } catch (Exception e3) { os = null; } if (os == null) { te.closePort(); System.exit(1); } PrintStream ps = new PrintStream(os); for (int i = 0; i < 10; i++) { ps.println("This is a test "+i); } te.closePort(); } } }
And it confirmed my fears: The Java communications framework knows only about LPT1, COM1, and COM2 on Win95 machines. Ouch. I still couldn't get the test program
apduGUI to work, and I was getting desperate. I decided to try one of the others. As chance would have it, I tried the BusinessCard demo by starting up the
BusinessCardDisplay class that was part of the Examples directory.
After much gnashing of teeth (and messages about timeouts and searching for drivers), I got the BusinessCard display up, and -- lo and behold! -- it found my ring and displayed my data! Success! If it weren't two in the morning I might have jumped for joy. As it was, my elation was somewhat muted. I set about fixing my card such that my coffee preference was listed as Dr. Pepper -- I don't drink coffee. I hacked the
BusinessCardDisplay applet and "fixed" it such that I could store my preferences in the ring. Then off to bed.
Day 4: Disaster and redemption
I woke on day four bleary-eyed and perhaps a bit hung-over. Partying, hacking, and not sleeping are not conducive to clear thinking. I did manage, however, to struggle out of bed and get to the conference. The crowd was significantly reduced, and I checked right away to see if I could show off my new "coffee preference" on the JavaStations at the show. It worked great, much to the annoyance of the folks running the coffee shop demo. (They were taking orders by having us put our rings in their reader; then they would serve your preferred coffee. Of course, my ring ordered Dr. Pepper. Lots of laughs.)
By now the folks running the TV/set-top box thingies with Blue Dot readers had them up and running. I thought it would be neat to show off my ring modifications. Unfortunately, I hadn't bothered to check out the interface first; in fumbling around got to the back end of the personalize-your-ring page, my ring was "personalized" with the previous user's information. Yuck! Now, not only did my ring not contain my kewl new beverage preference, it didn't even look like it belonged to me!
The guys at the TVs were no help at all, so I went looking for a Dallas Semiconductor engineer. No joy there -- they were all headed to Dallas (or wherever they go when they aren't at the Moscone Center). Then I found out that the Java Lobby guys had out-hacked me. They were using the BusinessCard applet to not only modify attendee's rings, but to register folks for the Java Lobby. I took the opportunity to reprogram my ring. Of course, they hadn't added the preference hack, so I was able to reclaim my personal information, but not my Dr. Pepper preference.
JavaOne slowly wound down. I ended up getting a jewelry-style ring (one that would fit my plump digit) and went home for some much-needed sleep.
Epilogue
There is no moral to this story, except perhaps that if you don't sleep you may catch a cold (I did). Over the weekend I was able to delve deeper into the code that runs the ring. Some useful resources are the JavaCard documents on the java.sun.com Web site, and of course the two articles in this issue of JavaWorld (April 1998). And, for those of you who are electron-pushers like myself, the Dallas Semiconductor application note on the serial interface (App74) is quite interesting as well. (See the Resources section below for links to these useful resources.)
I've started playing with the crypto code and hope to have a real secret coder ring running by the time you read this. The current ring has 6 kilobytes of RAM; Dallas Semiconductor claims it could do more than 128 kilobytes in the same package. That's the ring I'd really like to see. | http://www.javaworld.com/article/2076652/ring-fever--a-first-hand-look-at-java-powered-jewelry.html | CC-MAIN-2014-42 | refinedweb | 2,411 | 73.88 |
In this section you will learn how to count the number of vowels in String. Here you will ask to enter a string of your own choice and then you will get the number of vowels count.
Description of code : In this code first you will ask to enter the string through scanner class and compiler will read the string once you enter the string. Then we have taken a count variable which is initialized to 0. Now we have applied a loop here which will go up to length of string input and inside loop checking each character with if condition for vowel, if it is vowel, count is incremented, prints the no of vowel. to console.
Example : A Code to count the number of vowel in a string.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class Check { public static void main(String args[]) throws NumberFormatException, IOException { System.out.println("Enter the character"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); int count=0; System.out.print("Vowel are = "); for(int i=0;i<input.length();i++) { char ch=input.charAt(i); if(ch=='e'||ch=='o'||ch=='i'||ch=='a'||ch=='u'||ch=='O'||ch=='I'||ch=='E'||ch=='O'||ch=='A') count++; } System.out.println(count); } }
Output : After executing the count vowels
Post your Comment | http://www.roseindia.net/java/string-examples/count-vowels-inJava.shtml | CC-MAIN-2016-07 | refinedweb | 230 | 60.82 |
#include <sys/conf.h> #include <sys/ddi.h> #include <sys/sunddi.h> int ddi_segmap(dev_t dev, off_t offset, struct as *asp, caddr_t *addrp, off_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *credp);
int ddi_segmap_setup(dev_t dev, off_t offset, struct as *asp, caddr_t *addrp, off_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *credp, ddi_device_acc_attr_t *accattrp, uint_t rnumber);
These interfaces are obsolete. See devmap(9E) for an alternative to ddi_segmap(). Use devmap_setup(9F) instead of ddi_segmap_setup().
The device whose memory is to be mapped.
The offset within device memory at which the mapping begins.
An opaque pointer to the user address space into which the device memory should be mapped.
Pointer to the starting address within the user address space to which the device memory should be mapped.
Length (in bytes) of the memory to be mapped.
A bit field that specifies the protections. Some combinations of). If (maxprot & prot) != prot then there is an access violation.
Flags indicating type of mapping. Possible values are (other bits may be set):
Changes are private.
Changes should be shared.
The user specified an address in *addrp rather than letting the system pick and address.
Pointer to user credential structure.
Pointer to a ddi_device_acc_attr(9S) structure which contains the device access attributes to apply to this mapping.
Index number to the register address space set.:
Successful completion.
An error occurred. In particular, they return ENXIO if the range to be mapped is invalid.
ddi_segmap() and ddi_segmap_setup() can be called from user or kernel context only.
See attributes(5) for a description of the following attributes:
mmap(2), attributes(5), devmap(9E), mmap(9E), segmap(9E), devmap_setup(9F), cb_ops(9S), ddi_device_acc_attr(9S)
Writing Device Drivers for Oracle Solaris 11.2 | http://docs.oracle.com/cd/E36784_01/html/E36886/ddi-segmap-9f.html | CC-MAIN-2016-18 | refinedweb | 286 | 60.72 |
I couldn't find one central thread about this, so let's get everyone's opinion in one place!
Let's discuss what language is best for absolute beginners to learn. These beginner programmers will be learning the very basic aspects of software development; logic, debugging, problem solving, etc..
In the poll, I tried to group similar languages together. There is really no point having separate categories for C# and Java in this context. If there are any languages that do not fit in the poll, or if you cannot decide what category your language fits in, please post and hopefully I can have the poll amended.
I'll start with my opinion, which I have copied from a post I just made in one of these "* as a first language" topics:
c0mrade said:
C is a very simple language, and will let you learn the basic skills of a programmer, such as logic and debugging, without having to learn more than you need to.
For example, in Java, just to say hello world you need to create a class ("public class MyApp { ..."), add a method that is both "public" and "static", then write the call to print "hello world". The problem with this is that beginning programmers have no what a class is and why it is needed, and they have no idea why the method should be public and static. Plain old C has none of this overhead.
That said, I don't think it really matters that much. Starting out will be tough, but we all get through it one way or another. It's just about how easy those first steps will be. Also, I'm sure the best choice greatly varies from person to person.
This post has been edited by c0mrade: 25 April 2009 - 10:01 AM | http://www.dreamincode.net/forums/topic/101582-the-best-first-programming-language/ | CC-MAIN-2018-22 | refinedweb | 303 | 78.18 |
Hi there!
Welcome to the second part of my article series. Unless you have already done so, I suggest reading the first part for starters, as this second part will rely quite heavily on the fact that you already have the necessary tools and technologies installed.
In this part of the series, we will delve on the following issues. For some of you readers, it might feel strange that the writing of pure .NET applications doesn't come until now, but like the first part stated, this series is meant for those developers who already have a grasp on how Windows applications were written before the Whidbey compiler generation.
Our topics for tonight's discussion (yes, this article was written during the night) are as follows:
Without further delay, let's get started!
A few people who have read my first article sent in e-mails asking how they should proceed if they didn't want to use the Platform SDK. Like most of you already know, the VC++ Express contains a set of wizards, from which you can even find a Windows Forms application wizard. But, like you have already noted, I don't like using those wizards. Yes, they generate efficient skeletons, but the whole concept of learning how C++/CLI works requires that we sometimes write our applications from ground up.
So, go ahead, fire up your VC++ and create a new project. Its type should be .NET and the template Empty Project sounds suitable. For the name, give in Hello_CLI_3. The wizard will generate the folders for the solution and then you're dropped into the Solution Explorer view.
Now, as we are in the process of writing a pure .NET application, there are certain project settings that need to be altered in order for the builds to get targeted correctly. Here is a list of the settings, their locations, and the values they should be set to: (to access project properties, right-click on the project name, and choose Properties.)
Back in the Solution Explorer, it's time to add support for the .NET Framework. This time, we will do it completely manually, so right-click on the project name and choose .NET References. Locate a button called Add New Reference and click on it. From the list that is presented, add the System.dll and System.Windows.Forms.dll into your project, then click on OK, and close the Properties window.
Now, it's time to add actual code into our project. Add a new source file, and name it Main.cpp. Into this file, paste the following code fragment:
using namespace System;
int Main(void)
{
// Display a simple messagebox
System::Windows::Forms::MessageBox::Show( L"Welcome to C++/CLI", "TestApp",
System::Windows::Forms::MessageBoxButtons::OK );
// End the application
return 0;
}
Go ahead, compile and execute this program. You can see it starts up, pops a message box, and closes down. There it is, our very own, pure .NET application, alive and kicking. Like you can see, I prefer to use the full namespace of every class I use. This helps me learn where and how which object resides. Naturally, you could, at the start of the file, place the following line:
using namespace System::Windows::Forms;
The result of this would be that you wouldn't need to include this namespace in the code anymore. You could just call MessageBox::Show(), and specify MessageBoxButtons::OK as the parameter.
MessageBox::Show()
MessageBoxButtons::OK
Remember how we defined the entry point of the application in the linker settings? Now, you can see the effect. If we did not define this entry point, the linker would look for the WinMain entry point again. Using this approach, the .NET Framework is used to initialize the application and the thread, then call our entry-point function to allow the execution to begin.
WinMain
On our next section, we will dive into the process of writing a bit more complicated user interface. Our interface will present us with a MDI Frame form, a toolbar, and a single child form.
To get started, again create a new blank .NET project, naming it Hello_CLI_4. And following the familiar steps from above, setup the settings for the linker. Then add .NET References, this time only System.dll is needed. Add a new source file, and write the Main function, making it only return, and nothing else.
Main
Now, it's time to introduce the Forms. Add a new UI -> Windows Form item into the project. Name this form as Form_P. After a few minutes of thinking, you are presented with the Form Designer. Now, go to Solution Explorer and delete the Form_P.cpp file. This one is not needed for our purposes.
Form_P
Back in the Form Designer, right-click on the Form and choose Properties. From the Properties window, scroll to Appearance -> Text and change this property to The MDI Example. Next, scroll again to find Window Style -> IsMDIContainer and set this one to True. You can instantly see how our Form starts to look different. For a reference, here's a picture of what the form should look like when these settings are done.
In the .NET Framework environment, the concept of bars seems to be misplaced somewhere, and is replaced by the concept of Strips. A menu bar is represented by a MenuStrip component. A toolbar is called a ToolStrip, and a status bar is a StatusStrip. Also, the behavior of all these has changed a lot.
MenuStrip
ToolStrip
StatusStrip
Let's start by adding a MenuStrip. Drag it on the form. You can easily add and remove menu topics by clicking on the Type Here section and writing a menu topic. For this example application, create a File menu and a Help menu. Under the first one, add an item called Exit, and under the second one, an item called About MDI Example. If, at some point, the program will auto-generate code fragments and drop you into the Form_P.h's code view, then don't panic. Just delete the auto-generated code section and return to the Designer view. The safest way is to use the right-click to select an item.
When done, you should be left out with something like the following image represents:
Now is the time to name these items. As I have a solid background on Windows programming, I've grown quite fond with using the ID designations. So, click on the MenuStrip at the gradient section, and spot a small right-pointing arrow at its right end. Click on this arrow, and a quick-select Actions menu is popped open. From here, select Edit Items.
You are now taken to the Items Collection Editor window, from where you can quickly change the properties of each of the menu items. First, choose the File menu topic, browse to its Design -> Name section, and rename it to ID_FILE_MENU. Similarly, rename the Help menu topic to ID_HELP_MENU.
ID_FILE_MENU
ID_HELP_MENU
To access the individual menu items' properties, click on the desired menu topic, and scroll to Data -> DropDownItems and click on the More button (the one with three dots on it). You will be taken into a similar Items Collection Editor window, but this time focusing on the individual menu items. To navigate backwards, click on OK. Using this knowledge, go and change the IDs of the menu items to ID_FILE_EXIT and ID_HELP_ABOUT, respectively. Also, if you wish, then on both of the menu items, you can scroll to Behavior -> ToolTipText and enter a descriptive tooltip for both of them.
ID_FILE_EXIT
ID_HELP_ABOUT
When finished, return to the Form Designer and click on the right-pointing arrow again to close the Actions menu.
Adding a StatusStrip is quite a breeze. Just drag & drop it on the form. Type into the Type Here section and add a new Panel named Ready.... Right-click on this Panel and edit its properties again. To setup this Panel to display text only, and look correct, you should modify its properties according to this list:
Panel
Name
ID_STATUS_TEXT
Display Style
Text
TextAlign
MiddleLeft
AutoSize
False
Width
200
Now, our parent form is completed, and you should be resulted with something like the following image represents:
Now, it's time to start working on what all stuff the form can do. The easiest way to manipulate the events is to use the Properties window. On the top of this window, you can always see the name/ID of the object currently being edited. Going through all these in an orderly fashion, add handlers to the following events for the menu items (not menu topics).
Click
OnClicked_XXX
MouseEnter
OnEnter_XXX
MouseLeave
OnLeave_XXX
First, let's tackle the Click events. For the Exit menu item, we will again exit the Form by calling:
private: System::Void OnClicked_Exit(System::Object^ sender,
System::EventArgs^ e)
{
// Exit the form
Application::Exit();
}
The About menu item will display a message box showing a nifty error code:
private: System::Void OnClicked_About(System::Object^
sender, System::EventArgs^ e)
{
// Display a message box
MessageBox::Show( L"About-box for this application", L"About The MDI Example",
MessageBoxButtons::OK );
}
The MouseEnter and MouseLeave events are used to modify the text displayed by the status strip. The idea is that when mouse enters the item, the tooltip of the menu item is displayed on the status panel. To support this functionality, the code fragment for the MouseEnter events should be as follows:
private: System::Void OnEnter_Exit(System::Object^
sender, System::EventArgs^ e)
{
this->ID_STATUS_TEXT->Text = this->ID_FILE_EXIT->ToolTipText;
}
And for the MouseLeave, it should be:
private: System::Void OnLeave_Exit(System::Object^
sender, System::EventArgs^ e)
{
this->ID_STATUS_TEXT->Text = L"Ready...";
}
Remember that for the Help item, the text is different. You can use the ID you gave it to access its ToolTipText property.
ToolTipText
Our last step is to add the necessary code calls to make our form live and breathe. Save all changes and close the Form Designer and the form header file. Go back to the Solution Explorer and the source file you added. Include the header file for the form, and inside the Main function, add the familiar two calls. The resulting file should look something like this:
#include "Form_P.h"
using namespace System;
using namespace System::Windows::Forms;
int Main(void)
{
// Enable visual styles and run the form
Application::EnableVisualStyles();
Application::Run( gcnew Hello_CLI_4::Form_P() );
return 0;
}
Now, go and execute the application. Use the menu items, see how the status text changes when you enter/exit the menu item areas.
Phew! That was a serious amount of coding, good to know that all of you were patient enough to follow me through it all. I hope this article was helpful to you on your way to get everything started.
In the next article of the series, we'll dive even more deeper into the world of MDI Forms, adding a ToolStrip. As a sugar in the bottom, we'll also take a look of how easy the COM usage has become in the new language | http://www.codeproject.com/Articles/8078/Hello-Cplusplus-CLI-Part-2 | CC-MAIN-2014-10 | refinedweb | 1,847 | 72.26 |
matplotlib.pyplot is a collection of command style functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: eg, create a figure, create a plotting area in a figure, plot some lines in a plotting area, decorate the plot with labels, etc.... matplotlib.pyplot is stateful, in that it keeps track of the current figure and plotting area, and the plotting functions are directed to the current axes
import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show()
(Source code, png, hires.png, pdf)
You may be wondering why the x-axis ranges from 0-3 and the y-axis from 1-4. command, and will take an arbitrary number of arguments. For example, to plot x versus y, you can issue the command:
plt.plot([1,2,3,4], [1,4,9,16]) ‘b-‘, which is a solid blue line. For example, to plot the above with red circles, you would issue
import matplotlib.pyplot as plt plt.plot([1,2,3,4], [1,4,9,16], 'ro') plt.axis([0, 6, 0, 20]) plt.show()
(Source code, png, hires.png, pdf)
See the plot() documentation for a complete list of line styles and format strings. The axis() command; eg.
import numpy as np import matplotlib.pyplot()
(Source code, png, hires.png, pdf)
The figure() command here is optional because figure(1) will be created by default, just as a subplot(111) will be created by default if you don’t manually specify an axes. The subplot() command specifies numrows, numcols, fignum where fignum, ie,: line_styles)
import numpy as np import matplotlib.pyplot as plt mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) # the histogram of the data n, bins, patches = plt.hist(x, 50, normed. | https://matplotlib.org/1.3.0/users/pyplot_tutorial.html | CC-MAIN-2022-21 | refinedweb | 303 | 69.18 |
Hi, If CONFIG_HUGETLB is not defined, you get a RAW dependency clash in ivt.S. (2.5.39) I believe this patch should fix it (but I'm not an IA64 assmebler language expert!) # This is a BitKeeper generated patch for the following project: # Project Name: Linux kernel tree # This patch format is intended for GNU patch command version 2.5 or higher. # This patch includes the following deltas: # ChangeSet 1.851 -> 1.852 # arch/ia64/kernel/ivt.S 1.10 -> 1.11 # # The following is the BitKeeper ChangeSet Log # -------------------------------------------- # 02/10/16 peterc@gelato.unsw.edu.au 1.852 # Fix RAW dependency when CONFIG_HUGETLB_PAGE is not defined. # -------------------------------------------- # diff -Nru a/arch/ia64/kernel/ivt.S b/arch/ia64/kernel/ivt.S --- a/arch/ia64/kernel/ivt.S Wed Oct 16 10:14:27 2002 +++ b/arch/ia64/kernel/ivt.S Wed Oct 16 10:14:27 2002 @@ -116,8 +116,8 @@ ;; (p8) dep r25=r18,r25,2,6 (p8) shr r22=r22,HPAGE_SHIFT-PAGE_SHIFT - ;; #endif + ;; cmp.eq p6,p7=5,r17 // is IFA pointing into to region 5? shr.u r18=r22,PGDIR_SHIFT // get bits 33-63 of the faulting address ;;Received on Tue Oct 15 17:15:47 2002
This archive was generated by hypermail 2.1.8 : 2005-08-02 09:20:10 EST | http://www.gelato.unsw.edu.au/archives/linux-ia64/0210/3964.html | CC-MAIN-2020-24 | refinedweb | 217 | 59.9 |
If this template helps then use it. If not then just delete and start from scratch.
OS (e.g. Win10): Win10
What are you trying to achieve?:
I’m trying to make an event related(trial by trial) stroop task. So, I want stroop tasks to appear for half of the trials, and not to appear for rest of the trials.
Two numbers of different size and value will appear in ‘wm_s’ routine each at left and right corner of the screen and they are designated as text_13 and text_14.(For example, big 2 at left and small 5 at right)
And in ‘wm_r’ routine, I will show one word, either ‘value(값)’ or ‘size(숫자크기)’ which is text_15 and ask them to press left or right according to which side’s value/size was bigger.(For example, if value appears, then the participant will have to press ‘right’ because the value of 5 is bigger than 2)
For this, I have put
text_13 - size $si1 text $str1 opacity $p
text_14 - size $si2 text $str2 opacity $p
text_15 - text $strque opacity $q
And at begin routine tab in wm_s i have put
import random stroop=[1,2,3,4,5,6,7,8,9] si=[0.06,0.2] stroop1= random.sample(stroop, 2) stroop2=random.sample(si, 2) str1=stroop1[0] str2=stroop1[1] si1=stroop2[0] si2=stroop2[1]
At the begin routine tab in wm_r, I have put
import random strques=['값','글자크기'] strque=random.sample(strques,1) strque=strque[0] if strque=='값': if str1>str2: strans='left' if str1<str2: strans='right' if strque=='글자크기': if si1>si2: strans='left' if si1<si2: strans='right'
The problem is that, I want to synchronize the opacity of text_13, text_14, text_15, so that when text_13 and text_14 appears, then text_15 also appears and vice versa. However, now texts in those two routines doesn’t synchronizes. Can you help me out?
This is the workflow of my experiment
This is the condition file I inserted in trials_2. question/answer are the items that goes in pavinst_s and pavinst_r routine.
What did you try to make it work?:
What specifically went wrong when you tried that?:
Include pasted full error message if possible. “That didn’t work” is not enough information. | https://discourse.psychopy.org/t/stroop-task-in-event-related-design/5882 | CC-MAIN-2021-39 | refinedweb | 382 | 71.85 |
Hi, On Thu, 08 Sep 2016 15:39:57 +0200 Johannes Schauer <josch@debian.org> wrote: > On Thu, 30 Jun 2016 13:12:16 -0700 Ben Longbons <brlongbons@gmail.com> wrote: > > Now that the kernel supports user_namespaces(7), it should be possible to > > debootstrap in them. Some small changes are needed. > > > > Configuration needed: > > * Kernel 3.8 or later (3.11 recommended) > > * Set the sysctl kernel.unprivileged_userns_clone to 1 > > (Debian-specific "temporary" patch from years ago). > > * Install the `uidmap` package and add yourself to /etc/sub[ug]id > > * Install the `lxc` package (for one helper binary only) > > * Make sure the current directory is searchable by other. > > > > I have attached the necessary changes as a wrapper script, > > I find your script highly interesting! > > A year ago I tried to write a tool that combined the powers of > lxc-usernsexec(1) and unshare(1) because I was unable to combine them in a way > that would give me both: correct mapping of user and group ids as well as > unsharing the user namespace and others. I blogged about it here: > > > > and the code is here: > > > > I do not know whether what you demonstrated now in shell already worked one > year ago (in particular I was not aware of the lxc-unshare tool) but your > script works fine for me. I'm happy that it seems that I don't have to further > dabble with the perl code I came up with because lxc-usernsexec and lxc-unshare > seem to be able to do the major grunt work while the rest can be done in simple > POSIX shell. Thank you! The disadvantage of the lxc-usernsexec and lxc-unshare tools is, that they are part of the lxc package. See bug #847491. > I wonder though: why would this feature be useful for debootstrap? The > resulting directory would have all the wrong ownership information. The > directory would only be useful if its user knows exactly how to map the user > ids between the host and the unshared user namespace. > > So my practical question: > > How do you use the chroots that you create in this fashion? Which commands do > you use to work with them? To answer my own question: by packing up the chroot into a tarball. The files stored inside the tarball will have the correct permission. I combined the insights from your tool with the Perl script I wrote and cited above and added support to sbuild-createchroot to run debootstrap without needing sudo but using Linux user namespaces. Since debootstrap does not yet offer this functionality itself, I will carry the code as part of sbuild. See the following two commits for details: Thanks! cheers, josch
Attachment:
signature.asc
Description: signature | https://lists.debian.org/debian-boot/2018/06/msg00153.html | CC-MAIN-2019-26 | refinedweb | 449 | 64.1 |
Powerful dependency injection for iOS & OSX
Typhoon
Powerful dependency injection for Cocoa and CocoaTouch. Lightweight, yet full-featured and super-easy to use.
Not familiar with Dependency Injection?.
Usage
- Read the Quick Start for Objective-C or Swift.
- Here's the User Guide.
- 日本のドキュメンテーション
let assembly = MyAssembly().activated() let viewControler = assembly.recommendationController() as! RecommendationController
Open Source Sample Applications
- Try the official Swift Sample Application or Objective-C Sample Application.
- This sample shows how to set up Typhoon with Storyboards, Core Data and Reactive Cocoa.
Have a Typhoon example app that you'd like to share? Great! Get in touch with us :)
Installing
Typhoon is available through CocoaPods or Carthage, and also builds easily from source.
With CocoaPods . . .
Static Library
# platform *must* be at least 5.0 platform :ios, '5.0' target :MyAppTarget, :exclusive => true do pod 'Typhoon' end
Dynamic Framework
If you're using Swift, you may wish to install dynamic frameworks, which can be done with the Podfile shown below:
# platform *must* be at least 8.0 platform :ios, '8.0' # flag makes all dependencies build as frameworks use_frameworks! # framework dependencies pod 'Typhoon'
Simply import the Typhoon module in any Swift file that uses the framework:
import Typhoon
With Carthage
github "appsquickly/Typhoon"
From Source
Alternatively, add the source files to your project's target or set up an Xcode workspace.
NB: All versions of Typhoon work with iOS5 and up (and OSX 10.7 and up), iOS8 is only required if you wish to use dynamic frameworks. | https://iosexample.com/powerful-dependency-injection-for-ios-osx/ | CC-MAIN-2019-13 | refinedweb | 249 | 58.99 |
Take 40% off Microservices in .NET, 2nd Edition by entering horsdal3 into the discount code ox at checkout at manning.com.
Imagine that we have a Loyalty Program microservice.
Figure 1 shows the collaborations that the Loyalty Program microservice is involved in. The Loyalty Program subscribes to events from Special Offers, and it uses the events to decide when to notify registered users about new special offers.
Figure 1. The event-based collaboration in the Loyalty Program microservice is the subscription to the event feed in the Special Offers microservice.
We’ll first look at how Special Offers exposes its events in a HTTP based feed. Then, we’ll return to Loyalty Program and add a second process to that service, which will be responsible for subscribing to events and handling events.
Implementing an event feed
The Special Offers microservice implements its event feed by exposing an endpoint—
/events—that returns a list of sequentially numbered events. The endpoint can take two query parameters—
start and
end—that specify a range of events. For example, a request to the event feed can look like this:
GET /events?start=10&end=110 HTTP/1.1 Host: localhost:5002 Accept: application/json
The response to this request might be the following, except that I’ve cut off the response after five events:
HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 [ { "sequenceNumber": 1, "occuredAt": "2020-06-16T20:13:53.6678934+00:00", "name": "SpecialOfferCreated", "content": { "description": "Best deal ever!!!", "id": 0 } }, { "sequenceNumber": 2, "occuredAt": "2020-06-16T20:14:22.6229836+00:00", "name": "SpecialOfferCreated", "content": { "description": "Special offer - just for you", "id": 1 } }, { "sequenceNumber": 3, "occuredAt": "2020-06-16T20:14:39.841415+00:00", "name": "SpecialOfferCreated", "content": { "description": "Nice deal", "id": 2 } }, { "sequenceNumber": 4, "occuredAt": "2020-06-16T20:14:47.3420926+00:00", "name": "SpecialOfferUpdated", "content": { "oldOffer": { "description": "Nice deal", "id": 2 }, "newOffer": { "description": "Best deal ever - JUST GOT BETTER", "id": 0 } } }, { "sequenceNumber": 5, "occuredAt": "2020-06-16T20:14:51.8986625+00:00", "name": "SpecialOfferRemoved", "content": { "offer": { "description": "Special offer - just for you", "id": 1 } } } ]
Notice that the events have different names (
SpecialOfferCreated,
SpecialOfferUpdated, and
SpecialOfferRemoved) and the different types of events don’t have the same data fields. This is normal: different events carry different information. It’s also something you need to be aware of when you implement the subscriber in the Loyalty Program microservice. You can’t expect all events to have the exact same shape.
The implementation of the /events endpoint in the Special Offers microservice is a simple ASP.NET Core MVC controller.
Listing 1. Endpoint that reads and returns events
namespace SpecialOffers.Events { using System.Linq; using Microsoft.AspNetCore.Mvc; [Route(("/events"))] public class EventFeedController : Controller { private readonly IEventStore eventStore; public EventFeedController(IEventStore eventStore) { this.eventStore = eventStore; } [HttpGet("")] public ActionResult<EventFeedEvent[]> GetEvents([FromQuery] int start, [FromQuery] int end) { if (start < 0 || end < start) return BadRequest(); return this.eventStore.GetEvents(start, end).ToArray(); } } }
You may notice, that
GetEvents returns the result of
eventStore.GetEvents. ASP.NET Core serializes it as an array. The
EventFeedEvent is a class that carries a little metadata and a
Content field that’s meant to hold the event data.
Listing 2.
Event class that represents events
public class EventFeedEvent { public long SequenceNumber { get; } public DateTimeOffset OccuredAt { get; } public string Name { get; } public object Content { get; } public EventFeedEvent( long sequenceNumber, DateTimeOffset occuredAt, string name, object content) { this.SequenceNumber = sequenceNumber; this.OccuredAt = occuredAt; this.Name = name; this.Content = content; } }
The
Content property is used for event-specific data and is where the difference between a
SpecialOfferCreated event, a
SpecialOfferUpdated and a
SpecialOfferREmoved event appears. Each has its own type of object in
Content.
This is all it takes to expose an event feed. This simplicity is the great advantage of using an HTTP-based event feed to publish events. Event-based collaboration can be implemented over a queue system, but that introduces another complex piece of technology that you have to learn to use and administer in production. That complexity is warranted in some situations, but certainly not always.
Creating an event-subscriber process
Subscribing to an event feed essentially means you’ll poll the events endpoint of the microservice you subscribe to. At intervals, you’ll send an HTTP
GET request to the /events endpoint to check whether there are any events you haven’t processed yet.
We will implement this periodic polling as two main parts:
- A simple console application that reads one batch of events
- We will use a Kubernetes cron job to run the console application at intervals
Putting these two together they implement the event subscription: The cron job makes sure the console application runs at an interval and each time the console application runs it sends the HTTP GET request to check whether there are any events to process.
The first step in implementing an event-subscriber process is to create a console application with the following
dotnet command:
PS> dotnet new console -n EventConsumer
and run it with
dotnet too:
PS> dotnet run
The application is empty, so nothing interesting happens yet, but in the next section we will make it read events.
Subscribing to an event feed
You now have a
EventConsumer console application. All it has to do is read one batch of events and track where the starting point of the next batch of events is. This is done as follows:
Listing 3. Read a batch of events from an event feed
using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text.Json; using System.Threading.Tasks; var start = await GetStartIdFromDatastore(); ❶ var end = 100; var client = new HttpClient(); client.DefaultRequestHeaders .Accept .Add(new MediaTypeWithQualityHeaderValue("application/json")); using var resp = await client.GetAsync( ❷ new Uri($"{start}&end={end}")); await ProcessEvents(await resp.Content.ReadAsStreamAsync()); ❸ await SaveStartIdToDataStore(start); ❹ Task<long> GetStartIdFromDatastore(){...} async Task ProcessEvents(Stream content){...} Task SaveStartIdToDataStore(long startId){...}
❶ Read the starting point of this batch from a database.
❷ Send GET request to the event feed.
❸ Read the starting point of this batch from a database.
❹ Call method to process the events in this batch. ProcessEvents also updates the start variable.
With the code above the
EventConsumer can read a batch of events, and every time it is called it reads the next batch of events. The remaining part is to process the events:
Listing 4. Deserializing and then handling events
async Task ProcessEvents(Stream content) { var events = await JsonSerializer.DeserializeAsync<SpecialOfferEvent[]>(content) ?? new SpecialOfferEvent[0]; foreach (var @event in events) { Console.WriteLine(@event); ❶ start = Math.Max(start, @event.SequenceNumber + 1); ❷ } }
❶ This is where the event would be processed.
❷ Keeps track of the highest event number handled.
There are a few things to notice here:
- This method keeps track of which events have been handled #2. This makes sure you don’t request events from the feed that you’ve already processed.
- We treat the
Contentproperty on the events as
dynamic#1. As you saw earlier, not all events carry the same data in the
Contentproperty, so treating it as dynamic allows you to access the properties you need on
.Contentand not care about the rest. This is a sound approach because you want to be liberal in accepting incoming data—it shouldn’t cause problems if the Special Offers microservice decides to add an extra field to the event JSON. As long as the data you need is there, the rest can be ignored.
- The events are deserialized into the type
SpecialOfferEvent. This is a different type than the
EventFeedEventtype used to serialize the events in Special Offers. This is intentional and is done because the two microservices don’t need to have the exact same view of the events. As long as Loyalty Program doesn’t depend on data that isn’t there, all is well.
The
SpecialOfferEvent type used here is simple and contains only the fields used in Loyalty Program:
public record SpecialOfferEvent( long SequenceNumber, DateTimeOffset OccuredAt, string Name, object Content);
This concludes your implementation C# part of event subscriptions.
If you want to learn more, check out the book on Manning’s liveBook platform here. | https://freecontent.manning.com/implementing-an-event-based-collaboration-using-http/ | CC-MAIN-2022-05 | refinedweb | 1,367 | 56.76 |
Created on 2017-07-18.13:29:53 by Ivan, last changed 2018-02-13.22:29:08 by rklopfer.
Got this in logs:
'org.python.modules.sre.MatchObject' object has no attribute 'end'
Call stack:
gs.time_stamp = datetime.strptime(data_dict['time_stamp'], '%Y-%m-%dT%H:%M:%S')
File "/opt/flute/lib/jython-standalone-2.7.1.jar/Lib/datetime.py", line 1791, in strptime
File "/opt/flute/lib/jython-standalone-2.7.1.jar/Lib/_strptime.py", line 326, in _strptime
line 326 of _strptime is if len(data_string) != found.end()..
Unfortunately, I have no idea what was that in data_dict['time_stamp'].
Further investigation shown that this issue is due to using compiled re objects in multi-threading environment. Using the script below one can reproduce errors saying that certain attributes not present in org.python.modules.sre.MatchObject. This errors are not reproducible for jython2.7.0!
---- Then the question is -- should re be thread-safe at all?
import thread
import re
import time
REGEX = re.compile('((?:foo|bar)+)(\d*)E?')
def parse(line):
m = REGEX.search(line)
if m.groups():
print m.group(1)
thread.start_new_thread(parse, ('foobarfoofoofoofoofoofoofoofoofoofoo234',))
thread.start_new_thread(parse, ('foobarbarbarbarbarbarbarbarbarbarfoo4E',))
thread.start_new_thread(parse, ('foofoofoofoofoofoofoofoofoofoofoofoo434',))
thread.start_new_thread(parse, ('barbarbarbarbarbarbarbarbarfoofoo',))
time.sleep(1)
And here is the script to reproduce the original problem (run it several times to catch an exception). The bug is obviously due to regexp object shared somewhere between threads:
import thread
import re
import datetime
import time
def printtime(time):
print datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%S')',))
time.sleep(1)
Another issue with the same root is with json.loads:
dict = json.loads(flute.params)
File "/opt/flute/lib/jython-standalone-2.7.1.jar/Lib/json/__init__.py", line 338, in loads
File "/opt/flute/lib/jython-standalone-2.7.1.jar/Lib/json/decoder.py", line 366, in decode
AttributeError: 'org.python.modules.sre.MatchObject' object has no attribute 'end'
Thanks for investigating this so carefully.
You write "The bug is obviously due to regexp object shared somewhere between threads", I suppose because in your example it's the only object that obviously is shared between threads. A couple of things puzzle me:
1. Very little here has changed since 2.7.1b3 (Feb 2016).
2. The only obviously shared object (REGEX) appears not to be mutated.
Which causes me to wonder whether there might be a fundamental problem where module-global objects might be inconsistent between threads. Others may have more insight.
I was unable to reproduce this on my Windows box. Here's what I evolved Ivan's demonstration into:
import thread
import re
import time
import random
LEN = 2000
COUNT = 10000
REGEX = re.compile('((?:foo|bar)+)(\d*)E?')
counter = 0
counter_lock = thread.allocate_lock()
def count(inc=0):
global counter
with counter_lock:
counter += inc
return counter
def parse(line):
try:
m = REGEX.search(line)
finally:
count(1)
if LEN <= 10 and m.groups():
print line, m.group(1)
def make():
nonsense = list()
for i in range(LEN):
nonsense.append(random.choice(('foo', 'bar')))
nonsense.append(str(random.randint(1, 99999)))
nonsense.append(random.choice(('', 'E')))
return ''.join(nonsense)
# Make up material
tests = list()
for i in range(COUNT):
tests.append(make())
print "Start all threads"
start = thread.start_new_thread
for test in tests:
start(parse, (test,))
print "Wait for completion"
while True:
c = count()
print c
if not c < COUNT:
break
time.sleep(0.1)
I know there's a lock here, but it doesn't interfere until after the threads complete.
I get:
..\inst\bin\jython .\iss2609_parse2.py
Start all threads
Wait for completion
9984
10000
and no exceptions. During the run, jvisualvm peaks at 1038 live threads and the resource monitor shows all 4 CPUs busy, so I think I'm getting as much concurrency out of it as I have available. I am using:
Jython 2.7.1 (default:0df7adb1b397, Jun 30 2017, 19:02:43)
[Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)] on java1.8.0_141
Hello, Jeff, thanks for reply!
For some reason your version of script also works on my PC without any errors.
Could you please try this one:
import thread
import re
import datetime
import time
def printtime(time):
datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%S')
for i in range(10):
for i in range(10):
thread.start_new_thread(printtime, ('2017-07-01T11:11:11',))
time.sleep(0.5)
This reproduces the error on my Windows 8 laptop with 4 core CPU with the following callstack:
Unhandled exception in thread started by <function printtime at 0x2>
Traceback (most recent call last):
File "d:\temp\deleteme\foo.py", line 7, in printtime
datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%S')
File "D:\jython2.7.1\Lib\datetime.py", line 1791, in strptime
struct, micros = _strptime(date_string, format)
File "D:\jython2.7.1\Lib\_strptime.py", line 326, in _strptime
if len(data_string) != found.end():
AttributeError: 'org.python.modules.sre.MatchObject' object has no attribute 'end'
Our production environment (where the problem came from) are 2-core DigitalOcean droplets with Ubuntu 16.04
I had to make it 1000 blocks of 100 calls, but I did got one exception out of it. But not when I try and catch it :(
I reproduce this each time I run the script on my development machine.
But what is worse, we've got lots of these errors in production environment logs. We reverted the dependency to 2.7.1b3 which doesn't seem to be affected by this problem.
Another script to reproduce the problem:
import thread
import re
import json
import time
def process_json(str):
json.loads(str)
for i in range(10):
for i in range(10):
thread.start_new_thread(process_json, ('{"a": 15, "b": 20}',))
time.sleep(0.1)
fails with error
File "d:\temp\deleteme\foo2.py", line 7, in process_json
json.loads(str)
File "D:\jython2.7.1\Lib\json\__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "D:\jython2.7.1\Lib\json\decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
AttributeError: 'org.python.modules.sre.MatchObject' object has no attribute 'end'
That's what we have in production: regexp, strptime and json.loads calls are affected.
When running on OS X 10.12 I can reproduce this problem by increasing the number of threads and/or test runs. I see two types of errors:
AttributeError: 'org.python.modules.sre.MatchObject' object has no attribute 'end'
AttributeError: 'null' object has no attribute 'end'
The strptime implementation in datetime.py and _strptime.py is not written for multithreaded performance, but it does look correct.
What we faced in production (Ubuntu 16.04 virtual machine, 2Core-CPU, 2Gb memory) is:
1) multiple issues with strptime, json.loads and regex (variations of 'MatchObject has no attribute')
2) errors with 'object has no attribute' with reference to
So we had to roll back to Jython2.7.1b3: b3 version does not have these issues.
Apparently something is broken with synchronization, and apparently regexps are affected.
I have a real machine with the same specification and will try it there.
I've now seen this exception raised in the "parse" and "json" cases on my Linux system. They are rare for me. No program I have is guaranteed to raise one.
I tentatively observe:
1. They are more likely to occur early in execution (if they occur at all).
2. Often I get no actual concurrency (only 1 or 2 more threads than daemons in jvisualvm).
3. Attempting to catch the exception (almost) stops it happening :(
I prefer the parse example as it ought to be possible to preserve the crime scene.
I have a version of the program that (really) runs 100 threads, parsing 2000 foo/bar elements, and drops into pdb if it raises. I'm repeatedly launching it in a Bash while loop. No luck yet.
Hmmm ... I'm not sure that actual concurrency (large numbers of parsers working at the same time) has much to do with this. I run my test as:
> while ../inst/bin/jython parse3a.py ; do echo "ok"; done
which lets me fiddle with the source as it runs. It can be quite a wait. The times I've caught this, the numbers were small. Here's one:
REPEATS=2, THREADS=10, LENGTH=2.
barfoo
foofoo
foobar
barfoo
foofoo
barfoo
barfoo
barfoo
barfoo
barfoo
barfoo
barfoo
foofoo
foobar
foobar
barfoofoofoo
barfoo
barfoo
*** Caught one! ***
Traceback (most recent call last):
File "parse3a.py", line 25, in parse
if m.groups(): short_print(m.group(1))
AttributeError: 'org.python.modules.sre.MatchObject' object has no attribute 'groups'
> /home/jeff/Jython/iss2609/work/parse3a.py(25)parse()
-> if m.groups(): short_print(m.group(1))
(Pdb) p m
<org.python.modules.sre.MatchObject object at 0x2>
(Pdb) m.groups()
('foobar', '52536')
(Pdb) p tests
['barfoo84894', 'barfoo38345E', 'foofoo8017', 'barfoo42953', 'foobar52536E', 'foobar18661', 'barfoo35695E', 'foofoo89916', 'barfoo94921', 'barfoo32379']
(Pdb) p i
0
Now, as you can see, the object m behaved in the thread as if it had no groups() method, but later in the debugger it is present, and it yields the right result. This happens in the first block of threads.
My theory is that use of this object by the thread is running ahead of initialising the object or (quite likely) its class dictionary. I'll test that, see if I can get an incriminating snapshot.
[also sent to jython-dev, apparently I'm not properly registered to respond to this tracker to use email responses]
I increasingly believe this issue is almost certainly as Ivan pointed out earlier in this
thread. Note that the synchronization in PyType.fromClass, which is
responsible for constructing this map, was causing deadlocks was removed in
2.7.1b3 and replaced with a busy wait in 2.7.1rc1.
I want to ask this question: *should we revisit our original decision to
remove this synchronization*? (In and at least another followup
commit set). It is possible that we got this mixed up with the low memory
problem, and how it had a nasty action at a distance problem, see
At the very least this is a low cost thing to try out, although it may not
be conclusive.
I should point out that I spent too much time trying to revisit how this
publishes, and I never found a workable solution that didn't do the busy
waiting that Darjus proposed as an alternative. Clearly we don't care about
this code path being synchronized, only that it doesn't deadlock; it is not
going to be hot except in some pathological usage scenario (constant
reloading of Java classes through distinct class loaders, then used in some
sort of callback scenario is the only thing that I can think of; otherwise
this cost is only a startup cost).
I agree that it is likely to be a general problem with initialisation rather than specific to the thread safety of re. Investigation has led me into code that is generic to the support of types.
This is because, in circumstances (on my Linux box) where the error occurs, I've been able to catch m.__class__.__dict__.items() empty.
The observation that if its going to happen, it happens early, is misleading. I think this may be something to do with it being more likely when the machine is busy (or not busy, who can say). On my Windows machine, which is the only place debugging is a satisfatory experience, the same code will produce the error, but it takes around ten thousand calls. I can't reconcile this with the idea that it is synchronisation of the initialisation of the type that's at fault.
However, not understanding and fully, and given they're in the time frame b3-release, reverting them seems worth a try to me. I could probably try that this evening (UK time). It is clear from comments that we had our doubts about them. With hindsight, given this is a critical bit of the Jython core, and threading is so difficult, either proof or a massively beefy test of correctness was in order.
So far my own investigation has only led me into into MethodCache.lookup_where(). Speaking of hindsight, what I really need for this is a way to catch the miss, then single-step *backwards* into methods that just returned :)
Hello guys, if my evidence can be of any help:
1. On our production machines this errors is indeed a very tiny fraction of successful calls. I forgot to mention that we have 20 Ubuntu machines and watch aggregated logs. BUT on my Windows laptop I can reproduce these errors easily, without many retries.
2. Have been running for 2 days after rolling back to 2.7.1b3: no 'pathological' 'object has no attribute' on logs.
There's one more wrinkle here, which I thought about given Jeff's
observation that it doesn't occur at initialization, yet this looks
like a publishing problem to me. In running the test program of
msg11496, I tried the below change in PyType.java:
classToType = new MapMaker().weakKeys().weakValues().makeMap();
to
classToType = new MapMaker().makeMap();
and with that change, I'm not seeing the test program fail.
The weak references here are essential for Jython to be able to work
in the context of unloading corresponding Java classes and/or Python
types. But weak references of course do make it harder to think about
object lifetimes. For extra fun, I also threw in a gc.collect() in the
test program. With forced GC, that seemed to make it more reliable to
get the publishing failure using the current weak keys/values
construction, and at different times after startup. (Need to do this
testing more comprehensively to be sure, however.)
Note that we really don't care so much about it being weak keys/weak
values per se, only that it is possible to eventually do this cleanup
in some reasonable period of time. In other words, this should be a
cache. Right now, classToType doesn't appear to be caching terribly
well, given that we must be rebuilding these mappings despite being in
a tight inner loop.
More analysis required!
Small clarification from my previous post: doesn't *necessarily* occur at initialization
I think you've got it Jim.
To elaborate on my understanding ... two threads Alice & Bob start. Alice calls REGEX.match and gets a MatchObject result. Alice finds no PyType for a MatchObject, and adds one (maybe here:). Meanwhile Bob starts up, receives a MatchObject and finds the PyType Alice created. But Alice is still building it, and Bob uses it before Alice can finish filling it in.
An observation supporting this theory is that in a few cases the error is a Java NPE thrown from here: .
I find, on Windows, that I get the error much sooner if I print out the arguments during parse(), in the first block normally. Not sure why. However, in that condition of frequent early failure, if I add early in the main program:
sample = REGEX.search("foo23E")
it will run forever (ok, 20 minutes) without raising. Comment it out and it fails immediately. Of course, that line will fully construct (and keep alive) an instance of PyType corresponding to MatcherObject, and do so before the threads start.
There's an attempt here:
to do without the synchronisation, arguing that multiple construction is harmless, because the first thread to set a PyType in the map will win, and the duplicates can be discarded. This argument only works if the object is fully constructed by the time it is entered in the map.
But even then, might this be overlooking the question of cache coherence? The map entry could be absent in one processor's view of memory and not in the other's.
Ok, given the map is thread safe, the question about cache coherency is probably not an issue. I see the intended design here as relying on the map's thread safety rather than synchronising PyType as a whole. I guess we're trying to avoid holding a lock on a global (PyType.class) for longer than is necessary in this hot part of Jython.
As implemented, though, we leave completing the job until after the put(), and therefore unsynchronised (if I've understood it correctly). This was not so when the lock was on the PyType class. I assume the motivation for this two-phase construction is to deal with recursive reference. And you can't complete it before the put() for that reason. (Parallel: when loading Python modules we enter them in sys.modules *before* initialising them in case they refer to themselves.)
Is there a case for a map of part-constructed PyTypes that we are allowed to use in constructing other PyTypes but not in resolving regular accesses? Or is that just another thinking error?
Weak references make the problem occur more frequently because we repeat the faulty construction (I think). I appreciate the question of class unloading, but as written it seems like every time we stop using the exposed version of a class momentarily, we're going to pay for a new PyType. (Every time but the last, that is.) I think this is behind the comment in the docs for MapMaker here:, still recommending softValues() despite having removed that method.
Is ClassValue what we ought to be using here? I'm pleased to find that it is available from Java 7, not 8 as I thought. You'd still have to complete construction before making it visible to attribute access.
Also, JLS 17.4.4: "Programmers do not need to reason about reorderings to determine that their code contains data races."
I can confirm that backing out and makes my test run indefinitely (meaning 40 min). To be specific, the test is parse4a.py as attached, and it runs in a shell loop:
do { dist\bin\jython parse4a.py } until ($LASTEXITCODE -ne 0)
The same thing *without* the 2 changesets backed out drops into the debugger within a few minutes.
This leaves us with #2487 still to fix, and without reproducing this one. More there later.
Fix to push after a last regression test completes.
Belatedly linking, believed to solve it. Also not reworking of PyType in. | http://bugs.jython.org/issue2609 | CC-MAIN-2018-34 | refinedweb | 3,059 | 67.45 |
Storybook is a set of libraries that lets us create components and preview them by passing in various attributes to them. The recent release of Storybook 6 included many convenient new features. Without further ado, let’s take a look at the new features and how to use them.
Zero-config setup
With Storybook 6, we can build a Storybook with ease: all we have to do is run
npx sb init on our project and we have Storybook added.
If we wanted to add Storybook to a React project created with create-react-app, for example, we’d just use that command. Do note, however, that
npx sb init only works with existing projects and can’t be used on an empty project folder.
So, to use Storybook with a React project, we first run:
npx create-react-app storybook-project
This creates the
storybook-project React project. Then, we go to the
storybook-project folder and run
npx sb init to add Storybook to it.
To upgrade an existing Storybook project to the latest version, we run
npx sb upgrade to install it. We’d then run
yarn add @storybook/addon-essentials --dev to install the addons, which render the content we see below the preview of the component.
The Storybook Essentials package has a few useful addons for changing the viewport in which we can preview our component. It also has an addon that allows us to document our component using either JSX or MDX code. (MDX is a mix of Markdown and JSX.)
Other addons include:
- The actions addon: Lets us log event objects emitted from various events, such as clicks, mouseover, keyboard events, etc.
- The backgrounds addon: Lets us set the background to our preferred color when previewing our component
- The toolbars addon: Lets us customize the toolbar at the top of the Storybook screen with our own preferences
TypeScript support is also built-in with Storybook 6, so we can immediately use TypeScript out of the box without extra configuration.
Args for stories
In Storybook, args are attributes that we pass into our components to change it. This lets us make preset configurations for our component so that we can preview them.
We can set the args in the story files. For example, if we have a React Storybook project, we can create our components and stories as follows:
//src/stories/Button.js import React from 'react'; import PropTypes from 'prop-types'; import './button.css'; export const Button = ({ primary, backgroundColor, size, label, ...props }) => { const mode = primary ? 'button-primary' : 'button-secondary'; return ( <button type="button" className={['button', `button-${size}`, mode].join(' ')} style={backgroundColor && { backgroundColor }} {...props} > {label} </button> ); }; Button.propTypes = { primary: PropTypes.bool, backgroundColor: PropTypes.string, size: PropTypes.oneOf(['small', 'medium', 'large']), label: PropTypes.string.isRequired, onClick: PropTypes.func, }; Button.defaultProps = { backgroundColor: null, primary: false, size: 'medium', onClick: undefined, };
//src/stories/button.css .button { font-weight: 700; border: 0; border-radius: 3em; cursor: pointer; display: inline-block; line-height: 1; } .button-primary { color: white; background-color: #1ea7fd; } .button-secondary { color: #333; background-color: transparent; } .button-small { font-size: 12px; padding: 10px; } .button-medium { font-size: 14px; padding: 11px; } .button-large { font-size: 16px; padding: 12px; }
//src/stories/Button.stories.js import React from 'react'; import { Button } from './Button'; export default { title: 'Example/Button', component: Button, argTypes: { backgroundColor: { control: 'color' }, }, }; const Template = (args) => <Button {...args} />; export const Primary = Template.bind({}); Primary.args = { primary: true, label: 'Button', }; export const Secondary = Template.bind({}); Secondary.args = { label: 'Button', }; export const Large = Template.bind({}); Large.args = { size: 'large', label: 'Button', }; export const Small = Template.bind({}); Small.args = { size: 'small', label: 'Button', };
The
Button.js file has the component file, and the
button.css has the styles for the
Button component.
The
Button components takes several props:
- The
primaryprop lets us set the class for to style the button in various ways
backgroundColorset the background color
sizesets the size
labelsets the button text
The rest of the props are passed into the
button element.
Below that, we add some prop type validations so that we can set our args properly and let Storybook pick the controls for the args.
primary is a Boolean, so it’ll be displayed as a checkbox button.
backgroundColor is a string.
size can be one of three values, so Storybook will create a dropdown for it automatically to let us select the value.
label is a string prop, so it’ll show as a text input. The input controls are in the Controls tab of the Storybook screen below the component preview.
The args are set in the
Button.stories.js file, which is a file with the stories. Storybook will pick up any file that ends with
stories.js or
stories.ts as a story files.
The
argTypes property lets us set the control for our args. In our example, we set the
backgroundColor prop to be controlled with the
'color' control, which is the color picker.
Below that, we have our stories code. We create a template from the
Button component with our
Template function. It takes the args we pass in and passes them all off to the
Button.
Then, we call
Template.bind to let us pass the args as props to
Button by setting the
args property to an object with the props.
Template.bind returns a story object, which we can configure with args. This is a convenient way to set the props that we want to preview in our story.
Live-edit UI components
The Controls tab has all the form controls that we can use to set our component’s props. Storybook picks up the props and displays the controls according to the prop type.
Also, we can set the form control type as we wish in the stories file, as we’ve seen in the
argTypes property in the previous sections’ example. With this, we can set the props live in the Storybook screen and see what the output looks like in the Canvas tab.
The
backgroundColor prop’s value is changed with a color picker. The
primary prop is changed with a toggle button that lets us set it to
true or
false. And the
size prop is controlled with a dropdown since it can only be one of three values.
Storybook does the work automatically unless we change the control types ourselves. This is a very useful feature that lets us change our component without changing any code.
Combine multiple Storybooks
Storybook 6 introduces the ability to combine multiple Storybook projects by referencing different Storybook projects in another project.
We can do this by adding the following code in the
.storybook/main.js file:
module.exports = { //... refs: { react: { title: "React", url: '' }, angular: { title: "Angular", url: '' } } }
This lets us load multiple Storybook projects’ stories in one project. Now, if we run
npm run storybook, we’ll see all the Storybook stories displayed from both projects on the left sidebar.
The
title value is displayed in the left sidebar, and the
url has the URL to reach the Storybook project.
Conclusion
Storybook 6 comes with many useful new features. Storybook setup in existing projects can now be done with one command if you have a project that Storybook supports. We can use args to preset props in stories and preview them easily, and we can reference another Storybook project from another with minimal configuration.. | https://blog.logrocket.com/whats-new-in-storybook-6/ | CC-MAIN-2020-40 | refinedweb | 1,226 | 57.87 |
This document is also available in these non-normative formats: XML.
Copyright © 2002 W3C® (part of the XML Activity) and the XSL Working Group (part of the Style Activity).
Comments on this document and Pseudo-code Syntax
3 Concepts
3.1 Node Identity
3.2 Document Order
3.3 XML Schemas and the XML Information Set
3.4 Types
3.5 Typed Value and String Value
3.6 Mapping PSV Infoset additions to Types.2 Documents
4.2.1 Overview
4.2.2 Constructor
4.2.3 Accessors
4.2.4 PSVI to Datamodel Mapping
4.2.5 Data Model to Infoset Mapping
4.3 Elements
4.3.1 Overview
4.3.2 Constructor
4.3.3 Accessors
4.3.4 PSVI to Data Model Mapping
4.3.5 Data Model to Infoset Mapping
4.4 Attributes
4.4.1 Overview
4.4.2 Constructor
4.4.3 Accessors
4.4.4 PSVI to Data Model Mapping
4.4.5 Data Model to Infoset Mapping
4.5 Namespaces
4.5.1 Overview
4.5.2 Constructor
4.5.3 Accessors
4.5.4 PSVI to Data Model Mapping
4.5.5 Data Model to Infoset Mapping
4.6 Processing Instructions
4.6.1 Overview
4.6.2 Constructor
4.6.3 Accessors
4.6.4 PSVI to Data Model Mapping
4.6.5 Data Model to Infoset Mapping
4.7 Comments
4.7.1 Overview
4.7.2 Constructor
4.7.3 Accessors
4.7.4 PSVI to Data Model Mapping
4.7.5 Data Model to Infoset Mapping
4.8 Text
4.8.1 Overview
4.8.2 Constructor
4.8.3 Accessors
4.8.4 PSVI to Data Model Mapping
4.8.5 Data Model to Infoset Mapping
5 Atomic Values
6 Sequences
A XML Information Set Conformance
B References
C References (Non-Normative)
D Example (Non-Normative)
E Open Issues (Non-Normative)
F Recently Closed Issues .
Note:
In XPath 1.0, the data model only defines nodes. The primitive data types (number, boolean, string, node-set) are part of the expression language, not the data model.. Examples of values that cannot be expressed directly by the data model include schema components and atomic values whose type is not an XML Schema atomic type. prose, we define two sets of functions to explain the data model: accessors and constructors. The accessors and constructors defined by the data model are shown with the prefix dm. The prefix is always shown in italics to emphasize that these functions are abstract; they exist to explain the interface between the data model and specfications that rely on the data model: they are not and cannot be made accessible directly from the host language.
See [Issue-0033: Unclear relationship between values passed to the constructor, and those returned by the accessor].
The signature of accessors and constructors is shown using the same style as [XQuery 1.0 and XPath 2.0 Functions and Operators]. For example:
In the psuedo-code syntax, the term Node denotes the category of node values, AtomicValue denotes the category of atomic values, and Item refers to the category of either node values or atomic values.
Some accessors and construct:
Note:
The XPath 1.0 data model defines accessors, but does not define constructors., tree-shaped graph,. [Definition: The result of schema validity assessment is an augmented Infoset, known as the Post Schema-Validation Infoset, or PSVI.]
The data model supports well-formed XML documents conforming to [Namespaces in XML]. XML documents that are not well-formed are not XML, by definition. XML documents that do not conform to [Namespaces in XML] are not supported (they are.
Note:
This implies accommodation for the case where both a DTD and a schema are applied. This will probably require some reconciliation of the [attribute type] property with type information from the PSVI. See issues [Issue-0004: Schema/DTD], [Issue-0081: Schema-less documents with a DTD]..
See [Issue-0085: Globally declared namespaces in the infoset].
The data model supports a representation of named types as
expanded-QNames.
Named types include both the built-in types defined by
[XMLSchema Part 2] and user-types declared in a schema
and imported by a stylesheet or query.
Since named types in XML Schema are global, an expanded-QName
uniquely identifies such a type.
The namespace name of the expanded-QName is the target namespace
of the schema and its local name is the name of the type.
The data model does not uniquely identify anonymous types and
represents them by
xs:anyType or
xs:anySimpleType.
The data model associates type information with element nodes,
attribute nodes and atomic values. If this type information is
something other than
xs:anyType or
xs:anySimpleType, it is
locally declared,.
[Issue-0089: How is typed-value calculated?]
This section specifies how the type of an element or attribute node is computed from the PSVI properties that specify validity and type assessment for the node's corresponding information item.
See [Issue-0077: PSVI to Type mapping dependence on conformance levels]. and is false: the [member type definition namespace] and the [member type definition name].
If [type definition anonymous] exists and is false: the [type definition namespace] and the [type definition name]
Otherwise,
xs:anyType for elements or
xs:anySimpleType for attributes. tree contains a root plus all nodes that are reachable directly or indirectly from the root via the dm:children, dm:attributes, and dm.
See [Issue-0091: Support for substitution groups].].
The following table summarizes the accessor functions and the types of values that they return if called on a node of each type.
The dm:base-uri accessor returns a sequence containing zero or one uri references.
Document, element, and processing-instruction nodes have a base-uri property. If that property, an error is raised. See [Issue-0087: base-uri should return ()?] processing-instruction
The dm:string-value accessor returns a string representation of the node.
For some kinds of nodes, this is part of the node; for other kinds of nodes, it is computed from the dm:string-value of its descendant nodes.
The dm:string-value accessor can be used to recover the
lexical representation of an atomic value. The details of converting
an atomic value to its string representation are described in the
"Casting Functions" section of [XQuery 1.0 and XPath 2.0 Functions and Operators].
In particular if the atomic value's type is primitive,
dm:string-value returns the atomic value's canonical
lexical representation for that primitive type as specified in
[XMLSchema Part 2]. If the atomic value's type is derived, the
lexical representation depends on whether a value is supplied for the
type's pattern facet: If no such value is supplied
dm:string-value returns the atomic value's canonical
lexical representation for the primitive base type.
Otherwise dm:string-value returns a lexical
representation that matches the value specified for the pattern facet.
(This case includes
xs:integers.) See [Issue-0072: Lexical representation of Schema primitive types].
Note:
Using the canonical lexical representation for atomic values as described above may not always be compatible with XPath 1.0.
typed-valueAccessor.
See [Issue-0080: Typed value of Document, PI and Comment nodes].
If the node (or node kind) has no typed value, the empty sequence is returned.
typeAccessor
The dm:type accessor returns a sequence containing zero or one xs:QName.
For element nodes, dm:type returns the globally declared QName of the type of the node or xs:anyType if it is locally declared or no type information exists.
For attribute nodes, dm:type returns the globally declared QName of the type of the node or xs:anySimpleType if it is locally declared or no type information exists.
For other node kinds, it always returns the empty sequence.
childrenAccessor
The dm:children accessor returns a sequence containing zero or more nodes.
For document and element nodes, it returns the nodes that are the children of that node. It returns the empty sequence for document and element nodes that have no.
Document nodes encapsulate XML documents. Documents have the following properties:
base-uri, possibly empty.
children
Document nodes must satisfy the following constraints.
An document node's children may not contain two consecutive text nodes. Consecutive text nodes are collapsed by the document constructor into one text node. [Issue-0074: Do we need Document fragments].
Note:
Document nodes and XPath 1.0 root nodes are essentially identical.
A document node can be constructed using dm:document-node which returns a new node with unique identity, distinct from all other nodes.
The constructor takes an optional base URI value and a non-empty sequence of children nodes as arguments.
dm:document-node(
$children
as
Node+)
as
DocumentNode
dm:document-node(
$children
as
Node+,
$base-uri
as
xs:anyURI)
as
DocumentNode
The sequence of nodes passed as
$children must not be
empty and must consist only of element, processing instruction,
comment, and text nodes. See [Issue-0090: Documents can be empty].
If consecutive text nodes are specified as the children of a document node they are collapsed into one text node whose string value is the concatenation of the string values of the consecutive text nodes.
Two.
When a data model fragment is created from the PSVI, a document information item is mapped to a Document Node. The precise transformation is described by specifying the PSVI property corresponding to each argument of the document node constructor:
To construct the value of the
$children argument, for
each element, processing instruction, comment, and maximal sequence of
adjacent characater information items found in the
[children] property, a corresponding
Element, Processing Instruction, Comment, and Text node is constructed
and that sequence of nodes is used as the value. If present among the
[children], the
[document type declaration] information item
is ignored.
Note:
There is no way to determine what DTD might apply to the data model. See [Issue-0042: System Id and Public Id are not exposed].
The mapping of the data model to the XML Information Set maps a Document Node to a document information item. The properties of the document information item are constructed as follows:
Note:
Since Document Nodes are more permissive than document information items, the resulting InfoSet may be invalid.
Element nodes encapsulate XML elements. Elements have the following properties:
base-uri, possibly empty.
node-name
parent
type, possibly empty
children, possibly empty
attributes, possibly empty
namespaces, possibly empty
Element nodes must satisfy the following constraints.
An element node's children may not contain two consecutive text nodes. Consecutive text nodes are collapsed by the element constructor into one text node.
If a node N is a child of an element E, then the parent of N must be E.
If a node N has a parent element E, then N must be among the children of E.".
The element node constructor assures that the first three constraints are satisfied.
Note:.
An element node can be constructed using dm:element-node which returns a new node with unique identity, distinct from all other nodes.
The constructor takes an expanded-QName, a sequence of namespace nodes, a sequence of attribute nodes, a sequence of child nodes, the node's type, and an optional base URI as arguments.
The sequence of nodes passed as
$children
must consist only of element, processing instruction,
comment, and text nodes.
If consecutive text nodes are specified as the children of an element node they are collapsed into one text node whose string value is the concatenation of the string values of the consecutive text nodes.?].
The data model permits element nodes without parents. In fact element nodes created by the element node constructor never have parents unless they are enclosed in other node constructors. Such nodes may represent partial results during expression processing.
The dm:base-uri accessor returns the base-uri property of the element node, if it exists. If it does not exist, the base URI of the element's parent is returned. In other words, the value returned must be the same as the value of dm:base-uri(dm:parent()) although implemetations are not required to implement it in that way.
The accessors dm:namespaces and dm:attributes return the same set of namespace and attribute nodes (respectively) that were supplied to the constructor, but they are not constrained to return them in the same order. See [Issue-0086: Nodes returned by namespaces and attributes] element information item is mapped to an Element Node. The precise transformation is described by specifying the PSVI property corresponding to each argument of the element node constructor.
$qname
An
xs:QName constructed from the
[local name] property
and the
[namespace name] property
$nsnodes
A set of Namespace Nodes constructed from the namespace information items appearing in the [in-scope namespaces] property.
Implementations may provide mechanisms to allow some or all of the namespaces in the [in-scope namespaces] property to be discarded from the data model.
$attrnodes
A set of Attribute Nodes constructed from the
attribute information items
appearing in the [attributes]
property. This includes all of the "special" attributes
(
xml:lang,
xml:space,
xsi:type, etc.)
but does not include namespace declarations (because they are not attributes).
The special nature of
xsi:nil is still being discussed,
see [Issue-0071: Magic Attributes].
$children
If the [schema normalized value] PSVI property exists, a single text node whose string value is the value of that property.
Otherwise, the sequence of nodes constructed in the following way from the information items found in the [children] property: for each element, processing instruction, comment, and maximal sequence of adjacent characater information items found in the [children] property, a corresponding Element, Processing Instruction, Comment, and Text node is constructed.
Because the data model requires that all general entities be expanded, there will never be unexpanded entity reference information item children.
$type
The
xs:QName computed as described in
3.6 Mapping PSV Infoset additions to Types.
Note that if the type referenced would be a union type then
type refers to the member type that actually validated the
schema normalized value..
If a new prefix is generated, a corresponding namespace information item must be added to the [in-scope namespaces] property of the element information item. The namespace information item must associate the generated prefix with the namespace name of the QName returned by the element's dm:node-name accessor.
Note:
If the implementation has allowed in-scope namespaces to be discarded from the data model, then these namespaces may need to be reintroduced when creating an InfoSet in order to ensure that the InfoSet corresponds to a document that is namespace well-formed as defined in [XML Namespaces].
Note:
The algorithm used to calculate namespace attributes will need to be adjusted to cater for XML Namespaces 1.1, which allows the "undeclaration" of all namespaces, whether they have a prefix or not.
Attribute nodes encapsulate XML attributes. Attributes have the following properties:
node-name
parent
type, possibly empty
The above information associated with an attribute node is set during construction and can be accessed later via the accessor functions.
For convenience, the element node that owns this attribute is called its "parent" even though an attribute node is not a "child" of its parent element.
An attribute node can be constructed using dm:attribute-node which returns a new node with unique identity, distinct from all other nodes.
The constructor takes the attribute's expanded-QName, string value, and type.
Like all other node constructors, the attribute node constructor has the effect of creating a new node with a unique identity, distinct from all other nodes.
When a data model fragment is created from the PSVI an attribute information item is mapped to an Attribute Node. The precise transformation is described by specifying the PSVI property corresponding to each argument of the attribute node constructor.
$qname
An
xs:QName constructed from the
[local name] property
and the
[namespace name] property
$value
The [schema normalized value] PSVI property if that exists, or
the [normalized value] property.
$type:
If the attribute node has a parent, an implementation must construct the value of the [prefix] property in the following way: if the attribute has a parent, in the same way that a prefix would be constructed for that element, otherwise a prefix is chosen arbitrarily, and no attempt is made to associate the prefix with the namespace URI.
Namespace nodes encapsulate XML namespaces. Namespaces have the following properties:
prefix, possibly empty.
uri [Functions and Operators], namely xf:get-in-scope-namespaces and xf.
The above information associated with a namespace node is set during construction and can be accessed later via the accessor functions.
Each element node has an associated set of namespace nodes corresponding to its in-scope namespaces, and that element node acts as the parent of those namespace nodes.
A namespace node can be constructed using dm:namespace-node which returns a new node with unique identity, distinct from all other nodes.
The constructor takes a namespace prefix and the URI of the namespace being declared.
dm:namespace-node(
$prefix
as
xs:string?,
$uri
as
xs:string)
as
NamespaceNode
The namespace prefix may be the empty sequence. If the URI is the zero-length string, the prefix must be the empty sequence.
When a data model fragment is created from the PSVI a namespace information item is mapped to a Namespace Node. The precise transformation is described by specifying the PSVI property corresponding to each argument of the attribute node constructor.
$prefix
The [prefix] property.
$uri
The [namespace name] property.
Processing instruction nodes encapsulate XML processing instructions. Processing instructions have the following properties:
target
content
parent, possibly empty
A processing instructoin node can be constructed using dm:processing-instruction-node which returns a new node with unique identity, distinct from all other nodes.
The constructor takes an NCName, a string, and an optional base URI.
The string '?>' may not occur within a processing instruction's target or content value ([XML Recommendation]).
When a data model fragment is created from the PSVI, a processing instruction information item is mapped to a Processing Instruction Node. The precise transformation is described by specifying the PSVI property corresponding to each argument of the processing instruction node constructor.
$target
The value of the [target] property.
$content
The value of the [content] property.
$base-uri
The value of the [base URI] property.
There are no processing instruction nodes for processing instructions that are children of a document type declaration information item.
Comment nodes encapsulate XML comments. Comments have the following properties:
the content
parent
A comment node can be constructed using dm:comment-node which returns a new node with unique identity, distinct from all other nodes.
The constructor takes a string value.
dm:comment-node(
$content
as
xs:string)
as
CommentNode
The string "--" (two consecutive hyphens) must not occur within a comment's string value ([XML Recommendation]).
When a data model fragment is created from the PSVI a comment information item is mapped to a Comment Node. The precise transformation is described by specifying the PSVI property corresponding to each argument of the comment node constructor.
$content
The value of the .
A text node can be constructed using dm:text-node which returns a new node with unique identity, distinct from all other nodes.
The constructor takes a string value.
When a data model fragment is created from the PSVI a maximal sequence of consecutive character information items are mapped to a Text Node. The precise transformation is described by specifying the PSVI property corresponding to the argument of the comment node constructor.
$content
A string comprised of characters that correspond to the [character code] properties of each of the character information items.
Note:
The string-value is not W3C normalized as described in the Character Model for the World Wide Web version 1.0 draft. See [Issue-0045: Text nodes are not W3C-normalized text].
type are represented by a sequence of atomic values whose type is the item type.
The values of nodes whose type is derived by union from an XML Schema primitive type are represented by a sequence of atomic values"?> <!DOCTYPE catalog [ <!ELEMENT tshirt ANY> <!ATTLIST tshirt code ID #REQUIRED> <!ELEMENT album ANY> <!ATTLIST album code ID #REQUIRED> <!ELEMENT price ANY> <!ATTLIST price currency CDATA 'USD'> <!ENTITY copy '©'> ]> data-model constructors.
Date: Oct-2000
Raised by: Datamodel Editors
Effects: (Issue-0004, 2, This implies accommodation for the case where both a DTD and a schema are applied. This will probably require some reconciliation of the [attribute type] property with type information from the PSVI. See issues , . ).
Issue-0023: Support for document repositories
Date: 27-Mar-2001
Raised by: XPath 2.0 Task Force
Effects: (Issue-0023, 1, A collection of documents is represented in the data model as a sequence of document nodes (see ).)25: Types of Sequences
Date: 27-Apr-2001
Raised by: Mike Kay
Effects: (Issue-0025, 1, See .)
Description: Should sequence values carry their type as do simple typed values and element and attribute nodes?
Issue-0033: Unclear relationship between values passed to the constructor, and those returned by the accessor
Date: 28-April-2001
Raised by: James Clark
Effects: (Issue-0033, 1, See .)
Description: (members only). Asks for inference rules, especially for the constuctor, describing when values returned by an accessor are the same as those set by the corresponding constructor. Especially unclear are when adjacent text nodes are collapsed, base URI and namespace declarations.
Issue-0037: Axis functions
Date: 19-July-2001
Raised by: XSL WG
Description: Define (somewhere other than the data model document?) axis functions for non-primitive axes like descendants-or-self.
Issue-0038: XPath 1.0 treatment of non-unique IDs
Date: 13-August-2001
Raised by: Datamodel Editors
Effects: (Issue-0038, 1, Using this definition, only IDs declared in a DTD are effective. See . Even so, this definition is not backward compatible with XPath 1.0. See . Furthermore, it doesn't even work as spec'd, see . )?
Issue-0042: System Id and Public Id are not exposed
Date: 15-August-2001
Raised by: Jim Melton
Effects: (Issue-0042, 1, There is no way to determine what DTD might apply to the data model. See .)
Description: In our model, there is no way for a query to determine what DTD is relevant for the data model instance. That seems like a piece of information that might be wanted occasionally (though probably not often).
Issue-0044: Unable to construct an element with unique ID
Date: 15-August-2001
Raised by: Jonathan Marsh
Effects: (Issue-0044, 1, Using this definition, only IDs declared in a DTD are effective. See . Even so, this definition is not backward compatible with XPath 1.0. See . Furthermore, it doesn't even work as spec'd, see . )
Date: 2001-08-17
Raised by: Jim Melton
Effects: (Issue-0045, 1, The string-value is not W3C normalized as described in the Character Model for the World Wide Web version 1.0 draft. See .)
Description: The Character Model for the World Wide Web version 1.0 working draft defines W3C-normalized text. The algorithm for constructing text nodes from character information items does not perform normalization to this form. Should it?
Issue-0050: Relative order of free-floating nodes
Date: 2001-08-17
Raised by: Jim Melton
Effects: (Issue-0050, 2, The relative order of free-floating nodes (those not in a document) is not defined. See .)52: Element constructor copies nodes?
Date: 28-August-2001
Raised by: Michael Kay
Effects: (Issue-0052, 1,
Date: 25-September-2001
Raised by: Michael Kay69: Canonical form for derived types.
Date: 4-December-2001
Raised by: XPath Task Force
Description: Should derived types have a canonical form? Should we ask XML Schema to fix this?
Issue-0071: Magic Attributes
Date: 7-December-2001
Raised by: Michael Rys
Description: Should the following attributes be represented in the data model? xmlns attributes, xml:lang, xml:space, xsi:nil (etc). If so, how?
Resolution: Namespace declarations do not appear in the attributes property. All of
the other attributes except
xsi:nil do.
This issue remains open while the issue of
xsi:nil is resolved.
Issue-0072: Lexical representation of Schema primitive types
Date: 13-January-2002
Raised by: Jeni Tennison
Effects: (Issue-0072, 1, The string-value accessor can be used to recover the lexical representation of an atomic value. The details of converting an atomic value to its string representation are described in the Casting Functions section of . In particular if the atomic value's type is primitive, string-value returns the atomic value's canonical lexical representation for that primitive type as specified in . If the atomic value's type is derived, the lexical representation depends on whether a value is supplied for the type's pattern facet: If no such value is supplied string-value returns the atomic value's canonical lexical representation for the primitive base type. Otherwise string-value returns a lexical representation that matches the value specified for the pattern facet. (This case includes xs:integers.) See .)?
Issue-0074: Do we need Document fragments
Date: 12-February-2002
Raised by: Michael Rys
Effects: (Issue-0074, 1,).
Issue-0076: PSVI to Type mapping supporting derived types
Date: 29-July-2002
Raised by: Marton Nagy
Effects: (Issue-0076, 1, The above definition is currently under discussion. It is very likely that a change will be made in a future draft to reflect a more precise definition covering derived types and the possible usage of generated type identifiers when no type names available. See . ).
Issue-0077: PSVI to Type mapping dependence on conformance levels
Date: 29-July-2002
Raised by: XPath Task Force
Effects: (Issue-0077, 1, See .)
Description: The rules specifying the computation of the types from the PSVI do not yet reflect that this process depends on the conformance level of the processor. For Basic, are any type annotations preserved? The Query/XPath book says the data types are mapped to the nearest supertype, the Data Model needs to agree with this.
Issue-0079: String-value vs. string-value of the typed-value
Date: 31-July-2002
Raised by: Marton Nagy
Effects: (Issue-0079, 2, The string-value of a node and the result of casting the typed-value of a node to a string may give different results under this definition. The issue of whether to allow or possibly mandate that string-value return the same result as the string-value of the typed value is still under discussion. See . ).
Issue-0080: Typed value of Document, PI and Comment nodes
Date: 1-August-2002
Raised by: Mary Fernandez
Effects: (Issue-0080, 1, See .).
Issue-0081: Schema-less documents with a DTD
Date: 10-Sep-2002
Raised by: Editors
Effects: (Issue-0081, 1, This implies accommodation for the case where both a DTD and a schema are applied. This will probably require some reconciliation of the [attribute type] property with type information from the PSVI. See issues , . )
Description: If a document has a DTD, do we really have to lose the IDness of all ID attributes and other information that's available from DTD validation?}.
Issue-0085: Globally declared namespaces in the infoset
Date: 2002-10-23
Raised by: Norman Walsh
Effects: (Issue-0085, 1, See .)
Description: There is an open issue about how to map namespaces declared globally in the query prolog during the data model to infoset transformation.
This issue replaces an editorial note in the previous draft that said there was an issue.
Issue-0086: Nodes returned by dm:namespaces and dm:attributes
Date: 2002-10-17
Raised by: Jonathan Marsh
Effects: (Issue-0086, 1, The accessors namespaces and attributes return the same set of namespace and attribute nodes (respectively) that were supplied to the constructor, but they are not constrained to return them in the same order. See ).
Issue-0087: dm:base-uri should return ()?
Date: 2002-10-29
Raised by: Norman Walsh
Effects: (Issue-0087, 2, If the accessor is called on a node that does not have a base-uri property, or whose base-uri property is empty, the base-uri of that node's parent is returned. If the node has no parent, an error is raised. See )
Description: Calling dm:base-uri on a node that has no (transitive) base URI property raises an error. Would it be better to return ()?
See.
Issue-0088: Content type is not preserved
Date: 2002-10-30
Raised by: Norman Walsh
Effects: (Issue-0088, 1, A boolean that is true if and only if the entire Text Node consists of white space and the parent of the Text Node exists and is an element and the element content type of the element is not mixed. )
Description: Calculating the value of [element content whitespace] requires knowing the element's content type which doesn't seem to be available.
Issue-0089: How is typed-value calculated?
Date: 2002-11-01
Raised by: Norman Walsh
Effects: (Issue-0089, 1, ) ().
Issue-0090: Documents can be empty
Date: 2002-11-04
Raised by: Michael Kay
Effects: (Issue-0090, 1, The sequence of nodes passed as $children must not be empty and must consist only of element, processing instruction, comment, and text nodes. See .)
Description: I notice that there's a requirement that a document node has at least one child. This seems to have been in previous drafts, but I overlooked it. In XSLT it's legal to create a document node with no children.
Issue-0091: Support for substitution groups
Date: 2002-11-01
Raised by: Jeni Tennison
Effects: (Issue-0091, 1, See .))..
There are 16 recently closed issues. These issues have been resolved since the last publication.
Issue-0028: Whitespace handling
Date: 04-May-2001
Raised by: Jonathan Marsh30: Base URI is a property of element nodes
Date: 04-May-2001
Raised by: Jonathan Marsh32: Keys and key references not represented
Date: 17-May-2001
Raised by: Query
Description: Note that the data model does not currently represent key values and key reference values as described in XML Schema Part 1 : Structures [XMLSchema Part 1]. In a future draft of this document, keys and key references will be represented in the data model.
Resolution: Not in V1..
Issue-0034: Interaction of insignificant whitespace with comments
Date: 8-May-2001
Raised by: Michael Kay
Description: (members only). Clarify whether whitespace is classified as insignificant before or after PI and comment removal.
Resolution: NW: insignificant whitespace is orthogonal to PIs and comments.
Issue-0035: Eliminate heterogeneous sequences
Date: 8-May-2001
Raised by: XSL WG (Michael Kay)
Description: (members only), (members only). Simplify operations such as distinct() by disallowing sequences mixing nodes and simple typed values. Suggests converting nodes in such a heterogeneous sequence to their typed values.
Resolution: Heterogeneous sequences are here to stay.
Issue-0039: Parent of namespace nodes
Date: 13-August-2001
Raised by: Datamodel Editors
Description: In XPath 1.0 namespace nodes have a parent. Should we adopt the XPath 1.0 behavior, the current behavior (no parent), or some other parent (e.g. the document)?
Issue-0051: Document order of shared namespace nodes
Date: 28-August-2001
Raised by: Michael Kay57: Support for XSLT whitespace stripping
Date: 25-September-2001
Raised by: Michael Kay
Description: XSLT allows a stylesheet to designate elements whose whitespace is to be stripped. We need to support this in the data model, or possibly elsewhere.
Similarly, a data model instance for a stylesheet has provisions for stripping comments and processing instructions.
Resolution: NW: this functionality does not need to be supported in the data model.
Issue-0060: Sharing namespace nodes
Date: 25-September-2001
Raised by: Michael Kay
Date: 25-September-2001
Raised by: Michael Kay
Date: 16-October-2001
Raised by: Michael Kay70: Should the name accessor return "" or ()?
Date: 5-December-2001
Raised by: XPath Task Force
Description: Should the name accessor return "" or () for nodes that have no name?
Resolution: Returns ().
Issue-0075: Support for unparsed entities
Date: 26-June-2002
Raised by: Michael Kay
Description: XSL WG has a requirement to access unparsed entities in a document. This is needed to support the XSLT 1.0 unparsed-entity-uri() function, and the unparsed-entity-public-id() function which we are adding for XSLT 2.0. In XSLT 1.0, unparsed entities were not described in the XPath data model, but in an XSLT addition to the data model. This solution is unsatisfactory: the data model should describe all the information that is available. The information is available in the InfoSet so there is no architectural problem in providing it. There is room for debate about how it is best provided (we don't really want another node type if we can help it), but the information should be there. We are not proposing, at this stage, that the functions unparsed-entity-uri() and unparsed-entity-public-id() be moved from XSLT into XPath, though that can easily be done if people want them. The information about unparsed entities in the data model would therefore not be available to XQuery users or to XPath users outside an XSLT environment.
Resolution: Closed: added data model accessors.
Issue-0078: Data model does not represent CDATA sections
Date: 31-July-2002
Raised by: Michael Kay
Description: It is not clear how the current data model can represent or accomodate CDATA sections. (This is also captured as Issue 0293 on the XPath issue list.)
Resolution: Subsumed by query issue #293..
Issue-0084: How are unparsed entities represented?
Date: 26-Sep-2002
Raised by: Norman Walsh
Description: Suppose I have an attribute that has the type xs:ENTITY and the value "foo". How can I find out the public and system identifiers of the external unparsed entity "foo"?
Resolution: Duplicate of [Issue-0075: Support for unparsed entities] (closed). | https://www.w3.org/TR/2002/WD-query-datamodel-20021115/ | CC-MAIN-2021-25 | refinedweb | 5,637 | 56.15 |
SQL Max Count
'SQL Max Count'. To elaborate example
we create a table 'Stu'. The create table...
SQL Max Count
SQL Max Count is used to return the maximum records value of the specified
column
Max()
Max() How to find maximum values A101,A107,A108 from a table in sql
Using Min, Max and Count on HQL.
Using Min, Max and Count on HQL. How to use Min, Max and Count on HQL
SQL Aggregate Max
SQL Aggregate Max
SQL Aggregate Max is used to find the highest value of the column in a table
Understand with Example
The Tutorial illustrate an example from SQL
MySQL Count
MySQL Count
This example illustrates how to use count() in MySQL database.
Count(): The Count... * FROM employee;
Output:
To use COUNT(*) with the sql query
SQL Aggregate Max
from SQL Aggregate Max. In this
Example we create a table Stu_Table... SQL Aggregate Max
SQL Aggregate Max is used to find the highest value of the column
SQL Average Count
SQL Average Count
Average Count in SQL is used to count the aggregate sum of any field... example ,which helps you to
calculate the average count of any records specified
SQL Average Count
SQL Average Count
Average Count in SQL is used to count the aggregate sum of any field... demonstrative example ,which helps you to
calculate the average count of any
Aggregrate function Max() in db
Aggregrate function Max() in db Hi everyone i have a question and stuck with this problem.
i have a table like Brand in mySql db where brandid... for generating id.
Mycode for id generation is:
public String GetId(String sql
Table maximum Row count - JDBC
,
Sql Query for select maximum value max() function use.
"select max...Table maximum Row count Dear friends
I want to select maximum time entry Status from db.
for example :
Status : 3 4 6 8 3 5 7 5
SQL Aggregate Functions List
List
Queries. The Aggregate Function include the average, count, min, max, sum etc
queries.
Understand with Example
The Tutorial illustrate an example from SQL...
SQL Aggregate Functions List
PHP SQL Max
PHP SQL Max
This example illustrates how to use max() function in sql.
In this example... table using mysql_connect("hostName", "userName",
"
sql - SQL
want query?
4.what is the diffrence between sql and plsql? Hi Friend... query finds the second highest salary from the table employee:
SELECT MAX(salary) FROM employee WHERE salary NOT IN (SELECT MAX(salary) FROM employee);
2
Hibernate Max() Function (Aggregate Functions)
(...),
sum(...), min(...), max(...) , count(*), count(...), count(distinct...();
String SQL_QUERY = "select
max...
Hibernate Max() Function (Aggregate Functions
oracle - SQL
table Hi Friend,
In MySql, you can use the following queries:
1)select * from employee e1 where (3-1) = (select count(distinct (e2.salary)) from employee e2 where e2.salary>e1.salary)
2)select max(salary) from employee where
hibernate criteria Max Min Average Result Example
hibernate criteria Max Min Average Result Example
In this Example, We... of Projection. In this example we create a criteria instance
and implement the Projections class max, min ,avg methods.
Here is the simple Example code files
JDBC: Rows Count Example
JDBC: Rows Count Example
In this section, You will learn how to count number... is stored in ResultSet object.
Your query -
String sql = "SELECT count(*) FROM student";
rs = statement.executeQuery(sql);
Example : In this example we
Hibernate max() Function
the different keywords as the SQL to be written with the max()
function.
for example : max( [ distinct | all ] object.property )
Example :
An example is being given...Hibernate max() Function
In this tutorial you will learn about how to use HQL
MySQL Aggregate Function
in the MySQL
Query.
In this example we use the aggregate function ('COUNT', 'MIN', 'MAX', and
'SUM') in the MySQL Query. The group (aggregate) functions... MySQL Aggregate Function
mysql - SQL
mysql hi sir i want to display first two person highest salary in mysql Hi
I am sending a link where u can find max function to find the maximum marks of student.
JDBC Select Max Example
JDBC Select Max Example
In this tutorial we will learn how use MAX () in query with mysql
JDBC driver. This tutorial use... values that pass in
Max function i.e "SELECT MAX
Count Row - JSP-Servlet
Count Row Hello all, Please I need your help on how to desplay...();
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "register";
String driver = "com.mysql.jdbc.Driver";
int count= 0
Mysql Max Date
Mysql Max Date
Mysql Max Date is used to return the maximum value of date from a
table.
Understand with Example
The Tutorial illustrate an example from 'Mysql Max
Mysql Max Date
from 'Mysql Max Date'.To grasp this
example we create a table employee1... Mysql Max Date
Mysql Max Date is used to return the maximum value of date
Mysql Min Max
Mysql Min Max
Mysql Min Max is useful to find the minimum and maximum records from a table.
Understand with Example
The Tutorial illustrate an example from Mysql Min Max
SQL Example, Codes and Tutorials
SQL
Functions
MySql
Example... SQL Example, Codes and Tutorials
... to the
pass data value back to the invoker.
SQL Bulk Insert Example
Hibernate Count Query
Hibernate Count Query
In this
section we will show you, how to use the Count Query. Hibernate..., they return an
aggregate value (such as sum, average, and count) calculated from
Hibernate count() Function
the different keywords as the SQL to be written with the
count()
function.
for example :
count( [ distinct | all ] object | object.property)
count(*); also...Hibernate count() Function
In this tutorial you will learn how to use the HQL
SQL Aggregate Queries
Sum, Count, Average, Maximum, Minimum etc.
Understand with Example
The Tutorial illustrate an example from 'SQL Aggregate Queries'. To
understand...
SQL Aggregate Queries
SQL
result per row, use group functions. They are AVG,
COUNT, MAX, MIN & SUM...
SQL
SQL
SQL is an English like language consisting of commands to store, retrieve
Aggregate Functions in SQL, SQL Tutorial
of
which we can use many arithmetic operation like average, count, maximum and many
more in SQL. They are briefly described and denoted by the keyword in the given
below section.
AVG
COUNT
MAX
MIN
SUM
For all of the above given function
JDBC Get Row Count
JDBC Get Row Count
The JDBC Get Row Count enables you to return the row count
of a query. JDBC Get Row... of the column to be retrieved from the table.
Understand with Example
SQL bit
=max(t2.x) or t1.x = min(3 * t3.x)
order by t1.x;
x
3
10
select count(*),sum(x) from t1;
count | sum
------+-----
10 | 55...SQL bit Build a SQL table structure with data that will work
Rows Count Example Using JDBC ResultSet
Rows Count Example Using JDBC ResultSet:
In this tutorial you can count the number of rows in the database table using
ResultSet. Through this example... connection =
null;
String url = "jdbc:mysql://localhost:3306/";
String
SQLl query count and group by
SQLl query count and group by How to write a sql query to count and group by the data?
Sql query to count the data and group the data using group by function...
Name,
Count(Name) As Count
From
Table
Group
Php Sql Number of Rows
Php Sql Number of Rows
This example illustrates how to count the rows of the table.
As per the previous example we create a php page to find the number...;$res = mysql_query($sql);
if (!$res) {
SQL
SQL - SQL Introduction
SQL - An Introduction to the Structured Query Language
SQL stands for Structured Query Language (SQL), a standard language used for creating, updating, querying
Count Records using the Prepared Statement
\PreparedStatement>java CountRecords
Count records example using prepared... Count Records using the Prepared Statement
... to count all records
of the database table by using the PreparedStatement
PHP SQL Number of Rows
;
This example illustrates how to count the rows of the table.
To understand how to count the number of rows in a table, we have created a sql_num_rows.php...;* from users";
$res = mysql_query($sql
Hibernate Criteria Max Date Example
Hibernate Criteria Max Date Example How to write example program... the following links:
Example: Hibernate Criteria Max Date.
Check the tutorial... for finding max Date in Java program then check the following links:
Example
JDBC Select Count example
JDBC Select Count example
In this tutorial we will learn how work COUNT() in query with mysql
JDBC driver. This tutorial COUNT(*) ... NULL values. Table of user :
Mysql query "SELECT COUNT(*) FROM
Hibernate criteria count.
Hibernate criteria count. How do we count rows using criteria in hibernate?
Create hibernate configuration file (hibernate.cfg.xml... correctly the max results and such
run the alias criteria on its own in the same
SQL Functions
the aggregate function ('COUNT', 'MIN', 'MAX', and
'SUM') in the MySQL Query... in this Tutorial illustrate an example from 'Mysql Update'.To
grasp this example we...
The Tutorial in this section illustrate an example from 'Mysql Now Current
Date Time
Ask java count
the results: for example:
| code book | name of book | sum |
| b001... |
| b003 | advanced java book | 26 |
| b004 | MySQL 1
Need help on mySQL 5 - SQL
Need help on mySQL 5 Dear Sir,
I'm a beginner of mySQL 5 . I need... by using Aggregate function(MAX).
May i know that what command i need to enter into the MS DOS using aggregate function MAX to display the output as shown
Hibernate Criteria Count Example
Hibernate Criteria Count Example Example of Hibernate Criteria Count.
Check the tutorial Hibernate Criteria Count.
Check the Latest tutorials, articles and examples of Hibernate Framework.
Thanks
MYSQL - SQL
MYSQL how to select last row in table?(MYSQL databse)
How to select last row of the table in mySql
Here is the query given below selects tha last row of the table in mySql database.
SELECT * FROM stu_info
Get Column Count using ResultSet in SQL
Get Column Count using ResultSet in SQL
This
example counts the number of columns in a table...;url = "jdbc:mysql://localhost:3306/";
String
Mysql Date Max
Mysql Date Max
Mysql Date return you the maximum rows or records value from a table.
Understand with Example
The Tutorial illustrate an example from Mysql Date Max. To grasp
Hibernate criteria query using Max()
Hibernate criteria query using Max() What is Hibernate criteria query using Max()?
You can find out maximum value in hibernate criteria... setProjection method.
Here is an example:
Example:
package net.roseindia.projection
Hibernate Criteria
Java bigdecimal max example
Java bigdecimal max example
Example below demonstrates the working of bigdecimall class max() method. Java max method analysis the
bigdecimal
objects value and returns
sql - SQL
the example
and also what is the data type for image in database..
pleas send the answer to me with example of table and servet.
Hi friend... connectionURL = "jdbc:mysql://192.168.10.211:3306/amar";
java.sql.Connection
SQL Date, SQL Date Examples
The Tutorial illustrate an example from Mysql Date Max. To grasp... are the list of tutorials for manipulating the Date in your sql.
Mysql...
sql. The Query used
in the below example the now( ) return you
java sql - JSP-Servlet
("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://192.168.10.211:3306/";
String db = "amar";
String driver...(request.getParameter("offset").toString());
}
int total_count = 0;
int
Hibernate Criteria Count Distinct Example
Count Distinct?
Thanks
Here is an example of Hibernate Criteria...Hibernate Criteria Count Distinct Example I am learning Hibernate and trying to find good example of Hibernate.
I want example of Hibernate
Php Sql Null
Php Sql Null
This example illustrates to describe about null value of execution of sql
query in php.
In this example we select data from database...;
$result = mysql_query( $sql, $conn
qurey - SQL
").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql...();
String strQuery = "select count(*) from user_details where username
sql
sql returning value from a store procedure in sql with example
Please visit the following links:
JAVA to SQL
++) {
System.out.println("Coloumn Count : "+sheet.getCell(i, 0).getContents());
}
}
public... :
String DBCONNSTRING = "jdbc:mysql://localhot:3306/mysql";
//Provided by your driver documentation. In this case, a MySql driver is used
SQL Aggregate Functions Where Clause
with Example
The Tutorial illustrate an example from SQL Aggregate Function...
SQL Aggregate Functions Where Clause
SQL Aggregate Functions Where Clause is used
Java BigInteger max value
is as
follows:
public BigInteger max(BigInteger val)
In our java example code we...
Java BigInteger max value
We can use the max() method of the BigInteger
class to get
count in java - Java Beginners
count in java Hello javamania....
i want to ask something like... is 20.
i have JFrame Form(jTextField,jLabel,jButton), i want to get count of gender, like if jTextfield =male then count of male=50 and if jTextfield=female
SQL
SQL Trigger query Why we use the Trigger and what it's uses?
... customized database management system. For example, you can use triggers to:
1..., user events, and SQL statements to subscribing applications
10)Restrict DML
Hibernate Criteria Set Max Results
Hibernate Criteria Set Max Results
The set max result of hibernate criteria...%"));
criteria.setMaxResults(1);
List list = criteria.list();
An example of set max result is given below
CriteriaSetMaxResult.java
package
Count words in a string method?
Count words in a string method? How do you Count words in a string?
Example:
package RoseIndia;
import java.io.BufferedReader;
import...=br.readLine();
int count=0;
String arr[]=st.split
Count Rows from a Database Table
Count Rows from a Database Table
...:
For this program to work firstly we need to establish
the connection
with MySQL... then
it will show "SQL statement is
not executed!"
Description of code
SQL
SQL what data type we use for the uploading the video and image files in MySQL server 2008
javascript max size
javascript max size How to retrive Max size in JavaScript
SQL
a highly customized database management system. For example, you can use triggers... events, user events, and SQL statements to subscribing applications
10)Restrict DML
SQL
a highly customized database management system. For example, you can use triggers..., user events, and SQL statements to subscribing applications
10)Restrict DML
SQL
customized database management system. For example, you can use triggers to:
1... events, and SQL statements to subscribing applications
10)Restrict DML
Sql question
Sql question How to display duplicate values in Sql?
Hi Friend,
Please visit the following link:
Thanks
SQL Aggregate Functions Where Clause
. The
Aggregate Function include Sum , Count, Max, Min and Average.
Understand with Example
The Tutorial illustrate an example from 'SQL Aggregate Functions...
SQL Aggregate Functions Where Clause
SQL
with example
How to make a connection from javaME with MySQL - SQL
and MySQL.
I really hoping someone could help me on my final year project...);
charLine.setLength(0);
int count = 0;
for(int i = 0; i <... {
charLine.append(' ');
}
if(++count >
mysql select statement - SQL
mysql select statement i want to select id,name,age values from... a[])
{
Connection con = null;
String url = "jdbc:mysql... for more information with example
Thanks
mysql - SQL
mysql hi
i want to export my data from mysql to excel using php script. pls help me Hi Friend,
Please visit the following link:
Thanks
MySQl - SQL
MySQl How to Remove password for root in MY SQl.....?
Please Provide the steps Immediately
sql - SQL
order by SQL Query What is order by in SQL and when this query is used in SQL?Thanks! Hi,In case of mysql you can user following query.Select salary from salary_table order by salary desc limit 3,1Thanks
MySQL - SQL
MySQL how to set a time to repeat a trigger in Mysql? Hi Friend,
Please visit the following links:
NSArray Count Example
NSArray Count Example
In the example, we are going to count the number of elements in an array in objective c programming.
In Objective C language, Count... in an array.
Syntax of count method in objective c language
- (NSUInteger)count.
SQL Aggregate Functions In Where Clause
with Example
The Tutorial help you to understand an Example from 'SQL Aggregate... SQL Aggregate Functions In Where Clause
SQL Aggregate Function In Where Clause return
division in sql
count ( member_id) from member)
output = 2005
Now i have to divide above 2... in sql
what is retain count in objective c
what is retain count in objective c what is retain count in objective c ?
retainCount in Objective c
retainCount: retain count method is used to show the internal count of the given object so that programmer can
SQL Aggregate Functions First
illustrate an example from SQL Aggregate Functions First. The
Example create a table... SQL Aggregate Functions First
SQL Aggregate Function First, that performs calculation
mysql - SQL
mysql How to insert the check box values in mysql database through php | http://www.roseindia.net/tutorialhelp/comment/98339 | CC-MAIN-2014-52 | refinedweb | 2,795 | 55.74 |
I found some information here about how to install an application in Qtopia, but I can't get it to work. It's possible that I misinterpreted some of the directions that I found, so I thought that perhaps someone could point to my error if I carefully describe what I did.
1. I put my app (myapp.py) in /home/QtPalmtop/bin (which is in my path).
2. I made myapp.py executable. The first line is
#! /usr/bin/env python
The line that calls QPEApplication is:
app = QPEApplication(['myapp.py'])
I do:
from qtpe import QPEApplication
3. I created a file in /home/QtPalmtop/apps/Applications called myapp.desktop. It contains the lines
[Desktop Entry]
Comment=What my program does
Exec=myapp.py
Type=Application
Name=MyApp
4. I rebooted
An icon appears on the Applications page. When I click on it, it changes to the clicked icon and I see an hourglass. Then the hourglass disappears and my app does not run. I presume that it crashed. When I run it from a command prompt (by typing myapp.py), it runs fine. I hope that someone can see what I did wrong -- or can at least suggest a diagnostic procedure. For example, does Qtopia log error messages somewhere? Is there a way to capture error messages emitted during program startup? Thanks. | http://www.oesf.org/forum/lofiversion/index.php/t11827.html | CC-MAIN-2018-26 | refinedweb | 224 | 69.58 |
Program on Quicksort on Linked List in C++
In this tutorial, we are going to learn about Quicksort on Linked List in C++. Firstly we are going to look at linked list. Secondly about the quicksort and finally to combine them.
Introduction
Linked List
Linked list is a data type in which nodes are linked with each other. In a linked list node can be of different data type and is created using by a structure in c++. Single linked list contains a single link to the next node.
Quicksort
Quicksort is performed using the concept of divide and conquer. It takes an element as pivot and partitions the given array around the picked pivot. It is one of the fastest sorting algorithms.
Perform Quicksort on Linked List in C++
Firstly, we have to create a program to create a linked list and then fill it up with data.
Secondly, in the created linked list we apply quicksort.
Code:
#include <iostream> #include <cstdio> using namespace std; struct Node { int data; struct Node *next; }; void insert(struct Node** head_ref, int new_data) { struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } void print(struct Node *node) { while (node != NULL) { cout<<node->data<<" "; node = node->next; } cout<<"\n"; } struct Node *getTail(struct Node *cur) { while (cur != NULL && cur->next != NULL) cur = cur->next; return cur; } struct Node *partition(struct Node *head, struct Node *end, struct Node **newHead, struct Node **newEnd) { struct Node *pivot = end; struct Node *prev = NULL, *cur = head, *tail = pivot; while (cur != pivot) { if (cur->data < pivot->data) { if ((*newHead) == NULL) (*newHead) = cur; prev = cur; cur = cur->next; } else { if (prev) prev->next = cur->next; struct Node *tmp = cur->next; cur->next = NULL; tail->next = cur; tail = cur; cur = tmp; } } if ((*newHead) == NULL) (*newHead) = pivot; (*newEnd) = tail; return pivot; } struct Node *quickSortRecur(struct Node *head, struct Node *end) { if (!head || head == end) return head; Node *newHead = NULL, *newEnd = NULL; struct Node *pivot = partition(head, end, &newHead, &newEnd); if (newHead != pivot) { struct Node *tmp = newHead; while (tmp->next != pivot) tmp = tmp->next; tmp->next = NULL; newHead = quickSortRecur(newHead, tmp); tmp = getTail(newHead); tmp->next = pivot; } pivot->next = quickSortRecur(pivot->next, newEnd); return newHead; } void quickSort(struct Node **headRef) { (*headRef) = quickSortRecur(*headRef, getTail(*headRef)); return; } int main() { struct Node *start = NULL; int t,num; cout<<"Enter the number of elements: "; cin>>t; while(t--){ cin>>num; insert(&start, num); } quickSort(&start); cout << "Linked List after sorting \n"; print(start); return 0; }
INPUT:
Enter the number of elements: 5 2 1 6 4 3
OUTPUT:
Linked List after sorting 1 2 3 4 6
Explanation:
Firstly the number of elements is taken in input are insert inside the linked list. Then linked list is sorted using quicksort.
Written below is the algorithm for quicksort for linked list:
- After selecting an element as pivot, which is the last element of the linked list in our case, we divide the array for the first time.
- In quicksort, we call this partition. It is not simple, breaking down of linked list into 2 linked lists, but in case of partitioning, the linked list elements are so positioned that all the elements smaller than the pivot will be on the left side of the pivot and all the elements greater than the pivot will be on the right side of it.
- And the pivot element will be at its final sorted position.
- The elements to the left and right, may not be sorted.
- Then we pick linked lists, elements on the left of pivot and elements on the right of pivot, and we perform partition on them by choosing a pivot in the linked lists.
Also Checkout:
Count the number of occurrences of an element in a linked list in c++ | https://www.codespeedy.com/program-on-quicksort-on-linked-list-in-cpp/ | CC-MAIN-2019-43 | refinedweb | 627 | 65.56 |
hello there,
when i was going through separate interface for implememtation where writing the classes in some file .h and the class member function in someother file .cpp.
my question here is in the .h file. while writing the classes we tend to include #ifndef, #define and #endif. like for example
can any one please tell me why is that and what is the use of including that in the header file.can any one please tell me why is that and what is the use of including that in the header file.Code:#include DATE1_H --->> what is the need of thos ?? #define DATE1_H --->> " ?? class date { private: int day; int month; int year; public: date(int, int, int); date(); void setdate(int, int, int); bool isleap(); void printdate(); }; #endif ----->> what is the need of this??
thax very much | https://cboard.cprogramming.com/cplusplus-programming/62206-help-please.html | CC-MAIN-2017-13 | refinedweb | 138 | 81.83 |
C++ Graphics¶
Once you completed the graphics setup instructions, you now have two graphics libraries on your system: OpenGL and Glut. Both of these have a huge number of folks working to build some pretty cool graphics applications. We are not ready to do that, but we can tap into their work and do some fun stuff. The problem is that even with the new addition we installed, all of this is still too complicated.
Adding the class files¶
I have created a simple pair of files we can add to our projects to build simple graphics applications. Most significant programs involve more than one file, so this is not at all unusual.
The two files we will need are:
-
Graphics.cpp- new graphics functions we can use
-
Graphics.h- Needed to tie your program to the graphics routines
We will add the first file to our program project, then
include the second
file in our graphics programs. CLion will take care of hooking everything
together.
Setting up a demo¶
To get all this working do this:
Now, we need to check things:
- Edit the
main.cppfile for it says “Graphics Demo” instead of “Hello World”
- Run this code to make sure everything is set up correctly
- Save your project as usual
This program needs a bit more setup than our earlier work. You will be adding two more files to your project. If you are getting overwhelmed by all this, please be patient. I will give you plenty of time and help to get things going. Just follow the notes and know that many classes before you have gotten through this, and had fun with the result!
Hello, Graphics World¶
Modify your
main.cpp file so it looks like this:
#ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/glut.h> #endif #include "Graphics.h" void drawScene(void) { // your code goes here } int main(int argc, char ** argv) { graphicsSetup(argc, argv); glutDisplayFunc(drawScene); glutMainLoop(); }
That stuff looks pretty scary! The first few lines will make this program work on either a Mac of a Windows PC. (That sure looks like a strange IF-THEN-ELSE, and it is, but those lines are aimed at the compiler!) You probably are using a PC, but others, including me, are using Mac systems. This is a common issue in programming since the two systems set things up differently.
Make sure you type everything you see exactly as shown. The names and function
calls you see for things like
glutDisplayFunc are parts of the
Glut
library, and they set up the program to draw the things we see in our
drawScene procedure. It may seem strange to put the name of one procedure
into the call to another procedure as a parameter, but it is legal, and is
required by
glut to make it draw images on the screen. For now, just
consider it magic!
Wait, we are not done¶
The code just shown is incomplete. See the “your code goes here” line? We will put our own code here. Make sure you do not mess anything else up! We also need to add out additional files.
Adding the Graphics files¶
Copy the needed files from the folder you set up when you worked through the CLion Graphics Setup notes.
-
Graphics.cpp
-
Graphics.h
-
CMakeLists,txt
Once this is finished, you should have three files in your project
Graphics Procedures¶
Now, we can now draw simple shapes
- Boxes
- Circles
- Triangles
We can also control the colors used
Graphics window¶
All drawing is done in a 500x500 pixel window. A
pixel is one dot on your
screen. There is a
coordinate system associated with this window.
-
Xruns from 0 to 500 from left to right.
-
Yruns from 0 to 500 from bottom to top
- (The
originis in the lower left corner)
The simple graphics procedures I have provided give you the ability to draw a few simple objects on the screen and control where they are and what size and color they are. The code creates a square window on your screen 500 pixels wide and 500 pixels high. (A pixel is one dot on your screen, which is probably running with 1024 pixels horizontally, and 768 vertically (or more if you have a newer system). In the procedures I have created, the origin of the system is at the lower left corner of the window. x coordinates go from 0 at the left to 500 at the right, and y goes from 0 at the bottom, to 500 at the top. You will need to figure out what coordinates (x,y) you need to work with when you use the simplified graphics procedures. Here are the routines you can use for starters:
Drawing boxes¶
To get started, here are a couple of new functions:
- drawBox(x1,y1,x2,y2)
- drawFilledBox(x1,y1,x2,y2)
Here x1,y1 and x2,y2 define the box. These points are the opposite
corners of the box. These functions do not return a value. You
call them
by putting them on a line by themselves. Make sure you end the line with a
semicolon!
Remember that when you use these functions in your program, they are a
statement all by themselves and will need a semicolon after them like all
statements in
C++ do.
How about a circle¶
This function draws a circle;
- drawCircle(x,y,radius)
Here x,y is the coordinate of the center of the circle. radius is (well, you know!)
Ready for triangles?¶
These functions draw triangles:
- drawTriangle(x1,y1,x2,y2,x3,y3)
- drawFilledTriangle(x1,y1,x2,y2,x3,y3)
Here, x1,y1, x2,y2, and x3,y3 set the three corners.
Simple lines¶
We can draw a straight line using this function:
- drawLine(x1,y1,x2,y2)
The line goes from x1,y1 to x2,y2.
Setting colors¶
Each graphic object is drawn with a colored pen. You select the color for the pen using this function:
- setColor(color)
-
- where
colorcan be one of these names:
-
- WHITE, BLACK, RED, BLUE, GREEN, GREY, PURPLE, FOREST_GREEN
- MIDNIGHT_BLUE, CYAN, MAGENTA, YELLOW, BROWN
- (case is important here)
You must type in the name in all caps, exactly as shown above. Lower case names, or misspellings will cause errors when you try to compile your code.
A simple demo¶
Here is the code we need to add to test our routines
void drawScene(void) { clearWindow(); setColor(YELLOW); drawFilledTriangle(200,125,100,375,200,375); glEnd(); glutSwapBuffers(); }
Let’s add a few more objects to our drawing Add these lines (inside the
drawScene function:
setColor(BLACK); drawLine(200,200,400,400); setColor(RED); drawFilledCircle(100,100,100); setColor(MAGENTA); drawFilledBox(300,300,400,400);
The Graphics Files¶
Just to make sure you have the current versions of these files (there are several older ones around), here are the files I am using for this class. You do not need to understand what is in these files. They are provided so you can check the files you download, if you run into problems: | http://www.co-pylit.org/courses/cosc1315/simple-graphics/02-opengl-intro.html | CC-MAIN-2018-17 | refinedweb | 1,174 | 70.43 |
The IEEE standard 754-2008 defines several sizes of floating point numbers—half precision (binary16), single precision (binary32), double precision (binary64), quadruple precision (binary128), etc.—each with its own specification. Posit numbers, on the other hand, can be defined for any number of bits. However, the IEEE specifications share common patterns so that you could consistently define theoretical IEEE numbers that haven’t actually been specified, making them easier to compare to posit numbers.
An early post goes into the specification of posit numbers in detail. To recap briefly, a posit<n, es> number has n bits, a maximum of es of which are devoted to the exponent. The bits are divided into a sign bit, regime bits, exponent bits, and fraction bits. The sign bit is of course one bit, but the other components have variable lengths. We’ll come back to posits later for comparison.
IEEE floating point range and precision
We will denote a (possibly hypothetical) IEEE floating point number as ieee<n, es> to denote one with n total bits and (exactly) es exponent bits. Such a number has one sign bit and n – es -1 significand bits. Actual specifications exist for ieee<16, 5>, ieee<32, 8>, ieee<64, 11>, and ieee<128, 15>.
The exponent of a posit number is simply represented as an unsigned integer. The exponent of an IEEE floating point number equals the exponent bits interpreted as an unsigned integers minus a bias.
So the biases for half, single, double, and quad precision floats are 15, 127, 1023, and 65535 respectively. We could use the formula above to define the bias for a hypothetical format not yet specified, assuming the new format is consistent with existing formats in this regard.
The largest exponent, emax is 2es-1 – 1 (also equal to the bias), and the smallest (most negative) exponent is emin = 2 – 2es-1. This accounts for 2es-1 – 2 possible exponents. The two remaining possibilities consist of all 1’s and all 0’s, and are reserved for special use. They represent, in combination with sign and signifcand bits, special values ±0, ±∞, NaN, and denomalized numbers. (More on denormalized numbers shortly.)
The largest representable finite number has the maximum exponent and a significand of all 1’s. Its value is thus
where s is the number of significand bits. And so the largest representable finite number is just slightly less than
We’ll use this as the largest representable value when calculating dynamic range below.
The smallest representable normalized number (normalized meaning the signifcand represents a number greater than or equal to 1) is
However, it is possible to represent smaller values with denomalized numbers. Ordinarily the significand bits fff… represent a number 1.fff… But when the exponent bit pattern consists of all 0’s, the significand bits are interpreted as 0.fff… This means that the smallest denormalized number has a significand of all o’s except for a 1 at the end. This represents a value of
where again s is the number of significand bits.
The dynamic range of an ieee<n, es> number is the log base 10 of the ratio of the largest to smallest representable numbers, smallest here including denormalized numbers.
IEEE float and posit dynamic range at comparable precision
Which posit number should we compare with each IEEE number? We can’t simply compare ieee<n, es> with posit<n, es>. The value n means the same in both cases: the total number of bits. And although es does mean the number of exponent bits in both cases, they are not directly comparable because posits also have regime bits that are a special kind of exponent bits. In general a comparable posit number will have a smaller es value than its IEEE counterpart.
One way to compare IEEE floating point numbers and posit numbers is to chose a posit number format with comparable precision around 1. See the first post on posits their dynamic range and significance near 1.
In the following table, the numeric headings are the number of bits in a number. The “sig” rows contain the number of sigificand bits in the representation of 1, and “DR” stands for dynamic range in decades.
|-----------+----+-----+------+-------| | | 16 | 32 | 64 | 128 | |-----------+----+-----+------+-------| | IEEE es | 5 | 8 | 11 | 15 | | posit es | 1 | 3 | 5 | 8 | | IEEE sig | 10 | 23 | 52 | 112 | | posit sig | 12 | 26 | 56 | 117 | | IEEE DR | 12 | 83 | 632 | 9897 | | posit DR | 17 | 144 | 1194 | 19420 | |-----------+----+-----+------+-------|
Note that in each case the posit number has both more precision for numbers near 1 and a wider dynamic range.
It’s common to use a different set of posit es values that have a smaller dynamic range than their IEEE counterparts (except for 16 bits) but have more precision near 1.
|-----------+----+-----+------+-------| | | 16 | 32 | 64 | 128 | |-----------+----+-----+------+-------| | IEEE es | 5 | 8 | 11 | 15 | | posit es | 1 | 2 | 3 | 4 | | IEEE sig | 10 | 23 | 52 | 112 | | posit sig | 12 | 27 | 58 | 122 | | IEEE DR | 12 | 83 | 632 | 9897 | | posit DR | 17 | 72 | 299 | 1214 | |-----------+----+-----+------+-------|
Python code
Here’s a little Python code if you’d like to experiment with other number formats.
from math import log10 def IEEE_dynamic_range(total_bits, exponent_bits): # number of significand bits s = total_bits - exponent_bits - 1 return (2**exponent_bits + s - 2)*log10(2) def posit_dynamic_range(total_bits, max_exponent_bits): return (2*total_bits - 4) * 2**max_exponent_bits * log10(2)
Next: See the next post for a detailed look at eight bit posits and IEEE-like floating point numbers.
6 thoughts on “Comparing range and precision of IEEE and posit”
A good question to ask of a fixed/floating numeric format is how many values exist within a given interval.
A common use is to sanity-check the bounds used for equality testing, and allowing for all the corner cases.
How does the distribution of representable posit numbers compare to that of floating point? If I remember correctly, when the precision changes in floating point, there’s a larger range of unrepresentable numbers in the gap between the two precision “zones” than there is between two numbers in the zones to either side of the gap, is that also true for posits? How large are the jumps in precision?
Good question. My next post addresses this in the case of 8-bit numbers.
I’ve been thinking about this as as I’ve begun messing with deep neural nets. Everything is usually squished to (-1, 1) or (0, 1). But the floating point representation can only have at most 2^32 slots to pass out, many of these must be outside of the range. One must be hitting the empty slots over and over in running a model. Does this pattern of defined slots and gaps have some sort of ‘color’ in the IEEE spec? Maybe there would be some sort of simple way to push all the slots into the range one is actually using.
Why do you use formula (2*total_bits – 4) * 2**max_exponent_bits * log10(2) for calculating dynamic range for posits? Your formula describes the general situation and it results from the assumption that all bits after sign bit are 1’s and belong to the regime part.
In the example presented in table, you assume that the regime part consists of 2 bits only. So for 16 bit posit with 2 bits for the regime and 1 for exponent minimum value is u^-1 = 1/4. The maximum value is almost 4.
log10(16) = 1.2
So what’s the point of talking about dynamic range with assumption that regime consists of 2 bits?
Just to point out a minor error: the bias for ieee should be 2^14 – 1 = 16383, and not 65535. | https://www.johndcook.com/blog/2018/04/14/ieee-vs-posit/ | CC-MAIN-2022-40 | refinedweb | 1,278 | 59.94 |
You can subscribe to this list here.
Showing
7
results of 7
> 3. Someone with gs 8.13 (or one that works) generates the polygon-scan.png
> and homography.png files, and adds them into the repository
Remarkably, I just found out that these two .png files have been in the
repository (and are still in the Attic, of course) but were removed (by
you!) because they could be generated from the .eps files ;-)
Here is the CVS log for both PNG files:
RCS file: /cvsroot/vxl/vxl/core/doc/book/Attic/polygon-scan.png,v
----------------------------
revision 1.2
date: 2003/06/11 11:47:22; author: scottim; state: dead; lines: +0 -0
After Peter's wonderful fixes of EPS files, the documentation building
scripts can
process all of them correctly - so hand generated png files are not needed.
----------------------------
revision 1.1
date: 2003/06/06 11:47:03; author: peter_vanroose; state: Exp;
texi2html expects .png, not .eps
=============================================================================
Anyhow, I've added them back now.
-- Peter.
> I will be happy to provide the figures in a different format. They were
> originally jpeg. I converted them to eps so that I could view them in
> the compiled texi document.
Actually, I redesigned two of the pictures with Xfig to get rig of the jpeg
aliasing. So the png should better be generated directly from the Xfig
files (or equivalently from the .eps).
-- Peter.
On Mon, 5 Jan 2004, Frederik Schaffalitzky wrote:
> On Mon, 5 Jan 2004, Brad King wrote:
>
> > Hello,
> >
> > The win32-vc60/vcl_cmath.h is currently implemented like this:
> [deleted]
> > This introduces declarations into std, which is not technically allowed.
> > While it works fine for vxl code that uses vcl, it may conflict with
> > non-vcl-ized code (such as an application that does using namespace std
> > and also includes math.h).
>
> It is not allowed in a conforming implementation, no, but then again VC60
> is not conforming! [If it were then we would not be worrying about the
> ceil() missing from the std:: namespace.]
>
> Are you sure the "using" scenario you mention would actually be a problem?
Yes, because this was the scenario in which I found the problem. A small
example application I was trying to build was exposing it.
> Something that would be a problem is code (from some another project,
> say) that also tries to "fix" std:: in the same way. I think it is
> important for the ability of VXL to "bolt onto" existing projects that
> VCL not mess with the way the vendor library works.
Yes, of course this would be a problem too.
> > I suggest we change the implementation to work like this:
> [deleted]
>
> I think that would be better than the current approach.
Okay, I'll do the new implementation when I get a chance. It will have to
be synchronized with vcl_complex to get vcl_abs setup correctly.
-Brad
Hello,
The win32-vc60/vcl_cmath.h is currently implemented like this:
#include <math.h>
namespace std {
// ...
inline float ceil( float f ) { return ::ceilf(f ); }
inline double ceil( double f ) { return (double)::ceil(double(f) ); }
inline long double ceil( long double f ) { return (long double)::ceil(double(f) ); }
// ...
}
# define vcl_generic_cmath_STD std
#include "../generic/vcl_cmath.h"
This introduces declarations into std, which is not technically allowed.
While it works fine for vxl code that uses vcl, it may conflict with
non-vcl-ized code (such as an application that does using namespace std
and also includes math.h). I suggest we change the implementation to work
like this:
#include <math.h>
inline float vcl_ceil( float f ) { return ::ceilf(f ); }
inline double vcl_ceil( double f ) { return (double)::ceil(double(f) ); }
inline long double vcl_ceil( long double f ) { return (long double)::ceil(double(f) ); }
#define vcl_ceil vcl_ceil
-Brad
JPEGS and PNGs will work with pdflatex, and presumably pdftex, thus
allowing
pdf versions of the manual rather than DVI. Maybe someone could just
try to
pdftex book.texi
I will be happy to provide the figures in a different format. They were
originally jpeg. I converted them to eps so that I could view them in
the compiled texi document. Isn't it true that latex/texi requires eps
files? The conversion jpeg->eps was done using image_magick. It would
be nice to have a solution so that latex previews of texi are compatible
with the texi->html process.
Joe
o----o----o----o----o----o----o
Professor of Engineering (Research)
Barus and Holley Bldg., Room 351
Brown University
Providence, RI
401-863-2655
Sorry, about the delay. I've been off on holiday.
It looks like the problem is the version of ghostscript.
The version of gs I'm using is
clue_rbt@...:/tmp> gs -v
GNU Ghostscript 6.53 (2002-02-13)
about a year older than Peter's version. Unfortunately I can't just update
the postscript rpm on paine (a SuSe Linux box,) because of some
dependencies.
I'm not too happy about trying to build and install the latest AFPL gs
(8.13) or GNU gs (7.03) myself (because of all the font hassles,) unless
someone convinces me that it is trivial.
Anyway, I'm a little worried that we are relying on a very recent version of
gs to build the book. Lots of people would have difficulty building it if
they need gs 8.13.
So to solutions:
1. Someone convinces me that it is easy to build and install gs 8.13
2. Someone regenerates the two eps files so that they work with gs 6.53
But by far the easiest:
3. Someone with gs 8.13 (or one that works) generates the polygon-scan.png
and homography.png files, and adds them into the repository in the book
directory, removes the polygon-scan.eps and homography.eps files from the
repository, and commits the changes. scripts/doxy/gen_book.pl will find the
png files and use them instead of attempting to generate them from the eps.
(It does the same with jpeg files as well.)
Ian.
> -----Original Message-----
> From: Peter Vanroose [mailto:Peter.Vanroose@...]
> Sent: Monday, December 22, 2003 10:03 PM
> To: Joseph Mundy
> Cc: Ian Scott
> Subject: RE: [Vxl-maintainers] Figures in vgl
>
>
> > Yes, but texi requires a encapsulated postscript version of
> the image.
> > Then, there is some magic process that converts texi to html. This
> > magic process seems to fail to produce a displayable image.
>
> OK, then the problem lies in either the texi2html program (a
> perl script)
> or the command "makeinfo --html", whichever you use to generate html.
>
> -- Peter.
> | http://sourceforge.net/p/vxl/mailman/vxl-maintainers/?viewmonth=200401&viewday=5&style=flat | CC-MAIN-2015-40 | refinedweb | 1,085 | 67.15 |
real world example that I thought of to illustrate this (which might make you hungry) involves muffins. Well, Muffin objects (as we are talking Javano coffee pun intended). Suppose you have a DelayQueue upon which you place Muffin objects. The Muffin object (shown below) must implement the java.util.concurrent.Delayed interface to be placed on a DelayQueue. The interface requires the Muffin object to implement the getDelay method (shown below). The getDelay method, in essence, states how much time is left for the object to be kept in the DelayQueue. When the number returned by this method becomes zero or less than zero, the object is ready (or in this example, baked) and allowed to be dequeued (shown in Listing 3).
The Muffin class also implements the compareTo(java.util.concurrent.Delayed) method. Since the Delayed interface extends from the java.lang.Comparable class, this binds you by contract to implement the bakeCompletion time of the Muffin object.
Since you don't really want to eat a Muffin that's not fully cooked, place the Muffin on the DelayQueue for the recommended cooking time. Listing 4, taken from the class DelayQueueUsageExample, shows the queuing and dequeuing of the Muffin objects from the DelayQueue.
As you can see, the cooking time for a Muffin object is set using its constructor (the constructor expects the cooking time to be in seconds).
As stated before, the Muffin objects placed on the DelayQueue are not allowed to be dequeued until their delay time (a.k.a. cooking time) has expired. Elements are dequeued from the queue based on the oldest delay time. In this example, if you have a number of Muffin objects that have been cooked, they will be dequeued on a basis of how long they've been waiting to be dequeued (in other words, the oldest cooked Muffins get the dequeued before the newest cooked Muffins).
Catch 22The SynchronousQueue
Another blocking queue implementation Java 1.5 makes available is the SynchronousQueue. Interestingly enough, this queue doesn’t have an internal capacity. This is intentional, as the queue is meant for handoff purposes. This means that in a synchronous queue setup, a put request must wait for a take request to the SynchronousQueue from another thread. At the same time, a take request must wait for a put request to the SynchronousQueue from another thread. To demonstrate the concept programmatically, take a look at the sample code. Similar to the LinkedBlockingQueue example earlier, it contains a consumer (SynchConsumer), which is shown in Listing 5.
The code in Listing 5 uses the poll (long timeout, TimeUnit unit) method of the SynchronousQueue class. This method allows for the polling process to wait for a specified amount of time (in this case 20 seconds) before getting tired of waiting for another thread to write to the SynchronousQueue for consumption.
The producer (SynchProducer) shown in Listing 6 uses a similar offer(E o, long timeout, TimeUnit unit) method to enqueue objects on the SynchronousQueue. Use of this method allows a wait time (in this case, 10 seconds) before getting tired of waiting for another thread to read from the SynchronousQueue.
TestSynchQueue shows the producer and consumer in action:
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class TestSynchQueue
{
public static void main(String args[])
{
SynchronousQueue<String> synchQueue = new SynchronousQueue<String>();
SynchProducer producer = new SynchProducer("ProducerA",synchQueue, System.out);
SynchConsumer consumerA = new SynchConsumer("ConsumerA", synchQueue, System.out);
consumerA.start();
producer.start();
}
}
"They [synchronous queues] are well suited for handoff designs, in which an object running in one thread must sync up with an object running in another thread in order to hand it some information, event, or task."
Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled.
Your name/nickname
Your email
WebSite
Subject
(Maximum characters: 1200). You have 1200 characters left. | http://www.devx.com/Java/Article/21983/0/page/4 | CC-MAIN-2018-39 | refinedweb | 645 | 64 |
, namespace (followed by the assembly in parentheses), and type category of the type. It may also specify various additional flags that describe the type. The type name appears in bold at the upper left of the title. The namespace and assembly appear, in smaller print, in the lower left, below the type name.
In the upper-right corner of the title, you may find a list of flags that describe the type. The possible flags and their meanings are as follows:
The type is part of the ECMA CLI specification.
The type, or a supertype, implements System.Runtime.Serialization.ISerializable or has been flagged with the System.Serializable attribute.
This class, or a superclass, derives from System.MarshalByRefObject .
This class, or a superclass, derives from System.ContextBoundObject .
The type implements the System.IDisposable interface.
The enumeration is marked with the System.FlagsAttribute .
The lower-right portion of the title indicates the type category of the type (class , delegate , enum , interface , or struct ). The class category may include modifiers such as sealed or abstract . a lot like its source code, except that the member bodies are omitted, and some additional annotations are added. If you know C# syntax, you supertype or interfaces that the type implements.
The type definition line is followed by a list of the members that the type defines. This list includes only those members that are explicitly declared in the type, are overridden from a base class, or are implementations of an interface member. Members that are simply inherited from a base class aren aren't to be used literally. The member listings are printed on alternating gray and white backgrounds to keep them visually separate.
Each member listing is a single line that defines the API for that member. These listings use C# syntax, so their meaning is immediately clear to any C# programmer. There is some auxiliary information associated with each member synopsis, however, that requires explanation.
The area to the right of the member synopsis displays a variety of flags that provide additional information about the member. Some of these flags indicate additional specification details that don't appear in the member API itself.
The following flags may be displayed to the right of a member synopsis:
Indicates that a method overrides a method in one of its supertypes. The flag is followed by the name of the supertype that the method overrides.
Indicates that a method implements a method in an interface. The flag is followed by the name of the interface that is implemented.
For enumeration fields and constant fields, this flag is followed by the constant value of the field. Only constants of primitive and String types and constants with the value null are displayed. Some constant values are specification details, while others are implementation details. The reason symbolic constants are defined, however, is so you can write code that doesn't rely directly upon the constant value. Use this flag to help you understand the type, but don't rely upon the constant values in your own programs.
Within a type synopsis, the members aren't listed in strict alphabetical order. Instead, they are broken into functional groups and listed alphabetically within each group. Constructors, events, fields, methods, and properties are all listed separately. Instance methods are kept separate from static C# comments, such as // Public Constructors, // Protected Instance Properties, and // Events. The various functional categories are as follows (in the order in which they appear in a type synopsis):
Displays the constructors for the type. Public constructors and protected constructors are displayed separately in subgroupings. If a type defines no constructor at all, the C# compiler adds a default no-argument constructor that is displayed here. If a type defines only private constructors, it can't static properties and public and protected instance properties. After the property name, its accessors (get or set ) are shown.
Lists the static methods (class methods) of the type, broken into subgroups for public static methods and protected static methods.
Contains all public instance methods.
Contains all protected instance methods.
For any type that has a nontrivial inheritance hierarchy, the synopsis is followed by a Hierarchy section. This section lists all the supertypes of the type, as well as any interfaces implemented by those supertypes. It also lists any interfaces implemented by an interface. In the hierarchy listing, arrows indicate supertype-to-subtype relationships, while the interfaces implemented by a type follow the type name in parentheses. For example, the following hierarchy indicates SomeClass implements IDisposable and extends MarshalByRefObject , which itself extends Object :
System.ObjectSystem.MarshalByRefObjectSomeClass a number of optional cross-reference sections that indicate related types and methods that may be of interest. These sections are the following:
This section lists all the members (from other types) that are passed an object of this type as an argument, including properties whose values can be set to this type. This is useful when you have an object of a given type and want to know where it can be used.
This section lists all the members that return an object of this type, including properties whose values can take on this type. This is useful when you want to work with an object of this type but don't know how to obtain one.
For attributes, this lists the attribute targets the attribute can be applied to.
For delegates, lists the events it can handle.
Throughout the quick reference, you'll notice that types are sometimes referred to by type name alone and at other times. They can be summarized approximately as follows, however:
If the type name alone is ambiguous, the namespace name is always used.
If the type is part of the System namespace or is a commonly used type such as. | http://etutorials.org/Programming/ado+net/Part+III+API+Quick+Reference/Chapter+32.+How+to+Use+This+Quick+Reference/32.2+Reading+a+Quick-Reference+Entry/ | CC-MAIN-2020-34 | refinedweb | 960 | 55.95 |
jGuru Forums
Posted By:
mikey_jay
Posted On:
Thursday, November 7, 2002 12:13 PM
Hello All,
I have written some fairly large shell scripts.
I have also written a simple java GUI that contains a button that will run the script.
The script runs.
The problem is that I cannot see the output from the script in the x-term that I used to run my java class file.
Has anyone out there solved this problem or know of a way that I can?
Thanks
Re: Viewing output from a unix shell script.
Posted By:
michael_dean
Posted On:
Thursday, November 7, 2002 12:55 PM
You have to capture the output and do something with it. To capture the script's standard output, call getInputStream() (to get an InputStream that reads from the process's standard output stream--there's also a getOutputStream() and a getErrorStream() for writing to standard input and reading from standard error, respectively) on the Process reference returned by the call to the Runtime's exec(...) methods.
getInputStream()
InputStream
getOutputStream()
getErrorStream()
Process
Runtime
exec(...)
For example, to echo the standard output from a script file called ./test.sh:
./test.sh
#!/bin/shecho This is some output.echo This is more output.echoecho 'This is a test.'echo 'This is only a test.'echo Had this been a real emergency...
to the standard output of the Java application, execute the following Java application:
import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.io.IOException; public class Test { public static void main(String[] args) { try { Runtime rt = Runtime.getRuntime(); Process p = rt.exec("./test.sh"); InputStream is = p.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; while((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.err.println(e); e.printStackTrace(); } }} | http://www.jguru.com/forums/view.jsp?EID=1022908 | CC-MAIN-2015-06 | refinedweb | 307 | 58.69 |
This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.
On Tue, 2007-10-23 at 18:44 +0100, Dave Korn wrote: > On 23 October 2007 18:25, skaller wrote: > > > In > > > > > > g-Vars > > > > it explains how to use register variables .. but doesn't list them. > > > > Is there a document somewhere which lists > > > > a) each CPU macro name > > Don't at all understand what you're referring to there. Macro? You mean a > #define? Name of the cpu? I don't see anything referring to the cpu name in > the explicit reg vars docs. Sorry, I thought it was obvious.. I want to write: #if defined(AMD64) register void *stack asm ("%rsp"); #elsif defined(X86) register void *stack asm ("%esp"); #elsif defined (SPARC) register void *stack asm ("%stack"); .... #else #error "CPU NOT SUPPORTED" #endif Hmm .. actually I just checked in more depth how Boehm does this, and it is clever enough to avoid all this: int * nested_sp() { int dummy; return(&dummy); } Ouch .. I should have thought of that! And he's using setjmp to save registers plus other hacks I can steal.. :) However I may want to reserve a register, so I still need a list with ABI details (which ones are caller-saved). -- John Skaller <skaller at users dot sf dot net> Felix, successor to C++: | http://gcc.gnu.org/ml/gcc/2007-10/msg00365.html | CC-MAIN-2019-18 | refinedweb | 223 | 83.76 |
I'm trying to use the News API in a python program, and for some reason I can't get a 200 response no matter what. I'm pretty unfamiliar with the requests library, so maybe I'm not doing something right, but here's what my code looks like:
api = XXXXXXXXXX
def get_json_response(apiKey, resource='google-news', sortBy='latest'):
url = ''
headers = { 'source': resource,
'apiKey': apiKey,
'sortBy': sortBy}
r = requests.get(url, headers=headers)
print(r.status_code)
get_json_response(api)
r = requests.get(url + '/?source=' + resource + '&sortBy=' + sortBy + '&apiKey=' + apiKey)
Based on the 'working' link provided, it expects URL parameters, not headers on its request, so:
def get_json_response(apiKey, resource='google-news'): url = '' params = {'source': resource, 'apiKey': apiKey} r = requests.get(url, params=params) print(r.status_code) # etc. | https://codedump.io/share/9JrHiRef7Ap9/1/python-requests-for-newsapi-reponding-401-every-time | CC-MAIN-2017-39 | refinedweb | 127 | 54.22 |
Perl::Critic::Policy::Modules::RequireFilenameMatchesPackage - Package declaration must match filename.
This Policy is part of the core Perl::Critic distribution.
The package declaration should always match the name of the file that contains it.
For example,
package Foo::Bar; should be in a file called
Bar.pm.
This makes it easier for developers to figure out which file a symbol comes from when they see it in your code.
For instance,
when you see
Foo::Bar->new(),
you should be able to find the class definition for a
Foo::Bar in a file called Bar.pm
Therefore,
this Policy requires the last component of the first package name declared in the file to match the physical filename.
Or if
#line directives are used,
then it must match the logical filename defined by the prevailing
#line directive at the point of the package declaration.
Here are some examples:
# Any of the following in file "Foo/Bar/Baz.pm": package Foo::Bar::Baz; # ok package Baz; # ok package Nuts; # not ok (doesn't match physical filename) # using #line directives in file "Foo/Bar/Baz.pm": #line 1 Nuts.pm package Nuts; # ok package Baz; # not ok (contradicts #line directive)
If the file is not deemed to be a module, then this Policy does not apply. Also, if the first package namespace found in the file is "main" then this Policy does not apply.
This Policy is not configurable except for the standard options.
Chris Dolan <cdolan@cpan.org>
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. | http://search.cpan.org/~thaljef/Perl-Critic-1.120/lib/Perl/Critic/Policy/Modules/RequireFilenameMatchesPackage.pm | CC-MAIN-2014-23 | refinedweb | 266 | 64.61 |
NAME
Module::Extract::Use - Discover or are in the import lists for parent or base.
The module can handle the conventional inclusion of modules with either
use or
require as the statement:
use Foo; require Foo; use Foo 1.23; use Foo qw(this that);
It now finds
require as an expression, which is useful to lazily load a module once (and may be faster):
sub do_something { state $rc = require Foo; ... }
Additionally, it finds module names used with
parent and
base, either of which establish an inheritance relationship:
use parent qw(Foo); use base qw(Foo);
In the case of namespaces found in
base or
parent, the value of the
direct method is false. In all other cases, it is true. You can then skip those namespaces:
my $details = $extor->get_modules_with_details( $file ); foreach my $detail ( @$details ) { next unless $detail->direct; ... }
This module does not discover runtime machinations to load something, such as string evals:
eval "use Foo"; my $bar = 'Bar'; eval "use $bar";
If you want that, you might consider Module::ExtractUse (a confusingly similar name).
- new
Makes an object. The object doesn't do anything just yet, but you need it to call the methods.
- init
Set up the object. You shouldn't need to call this yourself.
- get_modules( FILE )
Returns a list of namespaces explicity use-d in FILE. Returns the empty list.
- get_modules_with_details( FILE ) direct - false if the module name came from parent or
SEE ALSO
Module::ScanDeps, Module::Extract
SOURCE AVAILABILITY
The source code is in Github:
AUTHOR
brian d foy,
<bdfoy@cpan.org>
This project is under the Artistic License 2.0. | https://metacpan.org/pod/release/BDFOY/Module-Extract-Use-1.047/lib/Module/Extract/Use.pm | CC-MAIN-2020-50 | refinedweb | 267 | 62.98 |
During one of my most recent events, I needed to connect PureData on my Raspberry Pi up to a physical switch to toggle a Bang event. For those that don’t use Raspberry Pi or PureData that probably sounded like gobbledegook.
The Raspbery pi is:
a series of small single-board computers developed in the United Kingdom by the Raspberry Pi Foundation to promote the teaching of basic computer science in schools and in developing countries.
It’s a brilliant and affordable way to control projects and interactive installations and all sorts. It’s the brains behind my Hummingbird installation and I’ve been using it in conjunction with PureData to do a lot of the maths for some projects too.
a visual programming language developed by Miller Puckette in the 1990s for creating interactive computer music and multimedia works.
It’s a really easy way to get into controlling any complex bits of a project you might need and you don’t need to code to do it! It’s all based on visual commands with connecting lines and boxes and whatnot. I’d highly recommend playing around with it, it’s a lot of fun and even with basic knowledge of how it works you can pull off some great ideas. And, what’s great, is that Raspberry Pi is powerful enough to run PureData so you can have it running on a teeny tiny board and massively cut down any bulk to a project that may have otherwise needed computers to function.
SO, I needed a physical switch on my Hummingbird to trigger a simple Bang object in Puredata. There are a few bits online about how to do this, but none of them worked for me and some of the links ended up in dead ends and 404s. So, my work around, was to use another programme called Processing to set up a netsend/netreceive communication within the raspberry pi.
I do not claim to be an expert, and there are probably easier ways and more efficient ways to get this to happen, but for now let me share how I managed it.
In Processing, I had this code running, with a physical switch between GPIO pin 4 and Ground.
import processing.net.*;import processing.io.*;Client myClient;Server myServer;int val = 0;int bang = 0;void setup() {GPIO.pinMode(4, GPIO.INPUT);// Starts a myServer on port 5204myClient = new Client(this, “127.0.0.1”, 5204);}void draw() {// sense the input pinif (GPIO.digitalRead(4) == GPIO.HIGH) {bang = 0;} else {bang = 1;}{myClient.write(bang +”;”);}}
And then, within Puredata, I had a netreceive object for the same Port as listed in the Processing code (5204):
This meant, whenever the switch was closed, the code in Processing read this as HIGH and then sent a number 1 via netsend/netreceive on port 5204 which puredata then used the sel 1 command to trigger a bang!
If you want send send other values i’m sure it’s possible too, the only thing i’d say is it’s important to include the + “;” when you send data as this is what the programmes use to determine when the message has ended. | https://vulpestruments.com/2018/01/16/connecting-raspberry-pi-and-puredata/ | CC-MAIN-2020-29 | refinedweb | 534 | 55.98 |
Alice goes for jogging every day for N meters. Sometimes she runs and sometimes she walks. Her walking speed is 1m/s and running speed is 2m/s . Given the distance up to which she does jogging, calculate the number of ways she can do jogging.
example:
Input: 3 (total distance covered during jogging)
Output: 3 (possible case)
Explanation: Alice could jog in 3 ways
- Alice Walks for 3 meter
- Alice Run for 2 meters and then walks for 1 m
- Alice walks 1m and then run 2m
Example 2:
Input: 4
Output: 5
Explanation: Alice could jog in 5 ways
- Alice walk for all 4 meters
- Alice walk for first 2 meters and then run for 2 meters
- Alice could run for 2 meters and then walk for 2 meters
- Alice walk for 1 meters and then run for 2 meters and then walk for 1 meters
- Alice run for all 4 meters
I have solved above problem statement using following code
from itertools import permutations n = int(input()) c = 0 t = [2]*(n//2) if n % 2 != 0: t = t+[1] for i in range(t.count(2)): c = c+len(set(list(permutations(t, len(t))))) t.remove(2) t.append(1) t.append(1) c = c+len(set(list(permutations(t, len(t))))) print(c)
I’m new in dynamic programming, any one can help me ? how i can implement this in dynamic approach method and achieve more optimum time complexivity?
Thankyou very much for giving your valuable towards my problem.
Answer
Inspired by all earlier posts, and the unwritten assumptions being confirmed, this is just another fib-sequence question.
Credits to all earlier posters. (the code is quite simple then) Just for reference – hope it helps.
def jogging_ways(n: int) -> int: # f(3) = f(1) + f(2) a, b = 1, 1 for i in range(n): a, b = b, a+b #print(a, b) return a
Running:
> jogging_ways(4) 5 > jogging_ways(5) 8 | https://www.tutorialguruji.com/python/dynamic-programming-approach-issue/ | CC-MAIN-2021-39 | refinedweb | 328 | 67.49 |
On Thu, 12 Aug 2004 17:11:45 -0400Bill Davidsen <davidsen@tmr.com> wrote:> > But they *don't* map to consistent device names. All hot pluggable > devices seem to map to the next available name. Looking at one of my > utility systems, it has IDE drives mapped by Redhat with ide-scsi, real > SCSI drives, a couple of flash card slots mapped to SCSI, and a USB > device, all in the /dev/sdX namespace. And in the order in which they > were detected (connected, in other words).> > Joerg hasn't made it any better, but it isn't great anyway. I recommend > a script to do discovery and make symlinks somewhere to names which > always match the same device.> That's exactly what udev allows you to do (among a lot of other things).Marc-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | https://lkml.org/lkml/2004/8/12/246 | CC-MAIN-2015-11 | refinedweb | 163 | 65.01 |
Write program adds large integers using linked listsemplois
Hello I am looking for a similar application ( see the application and give me the price t...
As disucssed
As discussed
As discussed.
We have a large list of roughly 20,000 websites to scrape 13,000 keywords from each to check how many times and if the words appear in the websites.
...first.
I want to promote my lunch video add on youtube with help of google adds.
Create a command-line tool C program, which implements a non-limited range integer calculator. The program should be able to: handle arbitrary integers, their input in multiple lines (choose a continuation symbol, like: ), carry out the five integer base operations as they work in.
I need some help with internet app marketing to promote my app to a large audience which includes young men and women and big adults.
A project in which we need to read integers from a file of 80-byte records, with zero or more numbers per record, and store the integers in a table.
job at hand writing an email to attract costumers and selling them an idea....
Veuillez vous inscrire ou vous connecter pour voir les détails.: [se connecter pour voir l'URL]
Would like to hire someone professional about Linked in business page. That person will build our linked in business page like pro.
I need a simple program in Java, C++ or C# that will do restoring division utilizing bitwise shifting two integers. Must be able to divide positive and negative numbers - use 8 bit registers. Can provide more details.
I need 2 (Two) banner adds - Banner Size: 728x90 and 300x250 - to promote a concert tour
I need someone to copy information from some websites.
import search filter large json file . search edit export data in many ways xls pdf etc.. will provide sample of small file and example data inside it once we discuss. winner of this project who place best bid . thanks...
...the.
I have a website with a google shop. I need google advertisement for my products.
looking for email lists dumper who can get mail lists from databases.
I need an expert that can rewrite my resume, cover letter and optimise my LinkedIn profile. The service should be exceptional. The person should have an in depth knowledge of the ATS system and how it works as regards resume development
there is only to improve the edges of the logo in better format with optimal reshaping me.... ... | https://www.fr.freelancer.com/job-search/write-program-adds-large-integers-using-linked-lists/ | CC-MAIN-2018-43 | refinedweb | 416 | 72.36 |
Bug Description
Dear Developer,
I have installed the newest YADE trunk on Ubuntu 16.04 and finished the compilation with the option DUSE_QT5=ON. But when i run the executable file, the following error jumps out:
gcf@gcf-
Welcome to Yade 2018-06-
TCP python prompt on localhost:9000, auth cookie `csduse'
XMLRPC info provider on http://
Traceback (most recent call last):
File "./yade-
import yade.qt
File "/media/
from PyQt5 import QtWebKit, QtWebKitWidgets
ImportError: cannot import name QtWebKit
I opened the python and tried to import the QtWebKit, but it seems that there is no QtWebKit in the PyQt5.
gcf@gcf-
Python 2.7.15 |Anaconda, Inc.| (default, May 1 2018, 23:32:55)
[GCC 7.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from PyQt5 import QtWebkit
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name QtWebkit
>>> import PyQt5
>>>
Please see [1] for similar problem and solution by Klaus:
/answers. launchpad. net/yade/ +question/ 446239
https:/ | https://bugs.launchpad.net/yade/+bug/1776853 | CC-MAIN-2019-04 | refinedweb | 169 | 65.62 |
MAX30101 Module¶
MAX30101 Class¶
- class
MAX30101(i2cdrv, addr=0x57, clk=400000)¶
Creates an intance of the MAX30101 class.
Example:
from maxim.max30101 import max30101 ... m301 = max30101.MAX30101(I2C0) m301.start() m301.init() data = m301.read_raw_samples(6)
init(mode = 'spo2', adc_range = 3, sample_rate = 50, pulse_width = 411, led_current = [255,255,0,0], proximity_thrs = 0, slot_multi = [0,0,0,0] )¶
Initialize the MAX30101. Default paramter values enable
"spo2"- without proximity - mode with: maximum ADC range, sampling rate of 50 Hz, LED pulse width of 411us and maximum pulse amplitude for both red and IR LEDs..
set_sample_averaging(n)¶
To reduce the amount of data throughput,
nadjacent samples (in each individual channel) can be averaged and decimated on the chip by using this method. Accepted values for
nare: 1,2,4,8,16 and 32.
set_fifo_rollover(ro = True)¶
This method controls the behavior of the FIFO when the FIFO becomes completely filled with data. If
rois
True, the FIFO Address rolls over to zero and the FIFO continues to fill with new data. If
rois
False, then the FIFO is not updated until FIFO is read or the FIFO WRITE/READ pointer positions are changed.
set_fifo_afv(n)¶
This method sets the trigger for the
"full"interrupt. The interrupt triggers when there are
nempty spaces left in FIFO.
Interrupt configuration¶
enable_interrupt(source)¶
Set bit on enable interrupt registers corresponding to the selected source. ‘sources’ must be a list including one or more available sources. Available values for ‘sources’ are:
"full": in spo2 or hr mode, this interrupt triggers when FIFO has a certain number of free spaces remaining.
"data": in spo2 or hr mode,.
read_triggered_interrupt()¶.
Mode configuration¶
shutdown()¶
Put the part into a power-save mode. While in power-save mode, all registers retain their values, and write/read operations function as normal. All interrupts are cleared to zero in this mode.
reset()¶
All configuration, threshold, and data registers are reset to their power-on-state through a power-on reset.
set_mode(mode, adc_range, sample_rate, pulse_width, led_current, proximity_thrs, slot_multi)¶). | https://docs.zerynth.com/latest/official/lib.maxim.max30101/docs/official_lib.maxim.max30101_max30101.html | CC-MAIN-2020-24 | refinedweb | 333 | 57.67 |
232 votes
1 answers
shopify - Change the page_title value for only one page
I'm trying to change the page title for my "all products" page but i don't manage to get it work. I want to set the page title for this page only.
Here is my code which I put in the theme.liquid file in the
<title> tag:
{%- if page_title == "Products" -%} {% assign page_title = "Paintings" } {%- endif -%}
Undefined asked
110
votes
Answer
Solution:
If this is the default "All products collection", this should work:
{%- if collection.handle == 'all' -%} {% assign page_title = "Paintings" } {%- endif -%}
Undefined answered
Source
Didn't find the answer?
Our community is visited by hundreds of Shopify development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
246 shopify - Is it possible to redirect myshopify admin page or change query from imbedded app in PHP?
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger. | https://e1commerce.com/items/change-the-page-title-value-for-only-one-page | CC-MAIN-2022-40 | refinedweb | 179 | 65.22 |
This chapter contains these topics:
XDK Java Components Specifications
Installing XDK Java Components
XDK Java Components Directory Structure
XDK Java Components Environment Settings
XDK Java Components Globalization Support
XDK Java Components Dependencies
Verifying the XDK Java Components Version
XDK Java components, release 10.1, are built on these specifications:
XML 1.0 (Second Edition)
DOM Level 2.0 Specifications
DOM Level 2.0 Core
DOM Level 2.0 Traversal and Range
DOM Level 2.0 Events
DOM Level 3.0 Specifications
DOM Level 3.0 Load and Save (internal draft version 10 October 2003)
DOM Level 3.0 Validation (Candidate Recommendation 30 July 2003)
SAX 2.0 and SAX Extensions
XSLT/XPath 2.0 Specifications
XSL Transformations (XSLT) 2.0 (working draft dated 02 May 2003)
XML Path Language (XPath) 2.0 (working draft dated 22 August 2003)
XPath 2.0 Data Model (working draft dated 11th November 2002)
XML Schema Specifications
XML Schema Part 0: Primer
XML Schema Part 1: Structures
XML Schema Part 2: Datatypes
XML Pipeline Definition Language 1.0
Java API for XML Processing 1.1 and 1.2 (JAXP)
Java Architecture for XML Binding 1.0 (JAXB)
In release 10.1, the DOM APIs include support for two new working drafts, DOM Level 3 Validation and DOM Level 3 Load and Save.
Load and Save
The DOM Level 3 Load and Save module enables software developers to load and save XML content inside conforming products. DOM 3.0 Core interface
DOMConfiguration is referred by DOM 3 Load and Save. Although DOM 3.0 Core is not supported, a limited implementation of this interface is available.
The following configuration parameters are supported by
XMLDOMBuilder which implements
LSParser:
"cdata-sections"
"validate"
"validate-if-schema"
"whitespace-in-element-content"
The following configuration parameters are supported by
XMLDOMWriter which implements
LSSerializer:
"format-pretty-print"
"xml-declaration"
Validation
DOM 3.0 validation allows users to retrieve the metadata definitions from XML schemas, query the validity of DOM operations and validate the DOM documents or sub-trees against the XML schema.
Some DOM 3 Core functions referred by Validation are implemented, but Core itself is not supported:
NameList and
DOMStringList in DOM core are supported for validation purpose.
Validation is based on XML Schema, DTD needs to be converted to Schema first (use
DTDToSchema utility).
The XSLT processor adds support for the current working drafts of XSLT 2.0, XPath 2.0, and the shared XPath/XQuery data model.
For the XPath 2.0 specification, only the new XPath 2.0 grammar and backwards compatibility with XPath 1.0 are supported.
These features of the specifications are not supported in release 10.1:
The functions in the Functions and Operators specification are not supported. Only the functions from XSLT 1.0 specification are supported.
The
validate and
complex types in
SequenceType expressions are not supported.
The new datatypes
fn:yearMonthduration and
fn:dayTimeDuration are not supported.
The Schema Import and Static Typing features are not supported.
The XSLT instructions
xsl:result-document and
xsl:namespace are not supported.
The XSLT instructions
xsl:text and
xsl:number use XSLT 1.0 semantics and syntax.
The standard attributes are allowed only on
xsl:stylesheet and literal result elements, except for
default-xpath-namespace and
version.
The processor does not honor the following attributes:
[required] on
xsl:param
[XML Schema related attributes, like
xsl:validation and
xsl:type, etc.
Regular expression functions are not supported.
Parameters are not passed through built-in templates.
xsl:sequence is not supported
XDK Java components are included with the Oracle database and with the Oracle application server. You can download the latest beta or production version of XDK Java components from OTN as part of the XDK. The XDK Java components and JavaBeans are now bundled together.
If you installed XDK with the Oracle database or the Oracle application server, you can use this chapter as a reference.
If you download the XDK from OTN, follow these steps:
Go to the URL:
Click the Software link on the right-side of the page.
Logon with your OTN username and password (registration is free if you do not already have an account).
Select the Windows or UNIX download.
Select the appropriate download for your operating system.
Accept all terms of the licensing agreement and then download the software by clicking the appropriate distribution.
Extract the files in the distribution:
Choose a directory under which you want the
./xdk directory and subdirectories to go.
Change to that directory and then extract the XDK Java components download archive file. For UNIX:
tar xvfz xdk_XXXX.tar.gz # UNIX. XXXX is the release name Use WinZip visual archive extraction tool in Windows
After installing the XDK, the directory structure is:
-$XDK_HOME | - bin: executable files and setup script or batch files. | - lib: library files. | - xdk: | - admin: (Administration): SQL script and XSL Servlet Configuration file (XSQLConfig.xml). | - demo/java: demonstration code | - doc/java: documents including release notes and Javadoc HTML.
All the XDK Java components are certified and supported with JDK 1.2, JDK 1.3, and JDK 1.4. Make sure that your CLASSPATH includes all the necessary libraries:
In addition, XML SQL Utility, XSQL Servlet, and TransX Utility all depend on JDBC and globalization support libraries, which are listed in Table 2-2:
The UNIX and Windows environment settings are listed:
This file sets up the environment:
$XDK_HOME/bin/env.csh
Table 2-3 lists the UNIX environment variables, with the ones that must be customized each marked with "Yes":
The XSQL Servlet is designed to run on any Java VM, using any JDBC driver, against any JDBC-enabled database. Oracle Corporation tests it against only the most popular configurations.
XSQL Pages and XSQL Servlet have been successfully tested only with:
JDK 1.2.2
JDK 1.3
JDK 1.4
This XSQL Servlet has been tested with the following servlet engines:
Oracle HTTP Server/JServ Servlet Engine
Oracle9iAS Oracle Containers for J2EE
Java Server Pages (JSP) can use
<jsp:forward> and/or
<jsp:include> to collaborate with XSQL Pages as part of an application. The following JSP platforms have been tested:
Oracle9iAS Oracle HTTP Server/JServ Servlet Engine works well against any database with a reasonable JDBC driver. While numerous users have reported successfully using XSQL Pages with many other JDBC drivers, the ones that Oracle has tested are:
Oracle8i 8.1.5 Driver for JDBC 1.x9i 9.2.0 Driver for JDBC 2.0
The demos are set up to use the
SCOTT schema on a database on your local computer (the computer where the Web server is running). If you are running a local database and have an account
SCOTT whose password is
TIGER, then you are all set. Otherwise, you need to edit the
.\xdk\admin corresponding to the Web server. In every case, there are these basic steps:
Include the list of XSQL Java archives:
xsu12.jar - Oracle XML SQL Utility
xmlparserv2.jar - Oracle XML Parser for Java V2
oraclexsql.jar- Oracle XSQL Pages
xsqlserializers.jar - Oracle XSQL Serializers for FOP/PDF Integration
classes12.jar - Oracle JDBC Driver or the JAR file for the JDBC driver you will be using instead
Include as well as the directory where XSQLConfig.xml resides (by default
./xdk/admin) in the server
CLASSPATH.
Map the
.xsql file extension to the
oracle.xml.xsql.XSQLServlet servlet class.
Map a virtual directory
/xsql to the directory where you extracted the XSQL files (to access the online help and demos).
The following sections describe the instructions specific to these Web servers:
Oracle Application Server (OracleAS)
OracleAS Oracle Containers for Java (OC4J) Servlet Container
Jakarta Tomcat 3.1 or 3.2
OracleAS comes preconfigured to run XSQL Servlet. By default its Apache JServ servlet engine contains all of the
wrapper.classpath entries in
jserv.conf to include the necessary Java archives to run XSQL. The
XSQLConfig.xml file is found in the
./xdk/admin subdirectory of the iAS installation home.
The easiest way to install XSQL Servlet in the OracleAS OC4J servlet container is to install it as an application. Assuming your OC4J installation home is
C:\j2ee\home, and that you have extracted the XDK distribution into the
C:\xdk directory, here are the setup steps:
Verify that the following JAR files are already in your
C:\j2ee\home\lib directory (they should come pre-installed):
xmlparserv2.jar - Oracle XML Parser for Java V2
classes12.jar - Oracle JDBC Driver
Copy the following additional JAR files from
C:\xdk\lib to
C:\j2ee\home\lib.
xsu12.jar - Oracle XML SQL Utility
oraclexsql.jar - Oracle XSQL Pages
x
sqlserializers.jar - Oracle XSQL Serializers for FOP/PDF Integration
Copy the
C:\xdk\admin\XSQLConfig.xml configuration file to the
C:\j2ee\home\default-web-app\WEB-INF\classes directory.
Edit the
C:\j2ee\home\config\global-web-application.xml server configuration file to add a
<servlet> and
<servlet-mapping> entry as child elements of the
<web-app> element as follows:
<orion-web-app ...and so on... > ... is processed by the XSQL Servlet. If you want to try the XSQL built-in samples, demos, and online help, then you need to perform the following additional step to map a virtual path of
/xsql/ to the
C:\xdk\demo\java\xsql directory.
Edit the file:
c:\j2ee\home\application-deployments\default\defaultWebApp\orion-web.xml
to add the following
<virtual-directory> entry:
<orion-web-app ...and so on...> ... etc ... <virtual-directory ... etc ... </orion-web-app>
Then, you can browse the demos using the URL:
Set up the server
CLASSPATH correctly for the XSQL Servlet. This is done by editing the JServ configuration file named
jserv.properties.
Assuming that you installed the XSQL Servlet files into C:\, you need to add the following entries to use the Oracle JDBC 1.x driver:
#.jar
To use the Oracle JDBC 2.0 Driver, the entries are:
#.jar
Map the
.xsql file extension to the XSQL Servlet: To do this, you need to edit the JServ configuration file named
jserv.conf (in JServ 1.0 this was named
mod_jserv.conf on some platforms). Add the following lines:
# Executes a servlet passing filename with proper extension in PATH_TRANSLATED # property of servlet request. # Syntax: ApJServAction [extension] [servlet-uri] # Defaults: NONE ApJServAction .xsql /servlets/oracle.xml.xsql.XSQLServlet
Map an
/xsql/ virtual directory: In this step, we want to map the virtual path
\xsql\ to
C:\xdk902\xdk\demo\java\xsql\ (or wherever you installed the XSQL Servlet files). To do this, you need to edit the Apache configuration file named
httpd.conf and add the following line:
Alias /xsql/ "C:\xdk902\xdk\demo\java\xsql\"
Restart the Apache server and browse the URL:
Do the following steps:
Set up the Server CLASSPATH for the XSQL Servlet:
This is done by editing the Tomcat startup script named
tomcat.bat in
./jakarta-tomcat/bin and adding the appropriate entries onto the system
CLASSPATH before the Tomcat server is started.
For Oracle JDBC 1.x
For Oracle JDBC 2.0
Map the .xsql File Extension to the XSQL Servlet:
Tomcat supports creating any number of configuration contexts to better organize the Web applications that your site needs to support. Each context is mapped to a virtual directory path, and has its own separate servlet configuration information. XSQL Servlet comes with a preconfigured context file to make XSQL Servlet setup easier.
By default, Tomcat 3.1 and 3.2 come preconfigured with the following contexts (defined by
<Context> entries in the file
./jakarta-tomcat/conf/server.xml).
The root context
/examples
/test
/admin
Install XSQL Servlet into one of these, but for simplicity create a new context just for the XSQL Servlet that maps to the directory where you installed the XSQL Servlet distribution.
Edit the
./jakarta-tomcat/conf/server.xml file to add the following
<Context> entry with path=
"/xsql".
<Context path="/test" docBase="webapps/test" debug="0" reloadable="true" /> <!-- | Define a Servlet context for the XSQL Servlet | | The XSQL Servlet ships with a .\WEB-INF directory | with its web.xml file preconfigured for C:\xdk902\xdk\demo\java\xsql | installation. +--> <Context path="/xsql" docBase="C:\xdk902\xdk\demo\java\xsql"/>
Note that the
docBase= "C:\xsql" points to the physical directory where you installed the XSQL Servlet distribution. You then need to create a WEB-INF subdirectory in the
C:\xdk902\xdk\demo\java\xsql directory and save the following
./WEB-INF/web.xml file in
/xsql Virtual Directory:
This is already achieved by creating the
/xsql context in the preceding section.
Restart the Tomcat server and browse the URL:
If you use Tomcat with an XML Parser (such as the Sun Crimson Parser) that only supports DOM Level 1 interfaces, then you must edit
tomcat.bat to insure that the Oracle XML Parser's archive
xmlparser.jar comes before the DOM Level 1 parser's archive in the
CLASSPATH. For example, you could edit
tomcat.bat to add the following lines:
REM NEED TO PUT xmlparserv2.jar FIRST before parser.jar set CP=C:\xdk902\lib\xmlparserv2.jar;%CP%
just before the lines:
echo Using CLASSPATH: %CP% echo. set CLASSPATH=%CP%
Here is a summary on the settings that relate to Globalization Support:
Using
xmlmesg.jar: If you are using a language other than English you need to set the
xmlmesg.jar into your
CLASSPATH to let the parser get correct messages in your language.
Using
orai18n.jar: If you are using a multibyte character set other than one of the following,
UTF-8
ISO8859-1
JA16SJIS
then you must set this JAR file into your Java
CLASSPATH so that JDBC can convert the character set of the input file to the database character set during the loading of XML files using either XSU, TransX or XSQL Servlet.
Figure 2-1 shows the dependencies of XDK Java Components when using JDK 1.2 and higher:
Figure 2-1 XDK Java Components Dependencies Using JDK 1.2.x and Higher
After you correctly setup the environment, include all the necessary JAR files in your CLASSPATH. You can then start writing your Java programs and compiling them with the
javac command:
javac your_program.java
If the compilation finishes without errors, then you can just test your program using the command line or the Web Server.
To obtain the version of XDK you are working with, compile and run the following Java code (
XDKVersion.java):
import java.net.URL; import oracle.xml.parser.v2.XMLParser; public class XDKVersion { static public void main(String[] argv) { System.out.println("You are using version: "); System.out.println(XMLParser.getReleaseVersion()); } } | http://docs.oracle.com/cd/B13789_01/appdev.101/b10794/adx02get.htm | CC-MAIN-2015-27 | refinedweb | 2,427 | 50.53 |
Initialize a Condition Variable
Destroy a Condition Variable
Wait for an Absolute Time
#include <thread.h> int cond_init(cond_t *cv, int type, int arg);
Use cond_init(3THR) to initialize the condition variable pointed to by cv. The type can be one of the following (note that arg is currently ignored). (For POSIX threads, see pthread_condattr_init(3THR).)
USYNC_PROCESS The condition variable can be used to synchronize threads in this and other processes. arg is ignored.
USYNC_THREAD The condition variable can be used to synchronize threads in this process only. arg is ignored.
Condition variables can also be initialized by allocation in zeroed memory, in which case a type of USYNC_THREAD is assumed.
Multiple threads must not initialize the same condition variable simultaneously. A condition variable must not be reinitialized while other threads might be using it.
#include <thread.h> cond_t cv; int ret; /* to be used within this process only */ ret = cond_init(cv, USYNC_THREAD, 0);
#include <thread.h> cond_t cv; int ret; /* to be used among all processes */ ret = cond_init(&cv, USYNC_PROCESS, 0);
#include <thread.h> int cond_destroy(cond_t *cv);
Use cond_destroy(3THR) to destroy state associated with the condition variable pointed to by cv. The space for storing the condition variable is not freed. (For POSIX threads, see pthread_condattr_destroy(3THR).)
#include <thread.h> int cond_wait(cond_t *cv, mutex_t *mp);
Use cond_wait(3THTHR).)
#include <thread.h> int cond_timedwait(cond_t *cv, mutex_t *mp, timestruct_t abstime);
Use cond_timedwait(3THR) as you would use cond_wait(), except that cond_timedwait() does not block past the time of day specified by abstime. (For POSIX threads, see pthread_cond_timedwait(3THR).).
#include <thread.h> int cond_reltimedwait(cond_t *cv, mutex_t *mp, timestruct_t reltime);
Use cond_reltimedwait(3THR) as you would use cond_timedwait(), except that cond_reltimedwait() takes a relative time interval value in its third argument rather than an absolute time of day value. (For POSIX threads see, pthread_cond_reltimedwait_np(3THR)._signal(cond_t *cv);
Use cond_signal(3TH.
#include <thread.h> int cond_broadcast(cond_t *cv);
Use cond_broadcast(3THR) to unblock all threads that are blocked on the condition variable pointed to by cv. When no threads are blocked on the condition variable then cond_broadcast() has no effect. | http://docs.oracle.com/cd/E19683-01/806-6867/6jfpgdcol/index.html | CC-MAIN-2016-22 | refinedweb | 352 | 57.77 |
CodePlexProject Hosting for Open Source Software
Hi,
I would like to extend the default settings offered by Orchard to include one where the user can select an image which would then be displayed as the logo for the site (rather than the default which displays the site name).
Is there any working examples of this I could have a look at?
Thanks
Interesting timing. I wrote a module that does exactly that last night, for a customer. I may be able to release it on the gallery but here is how it works: it's a theme that you only activate, without making it the current theme. It has an admin theme selector
that looks like this, to override the default admin theme:
public class AdminThemeSelector : IThemeSelector {
public ThemeSelectorResult GetTheme(RequestContext context) {
if (AdminFilter.IsApplied(context)) {
return new ThemeSelectorResult { Priority = 101, ThemeName = "MyCustomAdminThemeName" };
}
return null;
}
}
The new theme needs to have all the files from TheAdmin, but you can change any of them. In particular, header.cshtml contains the logo. You can add some code in there that reads from some site settings (which will be per tenant) and modifies the rendering
accordingly.
Hi bertandleroy,
I am new to Orchard so still not 100% sure how everything works so it would be great if you could add it to the gallery!
At the minute I have created my own theme (extending TheThemeMachine) and overriding the Branding.cshtml file to display the logo - the goal is to basically make this configurable from the General Settings. If I have understood you correctly you have
just created a new admin theme which includes a picker for a logo? Also, how could I make it render as a media picker?
It's not a picker, just a text field where you can paste the url of the logo.
I was hoping that I could somehow have a media picker (like in the content editor) just to make it easier for the end user.
Is something like this possible?
Of course. Look at the image field for an example.
Since this is probably pretty low priority for a module, would one of you write this up in a reply. I am trying to achieve displaying my site logo in the same element where the default site name displays but cannot seem to modify the branding.cshtml file
correctly to include the logo img in the link.
Write what up?
From: bertrandleroy
Ah, ok. Can you try to paste your code again, but this time using the ïnsert code snippet" button on the editing toolbar? (that's the last button on the toolbar)
@{
var homeUrl = Href("~/");
}
<h1 id="branding"><IMG SRC="SmallLogo.png" alt="Logo" height="60" width="60"/><a href="@homeUrl">@WorkContext.CurrentSite.SiteName</a></h1>
@{
var homeUrl = Href("~/");
}
<h1 id="branding"><IMG SRC="SmallLogo.png" alt="Logo" height="60" width="60"/><a href="@homeUrl">@WorkContext.CurrentSite.SiteName</a></h1>
and where is that smalllogo.png file located? Seems like you should have something like src="@Href("SmallLogo.png")"
Media files should be stored in different folders than the template files. Typically, images go into Content/Images.
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | https://orchard.codeplex.com/discussions/277392 | CC-MAIN-2017-22 | refinedweb | 558 | 66.13 |
I have three variables (password, nonce, and timestamp) and I need to get the value from them using this function:
Base64(SHA1($NONCE + $TIMESTAMP + SHA1($CLEARPASSWORD)))
My code in Postman is:
var clear_password = "AMADEUS";var nonce = "secretnonce10111";var timestamp = "2015-09-30T14:12:15Z";var crypto_pass = btoa(CryptoJS.SHA1(nonce + timestamp + CryptoJS.SHA1(clear_password)));
Using this values the result should be
+LzcaRc+ndGAcZIXmq/N7xGes+k= but the real result is
NWE1MGRhM2ZmNjFhMDA2ODUyNmIxMGM4MTczODQ0NjE2MWQyM2IxZQ==, and this result is like if I was doing:
Base64(HEX(SHA1($NONCE) + $TIMESTAMP + HEX(SHA1($CLEARPASSWORD))))
Is there any way to get the raw result from the SHA1 algorithm instead the HEX??
Thanks in advance.
EDIT
This is what I should to do, but I am stuck in the error of the third point:
I'm trying to pass a random string (which happens to be a number) "4176730.5" to SHA in Haskell to get a larger random string like "2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881".
I have this code to generate a random number and cast it to a string
num <- randomIO :: IO Float let x = C.pack (show (num*10000000)) print x
but when I pass it to SHA with
let a = sha256 x
I get the error
Couldn't match expected type ‘Data.ByteString.Lazy.Internal.ByteString’ with actual type ‘C.ByteString’
I've tried casting my number to C.ByteString, but I think there are two types of Bytestring, according to the Haskell compiler.
The full code is:
import Data.Digest.Pure.SHAimport System.Randomimport qualified Data.ByteString.Char8 as Cmain :: IO ()main = do num <- randomIO :: IO Float let x = C.pack (show (num*10000000)) print x let a = sha256 x b = hmacSha256 "key" "some test message" mapM_ print [showDigest a, showDigest b]
Seeing as how there are apparently two types of Bytestring, and I'm casting to the wrong one, how do I cast my random string correctly?
Further to @Cubic's answer below if I replace import qualified Data.ByteString.Char8 as Cwith
import qualified Data.ByteString.Lazy as C
I just get these errors
Couldn't match type ‘Char’ with ‘GHC.Word.Word8’Expected type: [GHC.Word.Word8] Actual type: String
and
Couldn't match expected type ‘C.ByteString’ with actual type ‘[Char]’
I'm new to Python and I'm creating a login system that hashes the passwords with hashlib. I want to add easygui to the code but don't know how i'd go about it, i've imported easygui and have tried adding multipassword boxes and msgbox. However, everytime i try and implement the gui I always ruin my code, so its not able to read username or password.
Import hashlibfrom easygui import *username = ""def main():global usernameok, name, username = checkLogin()if ok: print("Hello and Welcome to my Logon system", name.upper()) print("\n") runMenu()else: print("that is incorrect, please try again.") print("Thank you for using my system.")def checkLogin(): validUser = False numAttempts = 0 while (not validUser) and numAttempts < 3: uName = input("enter Username: ") pWord = str(hashlib.sha256(input("enter password: ")encode()).hexdigest())if uName in users and pWord == users[uName]['pwd']: validUser = True return True, users[uName]['fName'], uNameelse: numAttempts += 1if uName in users: users[uName]['valid'] = "INVALID"return False
How would you guys go about adding easygui to this code?i've only imported easygui, as I'm confused on how to implement it so i get a username and password box that can verify the password. Also when the user logs in, a choicebox should appear:
def runMenu(): choice = ' ' choices = [None, addUser, changePassword, viewUserDetails, listAllUsers, remUser]while choice != '6': choice = displayMenu() if '1' <= choice <='5': choices[int(choice)]() elif choice != '6' print("invalid input, please enter a number from 1 - 6." )with open('dict.txt', 'wb') as dataFile: dataFile.write(encryptor.ecnrypt(str(users)))#end def
(The username and passwords are stored in a dictionary called dict.txt) Sorry if its confusing as its my first time on stackoverflow! :)
Thanks!
Through the use of openssl's sha 512 algorithm I'm currently able to calculate the hash of a 2GB file in between 3 - 3.3 seconds (my CPU is an i7-5820k) - including the time it takes to open, write to, and close files (open the input & write hash to text file).
I wondered if there are any known methods to speed this process up, or whether my HDD is entirely at fault, creating a bottleneck (Seagate BarraCuda Green 2TB 5900RPM SATA 6Gb/s 64MB Cache).
FILE *ftest=fopen(hashInBuf, "rb"); FILE *ftest2=fopen(hashOutBuf, "wt"); /]);
(the code I'm currently using to calculate the sha 512)
My issue is that when I have the program running, and delete a file in said directory, when it (the same file) is placed back it returns a different value. I wondered whether this code below is the issue?
int main (int argc, char *argv[]){ int fd; int wd; unsigned char c[SHA512_DIGEST_LENGTH]; int i; SHA512_CTX mdContext; int bytes; unsigned char data[1024]; const int event_size = sizeof(struct inotify_event); const int buf_len = 1024 * (event_size + FILENAME_MAX); char *directory = "/home/joe/Documents/"; char *hashDirectory = "/home/joe/Documents/_Hash/"; char hashInBuf[500]; char hashOutBuf[500]; fd = inotify_init(); if (fd < 0) { perror("inotify_init"); } wd = inotify_add_watch(fd, "/home/joe/Documents", IN_CREATE); while (1) { char buff[buf_len]; int no_of_events, count = 0; //SEARCH FOR NEW FILES WITHIN DIRECTORY no_of_events = read (fd, buff, buf_len); while (count < no_of_events) { struct inotify_event *event = (struct inotify_event *)&buff[count]; if (event->len) { if ((event->mask & IN_CREATE)) if(!(event->mask & IN_ISDIR)) { snprintf(hashInBuf, sizeof(hashInBuf), "%s/%s", directory, event->name); snprintf(hashOutBuf, sizeof(hashOutBuf), "%s/%s.txt", hashDirectory, event->name); //OPEN FILES FILE *ftest=fopen(hashInBuf, "rb"); //ORIGINAL FILE FILE *ftest2=fopen(hashOutBuf, "wt"); //HASH FILE (stored in separate directory) /]); } fclose (ftest); fclose (ftest2); fflush (stdout); }} count += event_size + event->len; }} return 0; } //CLOSES INT MAIN
I can assure you the variables are defined correctly as for all intensive purposes it does work, just not correctly.... | https://www.convertstring.com/pl/Hash/SHA384 | CC-MAIN-2019-18 | refinedweb | 984 | 60.55 |
On Fri, Feb 23, 2007 at 11:18:46PM -0500, David Cabana wrote: > I)] This return conflicts with the one in Prelude, and (while similar) they are not interchangable. > -- page 76 > failure :: Parser a > failure = \inp -> [ ] This is analogous to Prelude.fail. Fortunately Hutton didn't call it that :) > item :: Parser Char > item = \inp -> case inp of > [ ] -> [ ] > (x:xs)-> [(x,xs)] Looks reasonable > parse :: Parser a -> String -> [(a,String)] > parse p inp = p inp Same here > -- page 77 > p :: Parser (Char, Char) > p = do x <- item > item > y <- item > return (x,y) > </code> Bad! Due to the Layout Rule that is parsed as a single long statement... I'm quite suprised you didn't get a parse error. It needs to be: p :: Parser (Char, Char) p = do x <- item item y <- item return (x,y) But, this still won't work. essentially the 'do' uses Prelude.return, Prelude.(>>), and Prelude.(>>=), which work on defined Monads; but your parser type is not properly declared as a monad. (and cannot be, because it is a type synonym.) You could define: (>>) :: Parser x -> Parser y -> Parser y (p1 >> p2) l = [ (s,rs2) | (f,rs1) <- p1 l , (s,rs2) <- p2 rs1 ] (>>=) :: Parser x -> (x -> Parser y) -> Parser y (p1 >>= fn) l = [ (s,rs2) | (f,rs1) <- p1 l , (s,rs2) <- fn f rs1 ] then use those (do-notation ignores scope so it must be desugared): p :: Parser (Char, Char) p = item Main.>>= \x -> item Main.>> item Main.>>= \y -> Main.return (x,y) This should work. Famous last words I know :) >. | http://www.haskell.org/pipermail/haskell-cafe/2007-February/022839.html | CC-MAIN-2013-48 | refinedweb | 256 | 78.59 |
# How to push parameters into methods without parameters in safe code
Hello. This time we continue to laugh at the normal method call. I propose to get acquainted with the method call with parameters without passing parameters. We will also try to convert the reference type to a number — its address, without using pointers and *unsafe code*.

### Disclaimer
Before proceeding with the story, I strongly recommend that you read the previous [post about StructLayout](https://habr.com/en/post/446478/). Here I will use some features, that were described there.
Also I would like to warn that this article does not contain material that should be used in real projects.
### Some initial information
Before we start practicing, let's remember how the C# code is converted into assembler code.
Let us examine a simple example.
```
public class Helper
{
public virtual void Foo(int param)
{
}
}
public class Program
{
public void Main()
{
Helper helper = new Helper();
var param = 5;
helper.Foo(param);
}
}
```
This code does not contain anything difficult, but the instructions generated by JiT contain several key points. I propose to look only on a small fragment of the generated code. in my examples I will use assembler code for 32 bit machines.
```
1: mov dword [ebp-0x8], 0x5
2: mov ecx, [ebp-0xc]
3: mov edx, [ebp-0x8]
4: mov eax, [ecx]
5: mov eax, [eax+0x28]
6: call dword [eax+0x10]
```
In this small example, you can observe fastcall — calling convention that uses registers to pass parameters (the first two parameters from left to right in the ecx and edx registers), and the remaining parameters are passed through the stack from right to left. The first (implicit) parameter is the address of the instance of the class on which the method is called (for non-static methods).
In our case first parameter is the address of the instance, second one is our **int** value.
So int the **first** line we see the local variable 5, there is nothing interesting here.
In the **second** line, we copy the address of the Helper instance into the ecx register. This is the address of the pointer to method table.
In the **third** line there is copying of local variable 5 into the edx register
In the **fourth** line we can see copying of the method table address into the eax register
**Fifth** line contains loading of the value from memory at the address 40 bytes larger than the address of the method table: the start of the methods addresses in the method table. (The method table contains various information that is stored before. For example address of the base class method table, the EEClass address, various flags, including the garbage collector flag, and so on). Thus, the address of the first method from the method table is now stored in the eax register.
*Note: In .NET Core the layout of the method table was changed. Now there is field (at 32/64 bit offset for 32 and 64 bit systems respectively) that contains the address of the start of method list.*
In the **sixth** line, the method is called at offset 16 from the beginning, that is, the fifth one in the method table. Why is our only method is fifth? I remind you that **object** has 4 virtual methods (*ToString(), Equals(), GetHashCode() and Finalize()*), which all classes will have, respectively.
### Goto Practice;
Practive:
It's time to start a small demonstration. I suggest such small blank (very similar to the blank from the previous article).
```
[StructLayout(LayoutKind.Explicit)]
public class CustomStructWithLayout
{
[FieldOffset(0)]
public Test1 Test1;
[FieldOffset(0)]
public Test2 Test2;
}
public class Test1
{
public virtual int Useless(int param)
{
Console.WriteLine(param);
return param;
}
}
public class Test2
{
public virtual int Useless()
{
return 888;
}
}
public class Stub
{
public void Foo(int stub) { }
}
```
And let's use that stuff in such way:
```
class Program
{
static void Main(string[] args)
{
Test2 fake = new CustomStructWithLayout
{
Test2 = new Test2(),
Test1 = new Test1()
}.Test2;
Stub bar = new Stub();
int param = 55555;
bar.Foo(param);
fake.Useless();
Console.Read();
}
}
```
As you might guess, from the experience of the previous article, the *Useless(int j)* method of type **Test1** will be called.
But what will be displayed? The attentive reader, I believe, has already answered this question. «55555» is displayed on the console.
But let's still look at the generated code fragments.
```
mov ecx, [ebp-0x20]
mov edx, [ebp-0x10]
cmp [ecx], ecx
call Stub.Foo(Int32)
mov ecx, [ebp-0x1c]
mov eax, [ecx]
mov eax, [eax+0x28]
call dword [eax+0x10]
```
I think you recognize the virtual method call pattern, it starts after *Stub.Foo(Int32) call*. As we can see, as expected ecx is filled with the address of the instance on which the method is called. But since the compiler think that we call a method of type Test2, which has no parameters, nothing is written to edx. However, we have another method call before. And there we have used edx to pass parameter. And of course we don't have instructions, that clear edx. So, as you can see in console output, previous edx value was used.
There is another interesting nuance. I specifically used the meaningful type. I suggest trying to replace the parameter type of the Foo method of the Stub type with any reference type, for example, a string. But the parameter type of the method *Useless()* does not change. Below you can see the result on my machine with some clarifying information: WinDBG and Calculator :)
[](https://habrastorage.org/webt/lj/pt/5i/ljpt5isxjzejz0_kxhu0yyovyhw.jpeg)
*Clickable image*
The output window displays the address of the reference type in decimal notation.
### Total
We refreshed the knowledge of calling methods using the fastcall convention and immediately used the wonderful edx register to pass a parameter in 2 methods at a time. We also spat on all types and with the knowledge that everything is only bytes easily obtained the address of the object without using pointers and unsafe code. Further I plan to use the received address for even more inapplicable purposes!
Thanks for attention!
P.S. C# code can be found [here](https://gist.github.com/ZloyChert/c1b013b35cc3c76c45f2b8b6f39f9196) | https://habr.com/ru/post/447254/ | null | null | 1,051 | 62.68 |
[.
Did you...
Right click that py file in your plug-ins folder and under Properties - Permissions, check the box: "allow executing file as a program"?
What version of Gimp are you
What version of Gimp are you using? Do other Python plugins work?
In Gimp 2.7 on Linux/Ubuntu it is difficult to get python to work, it seems (I can't get it done either).
BTW: a hacked version of gimpfu??
Version 2.6 on Windows XP,
Version 2.6 on Windows XP, Python 2.6
All python plugins I have tried are working fine.
At first I had a hard time making python work in GIMP, but then found some step-by-step guide to how to install all needed components, and it worked.
By 'hacked' i mean modified. See, I needed certain function changed in gimpfu, but if I import from it:
from gimpfu import *
it didn't work, so I actually have a copy of gimpfu pasted in, that allowed me to make necessary changes.
Linux ubuntu ?
That works great under windows! Good job! BUT could somebody help making it working under LINUX UBUNTU 10.10
Das wäre gelacht,wenn jemand dabei helfen könnte, das plugin unter LINUX UBUNTU 10.10 zu benutzen!
Many thanks for help!
Linux
In theory should work also in linux ,since apparently the script doesn't use anything that is Windows only
What problem you had in linux ?
the most commune problem may be with paths, the formatting of paths is different in the 2 OS
PS please don't reply in German or i will never understand your reply
The most common problem with
The most common problem with python scripts in Linux is that the user forgets to make them executable (chmod +x foobar.py).
I am sorry, I don't know
I am sorry, I don't know nothing about UBUNTU or LINUX in general except for Apache, I have been on windows all my life (shame, I guess...).
Maybe some other developers out here can help you.
Thanks for the positive feedback on the plugin though!
Cheers.
Pages | http://registry.gimp.org/comment/10540 | CC-MAIN-2014-10 | refinedweb | 352 | 72.97 |
SQL Server 2005 Reporting Services White Paper
Microsoft Corporation
July 2006
Applies to:
Microsoft SQL Server 2005 Reporting Services
Summary: This document assists Crystal Report designers with migrating to Microsoft SQL Server 2005 Reporting Services using a step-by-step migration strategy. (40 printed pages)
Click here to download the Word document version of this article.
Introduction
Comparing Business Objects Crystal Reports 8.5+ to SQL Server 2005 Reporting Services
Preparing to Convert to SQL Server 2005 Reporting Services
Migrating Crystal Report Sections to SQL Server 2005 Reporting Services
Migrating Additional Crystal Report Features to SQL Server 2005 Reporting Services
Using Alternative Migration Techniques
Conclusion
Useful Links with other applications, including Microsoft Visual Studio. While Crystal Reports has worked well for many companies, with the recent release of SQL Server Reporting Services, companies are reevaluating their purchasing decisions, and looking for a more unified and cost-effective reporting solution.
Microsoft SQL Server 2005 Reporting Services (SSRS) is the emerging solution of choice for businesses requiring enterprise reporting capabilities, and it competes directly with top-tier reporting solutions such as Crystal Reports. Because SSRS ships with SQL Server 2005, companies can fully leverage their investment in SQL Server and benefit from the deep integration with the other areas of the product. Some of the latest enhancements to Reporting Services—including an ad hoc report designer called Report Builder—bring Microsoft to the forefront of the reporting solutions market.
Because there are so many companies using Crystal Reports today that also own SQL Server and want to begin using SSRS as a lower-cost alternative, there is a need to guide Crystal Reports designers with the migration of their current Crystal Reports solution to SSRS. This document will focus on the manual migration effort for Crystal Reports 8.5 and later, and it includes a section-by-section comparison of report information from Crystal Reports to that of SSRS. This approach will also introduce Crystal Reports users to SSRS and demonstrate the similarities of the two systems.
By studying actual migration efforts, we have observed that a large number of migrated reports are tabular and use features such as formulas, groupings, and parameters. While much of the functionality in Crystal Reports is available in SSRS, the scope of this paper is limited to the migration of the specific sections detailed in Table 1.
Table 1. Crystal Report sections scoped for this paper, and comparable SSRS report sections
Please note that the semantic layers (Universe and Business View) in more recent versions of Crystal Reports are not considered in this document, although SSRS does include similar functionality that insulates the business users from the complexities of relational and online analytical processing (OLAP) data sources. Through the Report Builder of SSRS, end users can create ad hoc reports using predefined report models to act directly against relational data sources. Additionally, SQL Server 2005 introduces a new concept, the Unified Dimensional Model, which, like the Business Objects Universe view, is a metadata layer that sits on top of the physical database. Some of the key benefits of the UDM over the Business Objects Universe view include:
To learn more about the SSRS Report Builder capabilities and the SQL Server 2005 UDM, visit the following Books Online topics:
Finally, some basic knowledge of SSRS is required when migrating Crystal Reports to SSRS. To further assist in your reading, throughout this document there are links to SSRS Books Online that provide additional coverage on specific SSRS topics.
Making the decision to migrate your existing Crystal Reports to SSRS requires a thorough comparison of the two products, in order to determine which is best for your business. In addition to just looking at features, some key strategic questions to ask during this evaluation are:
With the release of SQL Server 2005, Microsoft has taken extraordinary steps to bring to market a complete enterprise Business Intelligence platform that integrates all aspects of Business Intelligence into one easy-to-use architecture. Not only does SQL Server 2005 include a new performance-enhanced database engine, but it also includes Analysis Services for building OLAP cubes and data mining; powerful Integration Services for performing extract, transform, and load (ETL) tasks from various data sources; and Reporting Services for Operational Reporting.
Because the tools included in the SQL Server Business Intelligence Development Studio—for example, the Report Designer—leverage the Visual Studio framework, developers benefit from a consistent development methodology and easier learning process when developing applications that require both Visual Studio and Reporting Services. Additionally, unlike Reporting Services for SQL Server 2000, which required a Microsoft Visual Studio .NET 2003 license, SQL Server 2005 includes a set of design tools in the SQL Server Business Intelligence Development Studio for report design, development, and deployment. SSRS also adds additional controls, such as the ReportViewer control, to Visual Studio 2005 and Visual Web Developer Express, so that you can embed reports within your .NET applications or ASP.NET websites.
Finally, baseline Reporting Services functionality has even been added to SQL Server 2005 Express with Advanced Services, so you can benefit from basic local reporting, without accruing additional cost. So, if you currently have an instance of SQL Server 2005, or are thinking about implementing one, consider leveraging your investment by using SSRS for your reporting needs, instead of paying potentially hundreds of thousands of dollars for third-party reporting solution products.
SSRS has several other benefits to consider. One of the key concepts of the product is its use of XML to describe reports, data sources, report models, and even service configuration. The Microsoft Report Definition Language (RDL) is an XML schema that is used to describe reports built using Reporting Services Report Designer or Report Builder. RDL documents promote an extensible and open report document format that can be easily shared between applications. Another feature of SSRS is its extensibility. By extending SSRS, application developers can create new custom data sources, new delivery capabilities, new rendering options, or new security. Additionally, Web Services can be used as data sources, and custom report controls can be easily created and used in reports. Finally, SSRS introduces Report Builder, which allows users to build ad hoc reports from the Report Manager, and then save those reports for future reference. For additional information about new features and enhancements in SSRS, refer to the Microsoft SQL Server 2005 Reporting Services website.
Table 2 provides a brief comparison of the features of Business Objects Crystal Reports Server and Microsoft SQL Server 2005 Reporting Services.
Table 2. Comparison of Crystal Reports Server and SSRS product features
Once you have made the decision to migrate your existing Crystal Reports to SSRS, the first step will be to determine how your current reporting solution will be duplicated in a Reporting Services solution. To start, consider the users of your reporting solution. As shown in Figure 1, there are generally three types of users in an organization that interact with reporting: information designers, information analysts, and information workers.
Figure 1. Reporting user types (Click on the image for a larger picture)
Note Delivery channels such as Microsoft Office and e-mail are not listed above but are supported by both product sets.
After determining how the different user types will interact with SSRS, you next need to study the reports in the current Crystal Reports solution. Develop a list of all reports, and capture important information relevant to each report—for example:
By organizing and capturing important information about your report consumers, you will better understand their common characteristics. With this list prepared, you can begin defining your SSRS solution.
More often than not, the implementation of a new reporting solution provides an opportunity to consolidate many reports that have been created over the years. By significantly reducing the number of reports, support for these reports is simplified, while data visibility and organization are improved. For example, you can consolidate reports that duplicate information or that no longer serve a purpose. Your analysis of your current reporting solution should help you discover consolidation opportunities.
Additionally, you should use this time to consider ways to better standardize reports. To start, consider implementing stored procedures to replace SQL statements in your reports. By using stored procedures, you can protect your reports from malicious attacks—for example SQL Injection—and potentially improve the performance of your queries.
When you have completed analyzing your current Crystal Reports reporting solution and identified any consolidation and standardizing opportunities, the next step is to plan the migration details of Crystal Reports to SSRS. This planning will use your analysis results to identify which report types and users to migrate to SSRS first. Generally, a phased migration is the best approach for the end users as well as the design team. Each phase should have a formal communication process that is shared with all end users. At a minimum, communicate the date of the migration, any possible downtime to the users, and a support contact for any issues the users may encounter after the migration. Once all phases have been defined, a target date can be set for the retirement of the Crystal Reports Servers.
Additionally, you may want to budget some time for training your end users on the Report Manager and Report Builder. During this training, you can solicit user feedback on the new system, as well as define new report models for the Report Builder ad hoc queries.
Now that you have completed analysis of your reporting solution and have a list of reports to convert, you're ready to perform a section-by-section migration process for each report. To begin, let's take a look at a typical Crystal Report (Figures 2 and 3). In this report, sales data is reported for each territory. Grouping is performed first by territory, and then by salesperson.
Figure 2. Sample Crystal report design interface (Click on the image for a larger picture)
Figure 3. Crystal report sample preview (Click on the image for a larger picture)
This Crystal Report connects to the AdventureWorks database and reports on Territory Sales. Two commands are used to return data for the report, Command and Command_1. Command returns the sales data for each employee in each region. Command_1 returns a distinct list of all territories. There is also one parameter defined, Terr, that represents the different territories available for selection when viewing the report. Finally, formulas are used to toggle visibility of the Page Header textbox for the text "Territory Sales Cont'd." If the page number is 1, the textbox is suppressed; otherwise, the textbox is displayed.
Next, let's review the steps required to migrate the report in Figures 2 and 3 to SSRS:
To get started, open SQL Server Business Intelligence Development Studio and create a new Report Server Project. When the project is created, you will see a standard report template similar to Figure 4. A report template includes three tabs: Data, Layout, and Preview:
Figure 4. Visual Studio .NET 2005 standard report template (Click on the image for a larger picture)
The first task required to migrate a report is to set up the connection information to the data source. From the Crystal Report migration sample in Figure 5a, the data source will be SQL Server. In SSRS, this connection information is called a data source. A dataset contains a reference to a data source, as well as query information. You can add a data source as a separate step, or as part of adding a new dataset. To set up a new dataset for your report, on the Data tab of the report, click the DataSet drop-down list, and then click New DataSet.
Figure 5a. OLE DB connection to the SQL Server AdventureWorks database
The Data Source dialog box appears (Figure 5b). Type a name for your data source, and then select the type.
Figure 5b. Data Source dialog box for a dataSet
Next, click Edit to define the connection properties for the data source (Figure 6).
Figure 6. Connection Properties dialog box for a data source
After specifying the connection properties and testing the connection, click OK to return to the Data Source dialog box. Click OK again to save the data source information and return to the Data tab of the report. You should notice the TerritorySales dataset now available in the Datasets window. So what just occurred? Essentially, we've just created a container for the results of our query to be stored once a report is run. The dataset acts as an in-memory representation for the results of the query. To learn more about datasets and data sources in SSRS, visit the Working with Data in Reporting Services topic in Books Online.
The next step is to generate a query to return a list of fields from this data source, to populate the dataset created for use in the report. Since the data source for the sample Crystal Report is the AdventureWorks database on a SQL Server, we can paste the SQL query from the sample Crystal Report directly into the query pane of the Data tab (Figures 7a and 7b).
Figure 7a. Command query from the sample Crystal Report
Figure 7b. Command query from the sample Crystal Report pasted into the data query for the SSRS report
You could alternatively call a stored procedure here as well, by changing the value in the Command Type drop-down list. For more information, visit the Defining Datasets for a SQL Server Relational Database topic in Books Online.
You also need to create one more dataset that lists all the available territories in the AdventureWorks database. This dataset will be used as a parameter source in the next section. Repeat the previous steps to create another dataset using the AdventureWorks data source, and name the dataset Territories. Use the same query from Command_1 in the Crystal Report sample.
Select distinct(Name) from Sales.SalesTerritory
Finally, the sample Crystal Report includes one parameter, terr, to allow users to select the territories to view when the report is run (Figure 8a).
Figure 8a. Sample Crystal Report parameter and parameter defaults from Command_1
In SSRS, the data query can be easily updated to include a where clause to automatically configure the report to display optional parameters. In Figure 8b, the data query has been updated to include the following where clause.
where st.name IN (@terr)
This statement will return all the territories from the data source whose name is in a territory list submitted by the user.
Figure 8b. Dataset query updated to use a parameter
An SSRS report also contains a Report Parameters properties page where the designer can view all the parameters of the data query in one place. To access the Report Parameters page, click the Report menu, and then click Report Parameters.
Upon opening the Report Parameters page, the terr parameter is automatically detected by SSRS and added to the parameters list. The basic properties of a parameter include its name, data type, and prompt. You can additionally select the value modes (allow nulls, multi-valued, and so on), available values to display for the parameter, as well as a default value(s) to use when the report first executes.
To configure the additional parameter information from the query in Figure 8b, configure the prompt for the terr parameter to Territories. Next, set the value mode to Multi-value and Allow blank value. When setting the available values, designers can input static non-queried values or use a dataset. For this sample report migration, use the Territories dataset to populate the parameter list. Use the Territories Name field as both the Value and Label fields. Because the parameter is a multi-value parameter, users will be able to select one, two, or all territories to view at once. Finally, the Default values section also allows for static, queried, or null values to be defined. Select the From Query option, and once again use the Territories dataset, with the Name field of the dataset as the Value field. Once complete, the terr parameter should look something like Figure 9.
Figure 9. Report Parameters properties page
Once all parameters have been entered for the report, click OK to return to the Data tab. Now that you have a report parameter, you can update the query to use it. When adding a parameter to a query or stored procedure, you precede the parameter name with the @ symbol, just like any other SQL variable. This query parameter serves as a placeholder, to be replaced at execution time with the parameter value selected in the report.
For more information about report parameters, visit the Using Parameters in a Report topic in Books Online for SSRS.
Finally, to test the dataset, you can run the query and view the result set by clicking the red exclamation mark above the query pane. The results will be displayed below the query pane.
The report header and report footer are generally sections that are displayed on the first page and last page, respectively, of the report. However, unlike Crystal Reports, SSRS does not have explicit Report Header and Report Footer sections. Instead, you can use the Page Header and Page Footer sections.
Let's examine the Report Header and Report Footer sections from the sample Crystal Report in Figure 3 (Figure 10a).
Figure 10a. Report Header and Report Footer sections from the sample Crystal Report (Click on the image for a larger picture)
In Figure 10a, the report header of the sample Crystal Report contains an image, a textbox object with the report title, and a date stamp to show when the report was created. The report footer contains a simple textbox object indicating the end of the report.
To migrate these sections to SSRS, click the Layout tab of the report template to view the report layout. To add a page header to the report, click the Report menu, and then click Page Header. This section is now available for use in the report layout form. Next, you'll use a rectangle as a container for an image and a textbox that comprise the report header. Drag a Rectangle control from the Toolbox window, and drop it in the page header. At this point you should notice the similarities between SSRS and Crystal Report's WYSIWYG report design as well as pixel perfect report creation (that is, controls can be easily dragged and dropped onto the design surface and positioned to the pixel location of choice with great flexibility).
Figure 10b. Typical report design with Page Header and Page Footer sections added (Click on the image for a larger picture)
Next, add Image and Textbox controls to the rectangle, and adjust the size of the rectangle as needed (Figure 11).
Figure 11. Page Header Rectangle control updated with Image and Textbox controls (Click on the image for a larger picture)
Because these controls should be displayed only on the first page of the report, you need to change the Visibility property of the Rectangle control. Right-click the Rectangle control, and then click Properties. In the Properties window, locate and expand Visibility. Click the list box for the Hidden property to select Expression. An expression is very similar to a formula in Crystal Reports, but it uses Visual Basic .NET syntax. By using an expression, a designer can programmatically define a value for a property. To toggle the visibility of the Rectangle control, you can create an expression using a global variable—PageNumber (Figure 12). For more information about expressions, see Working with Expressions in Reporting Services.
Figure 12. Using the Expression Editor to show\hide the Rectangle control based on page number (Click on the image for a larger picture)
Click OK to close the Edit Expression dialog box. You have now completed your report header. By grouping information in a rectangle, you are able to show or hide the rectangle contents based on the current report page. You can use this same method for the report footer as well. Follow the same steps that you just completed, but place the controls in the page footer. Change the expression for the page footer's rectangle to the following.
=IIF(Globals!PageNumber = Globals!TotalPages,False, True)
The page header and page footer are generally sections that are displayed near the top and bottom, respectively, of every page in a report. As you learned in the previous section, to include page headers or page footers in a report, click the Report menu, and then click Page Header or Page Footer.
Let's examine the page header and page footer from the sample Crystal Report (Figure 13).
Figure 13. Page Header and Page Footer sections from the sample Crystal Report (Click on the image for a larger picture)
Here, the page header displays the column or field headings of the report, as well as a textbox that is conditionally suppressed. When the current page is Page 1, the textbox is suppressed, but when the current page is not Page 1, the textbox is not suppressed. SSRS includes the column headings in the table control, as explained in the next section. For now, you can migrate the date stamp, and the textbox that contains the "Territory Sales Cont'd" text, to the page header in SSRS, since these controls are static text. Since the date stamp is displayed in the top-right corner of every page, you can use the page header to display this information. Drag a textbox onto the page header, and position it in the top-right corner. With the textbox selected, find the Value property in the Properties window, and then select the Expression option in the drop-down list to build the following expression.
=Replace(DateString(),"-","/")
This expression simply reformats the date string to look like the Crystal Reports date string. Rather than type a function, you can select any function from a list in the Expression Editor. Here, functions are organized by type in the Custom Functions list. The Replace function is in the Text group whereas the DateString function is located in the Date & Time group. Alternatively, you can use the format property of the textbox to set the date format (dd/MM/yyyy) and set the value for the textbox to =Now for this particular example.
Next, drag and drop another textbox into the page header, and type Territory Sales Cont'd in the textbox. Since this title should be displayed on all pages except the first page, use the Visibility property of the textbox to build an expression that conditionally shows or hides this control.
To migrate the page footer, drag and drop a textbox control to the Page Footer section. Then, set the Visibility expression to display the page footer information on all pages except the first page (Figure 14).
Figure 14. Updated page header and page footer information in SSRS (Click on the image for a larger picture)
To learn more about report layout in SSRS, visit the Understanding Report Layout and Rendering topic in Books Online for SSRS.
At the heart of most reports is the row-level data returned from the data source. Row-level data is often grouped by common fields. A report may also include subtotals for each group. Let's examine the available row-level data, groupings, and subtotals from the sample report that we are migrating (Figure 15).
Figure 15. Report details, groupings, and subtotals from the sample Crystal Report (Click on the image for a larger picture)
In Figure 15, there are two groups for the row level: Territory and Last Name. In this example, the data is also displayed in a tabular format for easy drilldown into each group. Finally, the report shows summary data (subtotals) of the total sales by territory and by salesperson.
As mentioned in the previous section, SSRS provides a table control to display the column headings in a tabular report.
Table 3 lists the controls—known as data regions in SSRS—that you can use in a report, and the corresponding Crystal Reports controls (if available).
Table 3. Comparing Crystal Reports and SSRS controls
To reproduce the details, groupings, and subtotals of the sample Crystal Report in Figure 15, drag and drop the table control from the Toolbox into the body of the report. By default, a new table contains header, detail, and footer information. Additional information about the table control is shown in Figure 16. In particular, notice that the table header in the table control displays column headings, unlike Crystal Reports, which use the page header.
Figure 16. SSRS table control overview
First, assign a dataset to the table control. Click the table, and then click the corner handle to display the properties of the table in the Properties window. Locate the DataSetName property, and assign the applicable dataset.
Next, configure groupings for the table. Click the table to display the row and column handles. Right-click one of the row handles, and then click Insert Group to display the Grouping and Sorting Options dialog box. The General tab in this dialog box allows you to specify the fields used to group the dataset. First, give the grouping a name. Next, select an expression for Group On. Since the first grouping is based on the territory name, select the Name field from the dataset. Keep the default values for everything else, and then click OK to return to the table. Your table now includes a new grouping, as shown in Figure 17.
Figure 17. Adding a grouping to a table control (Click on the image for a larger picture)
Next, add a second grouping for salesperson. Repeat the previous steps to add a second group to the table, based on SalesPersonID. Your table should now look similar to the one shown in Figure 18.
Figure 18. Adding a second grouping to a table control (Click on the image for a larger picture)
Now that your table includes groupings, you can start placing data into the table. Just drag and drop fields from the Datasets window onto the table. To continue with the sample Crystal Report, drag and drop the Name field into the first cell of the grouping header. Once the field is added to the grouping header, the table header is also updated with the field title. Alternatively, you can manually edit table headers, just as you can in Crystal Reports. Also, notice the expression used in the first grouping header to refer to the value of the dataset field in Figure 19.
Figure 19. Inserting dataset fields on a table (Click on the image for a larger picture)
Now you're ready to add SalesPersonID to the second cell of the second grouping row, which will stagger the display of data. Because the second grouping should display the salesperson's first and last names, you need to create an expression to concatenate fields in the dataset. Select the textbox, and then find the Value property in the Properties window. Select <Expression> in the property's drop-down list (or right-click the textbox, and then click Expression), and then build an expression like the following (Figure 20).
=Fields!FirstName.Value + " " + Fields!LastName.Value
Figure 20. Textbox value created using an expression (Click on the image for a larger picture)
The table in SSRS now contains all grouping information. The next level of detail in the sample Crystal Report displays the Sales Order number and the total due for the order. Before adding more fields to the table, add another column. Right-click the last column in the table, and then click Insert Column to the Right. Adjust the column widths to make sure that the table fits on the page. Then, drag and drop the SalesOrderNumber and TotalDue fields to the third and fourth columns, respectively, of the detail row. The table should now look similar to Figure 21.
Figure 21. Inserting fields in the table detail row (Click on the image for a larger picture)
Again, notice that the table header automatically includes the field name. Be sure to change the column headings to match the headings in the Crystal Report. You can apply formatting by using the Report Formatting toolbar, or by changing properties in the Properties window.
Now you're ready to add subtotals by salesperson and by territory. The first grouping header for total sales will display the subtotal for each territory. To calculate this subtotal, drag TotalDue into the fourth column of the first grouping header. SSRS automatically adds the Sum aggregate function to fields with a numeric data type. Repeat this step to add a subtotal by salesperson to the second grouping header under the Total Sales column. At this point, your table should look similar to Figure 22.
Figure 22. Calculating group subtotals (Click on the image for a larger picture)
The final step in this section is to enhance the table by removing unused rows and applying formatting. When you added groups to the table, group footer rows were automatically created. Since these rows aren't used in this example, you can click the table, right-click the row handle of the row to delete, and then click Delete Rows. Repeat this procedure to delete the remaining group footer row, as well as the table footer row. Figure 23 shows what the table control from Figure 22 looks like when formatted.
Figure 23. Formatting the report (Click on the image for a larger picture)
In the sample Crystal Report preview shown in Figure 3, the report hides the secondary grouping and the details of the report until a user clicks a territory or salesperson. To migrate this interactivity, you can add an interactive feature, such as Hiding Report Items, to rows of a table control. Using the Visibility property for the table detail row and the second grouping row, you can show or hide these rows when you click a textbox in another row. To select the entire second grouping row, click the table, and then click the corresponding row handle. The second grouping row is now highlighted, and properties for the row are accessible in the Properties window. Locate the Visibility property and change the Hidden property to True. Next, change the ToggleItem property to the name of the textbox that contains the grouping field for Territory. The ToggleItem property changes the value of the Hidden property from True to False when you click the specified textbox. Figure 24 shows the second grouping row selected and the ToggleItem property being set to txbTerritoryName, which is the name\ID of the textbox in the first grouping row.
Figure 24. Use the ToggleItem property to add report drilldown capabilities (Click on the image for a larger picture)
Repeat the previous steps to set the ToggleItem property for the table detail row. In this case, the ToggleItem property value is the textbox containing the second grouping for salesperson.
Finally, set the format of the Sales Total column to Currency. To do this, select the Sales Total column handle to highlight the entire column, and then set the Format property for the column to C. Click the Preview tab to see how the report looks now (Figure 25).
Figure 25. Migration report preview (Click on the image for a larger picture)
In reporting, more often than not, the database fields do not always provide the data required for particular parts of a report, and reporting solutions need alternative ways to generate data. Crystal Reports uses formulas and custom functions to do such data generation. A formula on a report uses expressions (Formula Workshop) to populate report items like textbox objects. A few examples of formulas include creating calculated fields to add to a report, formatting text on a report, and using a custom function. Custom functions are more complex procedures that you create in Crystal Reports to evaluate, make calculations on, or transform data in a report. Unlike formulas, where the scope of the formula is local to the report, custom functions can be saved, in order to be used across multiple reports.
In SSRS, we've been introduced to the Expression Editor to perform calculations or to manipulate strings of an SSRS control. This feature is very comparable to the Formula Workshop in Crystal Reports, but its scope is only to the control where the expression is defined. To create a more global report expression, SSRS allows designers to write custom Visual Basic .NET functions that are accessible by the Expression Editor of the report. Custom functions are added through the Report Properties, which you access by selecting Report Properties from the Reports menu. Here, you can set various properties for the entire report. In this section, we'll focus on the Code and References tabs of the Report Properties dialog box.
To create functions that are easily referenced within the current report, you can use the Code tab to create Visual Basic .NET functions. You can add multiple functions here. Currently, Visual Basic .NET is the only language supported. For demonstration purposes, add a simple Visual Basic .NET function to the code that sets the foreground color of the Territory Total Sales to red if the amount is greater than $10 million, as shown in Figure 26.
Figure 26. Visual Basic .NET code to set the foreground color based on total sales
To use this new function, select the textbox containing the Total Sales for the Territory (the first grouping), and then add the following expression to the Color property:
=Code.setColor(Sum(Fields!TotalDue.Value))
Notice the Code keyword in the expression. This works like a namespace in SSRS, to tell the Expression Editor where the function is located. Preview the report to confirm that territories having total sales greater than $10 million are displayed in a red font (Figure 27). This report design technique can focus attention on certain results in a report. Using the Code tab of the Report Properties dialog box and the expression builder, designers can quickly and easily add more functionality to reports.
Figure 27. Preview Visual Basic .NET code changing the foreground color of the Territory Sales subtotal (Click on the image for a larger picture)
It is important to reiterate that when migrating formulas or custom code from a Crystal Report into the Code tab of the Report Properties dialog box, the formulas and custom code must be converted to a Visual Basic .NET function.
In SSRS, to create custom reusable code like custom functions in Crystal Reports, the Reference tab of the Report Properties dialog box is used. The Reference tab allows designers to reference an assembly for the report. An assembly is precompiled code that can be shared among applications. Assemblies are a great way to keep a library of common methods together in one place. For instance, the sample report displays territory sales for the AdventureWorks company. If a project requires multiple reports related to sales and financial information, you could easily write an assembly to define commonly used functions. You could then reference this assembly in all reports in your project. Additionally, if any changes are required, all changes made to the assembly propagate to all reports. Furthermore, because it is a .NET assembly, you can use the assembly in any .NET application. Finally, you can circumvent the limitation that report code must be written in Visual Basic .NET by using an assembly, which can be written in any .NET language that you prefer (however, you must have a Visual Studio license to build custom .NET assemblies).
To demonstrate how to use a custom assembly in a report, you can recreate the embedded code example used in Figure 26. Using Visual Studio .NET, construct a class library file using C# .NET rather than Visual Basic .NET (Figure 28).
Figure 28. Custom assembly to return a color string based on the input value (Click on the image for a larger picture)
Once you compile the class library file as an assembly, copy the assembly to the application folders for Report Server and Report Designer. The default location of the bin folder for the report server is C:\Program Files\Microsoft SQL Server\MSSQL.3\Reporting Services\ReportServer\bin. The default location of the Report Designer is C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblies. For more information about deploying a custom assembly to a report, see Reporting Services Online Help.
Next, you reference this assembly by using the Reference tab in the Report Properties dialog box. In the Reference section, click the ... (ellipsis) button, and browse to the assembly in the Report Designer application folder. Select the assembly and click Add. Finally, click OK to return to the Report Properties dialog box (Figure 29). Because the setColor function in the assembly is a static method, you don't need to populate the class information for the assembly.
Figure 29. Referencing the custom assembly in the Report Properties dialog box
Click OK to close the Report Properties dialog box. Now, you can update the expression for the Total Sales by Territory textbox color to use this custom assembly. To do so, modify the expression to call the static method in the assembly, as follows.
=RSLibrary.MyReportFunctions.setColor(Sum(Fields!TotalDue.Value))
Preview the report to see that territories with total sales greater than $10 million are once again displayed in a red font.
In a matrix report, you arrange data into columns and rows, much like a crosstab or pivot table. By contrast to a table, which has a static set of columns, the number of matrix columns can be dynamic. Like Crystal Reports, SSRS includes a matrix control (or crosstab control) to generate this type of report. However, unlike the Crystal Reports matrix control, SSRS allows for fold/unfold or toggle behavior in its matrix control. In addition, an SSRS report can also include a mixture of matrices and other data regions, such as tables and charts, on a single report. This gives designers much more flexibility in design. Additional information about the SSRS matrix control is shown in Figure 30.
Figure 30. Matrix control overview
To create a matrix report, create a new report in SQL Server Business Intelligence Studio, create a dataset for the report, and then drag and drop a Matrix control onto the Report Layout (Figure 31).
Figure 31. Empty matrix view (Click on the image for a larger picture)
In Figure 31, notice that the control has labels for the Rows, Columns, and Data regions. The first task of migrating a Crystal Reports matrix report is to create a new dataset in the SSRS report, using the data source and query information from the Crystal Report. Using the new dataset, you can drag and drop fields onto the SSRS matrix. The dataset for this sample matrix report, shown in Figure 32, connects to the AdventureWorks data source, and returns company sales information for each department during the years 2002 and 2003.
Figure 32. Matrix with grouped dataset fields (Click on the image for a larger picture)
After placing fields from the dataset onto the matrix, the matrix can now be formatted. Like the table control in SSRS, the columns and rows of a matrix can be hidden or displayed based on user interaction with the report, but the process to add this functionality is slightly different. In the following example, you'll toggle the visibility of the subcategory and the order quarter information when the user clicks the Category and Order Yearly textboxes, respectively. To do this, click the matrix, right-click the corner handle, and then click Properties. Next, click the Groups tab to see the grouping defined for the matrix (Figure 33).
Figure 33. Editing the matrix groups
Click the <matrix name>_SubCat group, and then click Edit to view the Grouping and Sorting dialog box for this group. Click the Visibility tab to set the initial visibility of the group, as well as to specify the report item that toggles the visibility (Figure 34).
Figure 34. Editing the visibility of the Matrix1_SubCat group
Before you click OK to save the changes, click the Sorting tab. Here, you can add sorting to the group, based on any fields in the dataset. After defining the sort order, click OK to return to the Matrix Properties dialog box. Repeat these steps to set the visibility and the sorting for Order Quarterly group. Finally, set the sorting for the remaining groups in the matrix: Product Category and Order Year. Click OK when finished.
Finally, add any desired formatting to the matrix in order to enhance its appearance (Figure 35).
Figure 35. Preview of the matrix report with visibility, sorting, and formatting updates
For more information about the Matrix Data Region in SSRS, please visit the Working with Matrix Data Region topic in Books Online.
A chart is a great way to visually display data in a way that captures immediate attention. When migrating charts from Crystal Reports, use the existing data source, query, and parameters from the Crystal Reports chart definition to create a new dataset in SSRS. Once the dataset is created, click the Layout tab, and drag and drop a chart control into the body of the report (Figure 36). To customize the chart, right-click the chart and click Properties. Using the Chart Properties dialog box, you can configure and customize every aspect of the chart. Whether you need to set the chart type and dataset name, configure values for the x and y axes, or add visual effects, the Chart Properties dialog box is a one-stop shop for setting up a chart.
Figure 36. Default line chart type in SSRS (Click on the image for a larger picture)
Another interesting point when migrating charts from a Crystal Report to SSRS is how SSRS handles the rendering of multiple charts and aggregate. In Crystal Reports, many report designers place charts and tables containing aggregate data in the report footer, because the report must read the detail data before it can report any aggregate data. This constraint is a product of the multipass calculation engine in Crystal Reports. SSRS, on the other hand, overcomes this constraint by providing designers a free-form surface on which they can lay out their reports any way that they want. This includes placing tables with aggregates and side-by-side charts anywhere on a report.
Finally, because SSRS is an extensible framework, you can purchase additional charts, gauges, and diagram types from third-party vendors. One vendor specializing in SSRS chart controls is Dundas. To learn more about charts, visit the Working with Chart Data Region topic in Books Online.
Crystal Reports and SSRS both have the ability to connect to a wide range of data sources; however, using multiple data sources on a single report in Crystal Reports has been known to cause performance issues. These performance issues are a direct result of executing the second/subsequent SQL queries for every row of data returned by the primary SQL query. This could result in the launching of hundreds of distinct queries. To work around this issue, Crystal Reports designers use multiple subreports on a single master report to display data from multiple data sources. SSRS, on the other hand, allows designers to create multiple data sources in a report that can be used in different data regions (controls), in a free form layout, to create the report that they want to create, without having to look for obscure workarounds or compromise the report's performance.
To demonstrate how to connect to multiple data sources in SSRS, open the tabular report created earlier to add a new dataset to the report. Using the Dataset dialog box, you can create a new data source to define a new connection. To follow this example, connect to Microsoft SQL 2005 Analysis Services. You should now have three datasets defined in the report. TerritorySales and Territory use the AdventureWorks database, whereas OLAPDataSource uses the AdventureWorks OLAP database (Figure 37).
Figure 37. Report sample with a heterogeneous data source in a single report (Click on the image for a larger picture)
In SSRS, a subreport is a report item that references another report on the report server. The referenced report can be a full report that can be viewed independently, or it can be a report created specifically for embedding in another report. When you define a subreport, you can also define parameters to filter data in it. To add a subreport to your report, use the Subreport control in the Toolbox. After placing the Subreport control on the report, right-click the control to access its properties. Here, you specify the referenced report and define the parameters required for the subreport.
You may want to consider using a data region instead of a subreport. Because the report server processes each instance of a subreport as a separate report, performance can be adversely impacted. Data regions provide much of the same functionality and flexibility as subreports, but with better performance.
When creating a link to another report in Crystal Reports, a designer must create an openDocument link on a particular field in a report in order to handle the report redirection. However, to use the openDocument function you must have Business Objects Enterprise installed, in order to get access to a report repository.
SSRS offers the ability to link and pass parameters to other reports quite easily, by setting the navigation property for a given object. You can even link to reports located on other report servers, by using the URL Access capabilities in SSRS, as explained later. To demonstrate the navigation property of a textbox, the following example uses the Sales Person column in the sample report to navigate to the Employee Sales Summary report (one of the samples included with SSRS). First, access the properties of the Sales Person textbox located in the second grouping of the table. Right-click this textbox, and then click Properties, as shown in Figure 38.
Figure 38. Accessing the properties of a textbox (Click on the image for a larger picture)
Click the Navigation tab of the Properties dialog box. In the Hyperlink section, select Jump To Report, and then select the target report in the drop-down list. To set the parameters to pass to the target report, click Parameters. SSRS creates a list of parameters from the target report. You can then associate static values or dataset values with selected parameters, as shown in Figure 39.
Figure 39. Editing the Jump to Report parameters using static values and dataset field values
Click OK until you return to the report designer. When you preview the report, expand the territory grouping (Figure 40), and then hover the cursor over the salesperson's name to see the pointer change to a hand.
Figure 40. Preview report-linking functionality (Click on the image for a larger picture)
Click a salesperson's name to navigate to the linked report using the parameters specified in the Jump To Report definition in the textbox properties (Figure 41).
Figure 41. Target Sales Person report from the Territory Sales report (Click on the image for a larger picture)
Use the navigation bar at the top of the report (Figure 42) to browse the current report, or to return to the parent report.
Figure 42. Linked report navigation bar (Click on the image for a larger picture)
You can also link reports in SSRS by using a report server URL. A URL request enables you to access reports, resources, and other items on a specific report server. Using URL access, you can also customize the report viewing and navigation experience for your users. The query string of the URL includes device information settings, as well as report parameter values and a specific rendering format (Figure 43). You can also use URL access to embed hyperlinks to reports and other report server items in any Windows or Web applications that you develop.
Figure 43. Available methods to communicate with a report server
For more information about linking reports in SSRS, visit the Adding Links to Reports topic in Books Online.
As with Reporting Services v1.0, SQL Server 2005 Reporting Services includes a Report Wizard to help start report development. The Report Wizard walks you through defining a data source, building a query, selecting a report type, grouping report data, and selecting a style for the report. To access the Report Wizard, right-click the Reports folder in the Solution Explorer of SQL Server Business Intelligence Development Studio, and then click Add New Report. For more information about the Report Wizard, visit the Creating a Report Using Report Wizard topic in Books Online.
When migration efforts involve hundreds or thousands of reports, you may want to consider automating as much of the migration process as possible. Third-party service providers have recognized the need for companies to accelerate the process of migrating to Reporting Services, and they have developed applications and methods within a consulting engagement that will allow companies to reach their goal faster. A short list of some third party solutions include
Table 4. Third-party migration solutions
For more information, visit the Reporting Services Partner page.
In this paper, we explained various aspects of migrating from Crystal Reports to SSRS. First, to help you decide whether to migrate, we provided a high-level comparison between Crystal Reports and SSRS features, along with an overview of some of the strategic benefits of migrating from Crystal Reports to SSRS. Next, to help you prepare for the migration, we described methods that you can use to analyze your current reporting solution, identify consolidation and standardization opportunities, and implement a phased migration. Next, to help you perform the actual migration, we demonstrated a step-by-step migration process that mapped each section of a sample Crystal Report with the analogous SSRS section. Then, to help you see the range of capabilities in SSRS, we discussed additional features such as matrices and charts. Finally, to help you decrease the time required to migrate, we explained how you can automate many of the steps of the migration. The information and techniques presented here will make your migration process easier and quicker.
For more information: | http://msdn.microsoft.com/en-us/library/aa964127(SQL.90).aspx | crawl-002 | refinedweb | 8,384 | 50.87 |
A Generalized Suffix Tree for any iterable, with Lowest Common Ancestor retrieval
Project description
A Generalized Suffix Tree for any Python iterable, with Lowest Common Ancestor retrieval.
pip install suffix-tree
from suffix_tree import Tree >>> tree = Tree ({ 'A' : 'xabxac' }) >>> tree.find ('abx') True >>> tree.find ('abc') False
This suffix tree:
- works with any Python iterable, not just strings, if the items are hashable,
- is a generalized suffix tree for sets of iterables,
- uses Ukkonen’s algorithm to build the tree in linear time,
- does constant-time Lowest Common Ancestor retrieval,
- outputs the tree as GraphViz .dot file.
Three different builders have been implemented:
- one that follows Ukkonen’s original paper ([Ukkonen1995]),
- one that follows Gusfield’s variant ([Gusfield1997]),
- and one simple naive algorithm.
PyPi:
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
suffix-tree-0.0.7.tar.gz (20.0 kB view hashes) | https://pypi.org/project/suffix-tree/ | CC-MAIN-2022-27 | refinedweb | 161 | 55.03 |
C9 Lectures: Stephan T. Lavavej - Standard Template Library (STL), 4 of n
- Posted: Sep 07, 2010 at 1:16 PM
- 72,779 Views
- 33 4, Stephan explains his solution to writing a solver for the Nurikabe puzzle using the STL (of course...). You will be introduced to some new concepts as well as use some of the things you have already learned.
Get the output and source code (v1) for Stephan's Nurikabe solver.
Get the optimized output and source code(v1.2) for Stephan's Nurikabe solver. 1.2 adds new test cases, improves the output, and significantly speeds up certain test cases. 1.2 is a better foundation for the performance exploration that Stephan suggested for the homework assignment. You're doing your homework, awesome video from Stephen
I'm still quite new to the STL, though I do like C++.
I was wondering if theres a C++ class that handles HTTPRequest without using .NET.
I was thinking about a writing a RSS Reader that checks a RSS feed every few hours/days/minutes whatever,
and if it finds what I'm looking for, it notifies me using a notifer icon.
So, I opened the source file, saw a nearly 400 line solve function with minimal "island" comments and pretty much lost all interest in what the program does. Just my two cents worth... Does it really have to be this unstructured to perform? Can it be any less structured and still be instructive (/sarcasm)? Was it necessary to cram it all into one .cpp file, given that it was part of a zip archive?
Just my 2 cents...
The commentary is in the video. Play the video, listen, watch, open the sources (v1) and follow along
Yes, the time algorithm isn't as efficient as you'd like, but knowledge requires real time. There is no getting around it. Well, there's virtual time,
but what's the delivery vehicle, exactly? Better would be synching viewers' VS editors with Stephan's presentation.
Hmm.
C
Well, he does state that the solve function, the meat of this application, will be covered in the next video, so I suppose we can take a wait and see approach. However, basic OO/structured programming tenets do not condone the use of 400 line "super-do-everything" functions, of which solve() is one. Bottom line is that we'll have to give Stephan the benefit of the doubt and let him elaborate in the next episode...
.
[Corrector2]
> So, I opened the source file, saw a nearly 400 line solve function with
> minimal "island" comments and pretty much lost all interest in what the program does.
My apologies. Please give it a second chance - it is not nearly as complicated as its length suggests.
I'm not sure what you mean by "island comments". I assume you're referring to big comment blocks. I carefully commented most of the file, especially the data structures, with short comments. As I mentioned in either Part 4 or 5, typically I let my code speak for itself, and I reserve comments for inherently complicated code (for example, I usually don't include comments like "Validate width and height." or "Parse the string."). In this case, though, I included almost as many comments as possible without overcommenting ("++i; // Increment i" being an obvious example of a comment that should not exist). The short comments do tend to thin out in the complicated functions like unreachable(), which assume an increasing level of familiarity with the STL, the problem domain, and the algorithm. However, I did include two gigantic comment blocks, for the complicated analysis steps. There's a big one explaining confinement that begins with "A region would be "confined" if it could not be completed.", with a diagram (!) for the most subtle part, and another big one explaining unreachability that begins with "The cell at (x_root, y_root) is unreachable if". Instead of explaining individual implementation steps, these big comment blocks explain concepts that are absolutely critical to understanding the following code.
Do you really want a big comment block for the step "Look for complete islands."? The single-line comment explains what's going on, and the code explains how it's finding complete islands (it looks for numbered regions with sizes equal to their numbers - and the "class Region" comments explain how that's tracked). This is a perfect example of code that should NOT have a gigantic comment.
I did consider breaking solve() up into smaller member functions, which I mentioned in either Part 4 or 5 (they were filmed back-to-back; I suspect it was Part 5). I decided against it, because solve() simply performs one step after another, and the steps are essentially independent. Introducing smaller member functions would have increased the total amount of code, and I didn't feel that it would improve clarity. Perhaps this judgment was incorrect.
> Does it really have to be this unstructured to perform?
No - solve()'s length is unrelated to its performance.
> Was it necessary to cram it all into one .cpp file, given that it was part of a zip archive?
It's a single class, with a small nested class, and a main() function. Unlike solve(), which I thought about breaking up, I felt no urge to break this up into multiple headers and source files. It's a large and realistic example, but not production code. If it were production code, Grid's class definition would certainly appear in a header, with member function implementations in source files, and it might even be pimpled to reduce compile-time dependencies (observe that its public interface is extremely small, while its private interface is large and refers to many things - in this case all of those things are from the Standard Library, but when they're from other code that's actively changing, that's a motivation to pimpl).
I'll see about breaking up solve() in version 1.3. Although I don't think it's the end of the world, your points are valid, and I'm probably desensitized to long functions.
> However, basic OO/structured programming tenets do not condone the
> use of 400 line "super-do-everything" functions, of which solve() is one.
The most important lessons from structured programming are that complex behavior should be encapsulated in simple functions, and that for/while loops are the antidote to poisonous gotos. solve() encapsulates very complex behavior - it performs a step of grid analysis - in a very simple interface. (It has to be told whether to be verbose and whether guessing is permitted - both of which have defaults - and it returns whether more analysis is required, or if not, why not.) As far as the outside world is concerned, solve() is perfectly structured. Internally, you may argue that solve() could be further structured, by independently encapsulating its steps of analysis. That is reasonable, although my first reaction was that it would simply move blocks of code around, not make those blocks easier to understand, or avoid duplication. (unreachable(), confined(), and other helpers are called more than once, which is why they're separate member functions.) Hopefully you can agree that my original point of view was at least somewhat reasonable.
As for object-oriented programming, its most important lesson is that state and behavior should be encapsulated in classes. Grid perfectly satisifes that and there are absolutely no problems there. Region is not especially encapsulated, but as I explained in either Part 4 or 5, that's because it's internal to Grid, and Grid is ultimately responsible for maintaining Region's invariants.
(Some people think that "object-oriented programming" means that everything should live in inheritance hierarchies. I disagree extremely strongly. Fortunately, that doesn't appear to be an issue here.)
Since most of the issues revolved around solve, let me be more clear in my argument:
- A complex function, even if it is mostly one containing linear flow can be broken down into several simple functions in order to become more hierarchical and less linear. Let me give a simple example to elucidate my point:
Instead of a long function such as:
void Car::Build()
{
// Build the frame
... build the frame code
// Add doors
... add doors code
// Insert engine
... insert engine code
// Insert transmission
... insert transmission code
// Insert upholstery
... insert upholstery code
// Paint the car
... paint the car code
// Whatever else needs to be done
... whatever else needs to be done
}
It is much easier to see (the comments are not part of the code, I am just adding them to show what the functions being called do for the purpose of explaining my point):
void Car::Build()
{
BuildFrame(...); // Calls AddDoors()
AddInternalParts(...); // Calls AddEngine(), AddTransmission(), AddUphostery()?, etc...
AddBodyParts(...); // Calls AddDoors()
Paint(...);
}
Now the Build function is easy to eye over and comprehend. If the programmer wishes to look into detail and see how each step is actually implemented, he can go into each of the functions being called and examine them (or look at call graphs, etc...).
By creating a deeper (rather than shallower) Build() function, it is much easier to comprehend in a top down (rather than bottom up) fashion. This is how most people solve and analyze problems - from an abstract problem statement to analyzing (i.e., "sweating") the details.
If you:
Then, it would be much easier to see what solve does as a whole and there would be no performance penalty in doing this, to boot, because these sub-tasks would probably still be gross tasks. If any of the sub-tasks are still complex, you can further decompose them into more sub-tasks.
A developer reading solve would drill down to the level of interest to him, while seeing the big picture all along the way. Compare this to having to gloss over 400 lines of code, even if only looking for comments, in order to try to figure out what solve does.
My two cents...
.
Thanks I'll take a look at that.
Charles,
Any idea when's the next video will be uploaded?
Yes. Next week.
C
One other niggle, Stephen.
When is it best to use helper methods?
I've heard a lot of people say they're bad.
Tom
// 1.3 (9/8/2010) - Reorganized Grid::solve() into smaller member functions.
Thank you, Corrector2, for helping me to improve my code.
[Tominator2005]
> When is it best to use helper methods?
> I've heard a lot of people say they're bad.
Nonsense. (I've never even heard that before.) Helper functions (both free and member) are wonderful. They are absolutely necessary when called more than once, and as Corrector2 patiently explained, they are useful even when called exactly once.
If you look at my Grid, its public member functions are supported by its private member functions. This is how basically every well-designed class works. Whether you refer to the private member functions as "helpers" doesn't change the fact that you need them.
When I wrote my solver, I planned from the beginning to have Regions, and I knew that I'd need add_region(), fuse_region(), and so forth. As I wrote more code, I noticed that I was repeatedly looking at a cell, figuring out which of its neighbors were within the bounds of the grid, and doing something for each neighbor. I lifted that out into for_valid_neighbors(), and as I noticed common operations, I created insert_valid_neighbors() and insert_valid_unknown_neighbors() to remove code duplication.
Looking much better in 1.3! I'd still do more refactoring on unreachable(), but it's a whole world better than before...
I noted in case of errors exceptions are thrown in your code (e.g. throw runtime_error, throw logic_error...) with a proper error message.
The error message is an English string stored in a char-based string. In case of production-quality code there would be a need to localize error messages. But std::exception class seems to support only char* strings. How could this localization problem be solved? Should a new class be derived from std::exception, adding Unicode string supports or some form of string table? Should every library define its own custom localizable std::exception class?
Thanks.
[C64]
> In case of production-quality code there would be a need to localize error messages.
Yep!
> But std::exception class seems to support only char* strings.
Correct. std::exception::what() is intended to be seen by developers and not by end users. You could put UTF-8 in there, but you only get one what().
> How could this localization problem be solved?
Derive from std::exception (at a minimum; deriving from the <stdexcept> classes would be better), and tag your exceptions with string resource identifiers. Then you can load the appropriate string at runtime based on the user's language.
Also, see Boost.Exception: The Standard Library's exceptions are just a starting point.
Thanks STL,
Ok, my bad. It wasn't helper functions but Helper Classes, as in classes with static functions,
it just came up on a Google Search for Helper functions, and I saw the word Helper and Evil,
and totally misread and misconceived that the idea of helper functions were evil.
Looking good btw. I might try Boost ASIO, but its not as simple as creating a instance
of HTTPRequest to get html from a web page or xml from a RSS feed.
I do enjoy watching these STL videos and request a lot more please
But why does it take so long to release them ?
Also i must ask: how blood hard is it to make videos without black stripes ?!
To me this is a very obvious sloppy mistake (there are other mistakes too but you get the point). The noob editing this video needs a go-back-to-school slap.
Seems to me that the stl videos get low priority, how come ? You (Charles) did say more C++ videos are coming and that they were important to you and the community so was the 'important' part yet another microsoft PR lie ?
What is your time table with the other C++ videos, i'm craving C++ videos and my patience is running low after a few weeks..month of waiting.
I'm trying to express my worry and concern here.
Charles, give that sloppy noob video editor a friendly slap from me.
wow, Part 5 you managed to mess-up even more (out of sync, black stripes, etc), do you get paid to do it wrong ?!
What's wrong with these videos, exactly? Parts 4 and 5 were encoded by somebody who is far from a noob... That said, I will pass along your feedback to him. Would be nice if you could remove your harshness and replace with useful feedback. Please do provide it.
These release as soon as we can make them. Stephan has a very busy day job, so we get him into the studio when it's convenient for him. There is a lot of C++content on C9 (and there has been for a long time....). New content in on the horizon including more lectures.
Re: Part 5: this is being corrected. My apologies.
C
[Tominator2005]
> It wasn't helper functions but Helper Classes, as in classes with static functions,
Writing a class that contains only static member functions is usually silly. (Non-member functions in namespaces would be a better idea.) However, there's at least one case where such classes are definitely useful. Function templates cannot be partially specialized; they can be overloaded, which has the same effect 98% of the time. The rest of the time, when you really do need partial specialization, you can partially specialize a class with static member functions, and that'll get the job done.
[Mr Crash]
> I do enjoy watching these STL videos and request a lot more please
> But why does it take so long to release them ?
Glad you like them. Editing is a black box to me, but I know what determines my frequency of filming. As you're aware, I work with Dinkumware to maintain VC's implementation of the C++ Standard Library. Because this implementation is inherently very complex, and the C++0x Working Paper has been a fast-moving target for the last several years, this is a lot of work! I try to write blog posts and film videos whenever I can, but this competes for time with my development work (i.e. making VC11's STL even more awesome than VC10's), so I have to balance them.
In terms of time, Parts 4 and 5 were even more expensive than 1, 2, and 3, because I wrote a large example program. I almost never get the chance to do that. Part 6 (which will cover algorithms and customizing them with functors, unless I think of a better idea) will go back to my (organized) stream of consciousness, which requires little advance preparation, but I'm on vacation this week, so I won't be able to film it immediately.
@STL:
> But why does it take so long to release them ?
I was unclear here, sorry. I meant the time between filming and release video to public
Does the video editing/encoding take that long ? Do you use some kind of queue system?
@Charles:ok, i guess i could help with translating my feedback
Do you have an e-mail address i can send the feedback to (i plan to include some pictures to better show what i mean)
Mr_Crash! Have you ever used Windows Media Encoder? Do try, and in the meantime go visit your family in another state
Vector of vectors is appropriate for a text editor, less appropriate for relational data where you want to do things to rows, and totally inappropriate for a matrix, unless the matrix is so huge that you cannot keep it all in RAM --- but then, please explain the options for low RAM environments because STL is not an option for various reasons. And, even if you insist, the interface class should be called Matrix (or, in fact, Grid proper) and use a vector of vectors as an implementation detail.
And I do not think that explaining the viewers that the numbers count the fields in contiguous white areas would be such a waste of time. I am watching your videos in circumstances where I cannot type.
[giecrilj71pl]
> Vector of vectors is appropriate for a text editor, less appropriate for relational data where you want to do things to rows, and totally inappropriate for a matrix
It works fine for Nurikabe. (I agree with you that solutions should be chosen so that they're appropriate for the problem domain - and the problem domain in this example is Nurikabe.)
One of my todos is to investigate storing the cells in a 1D vector. I actually did that during my development (it makes parsing somewhat easier, as cells can be stored in input order), but I never thought about using 1D coordinates everywhere as well. I suspect that my reliance on pair<int, int> may affect performance.
> but then, please explain the options for low RAM environments because STL is not an option for various reasons.
Actually, the STL is extremely good at conserving space.
> And, even if you insist, the interface class should be called Matrix (or, in fact, Grid proper) and use a vector of vectors as an implementation detail.
My Nurikabe Grid class uses a vector of vectors as an implementation detail. It is strongly encapsulated and nobody outside of the Grid is aware of its presence. I saw, and continue to see, no reason to further encapsulate the Grid's storage. (On the other hand, Region is a nontrivial data structure, which benefits greatly from the partial encapsulation that I gave to it.)
> And I do not think that explaining the viewers that the numbers
> count the fields in contiguous white areas would be such a waste
> of time. I am watching your videos in circumstances where I cannot type.
I'm sorry, I don't understand. Are you saying that I should have explained the meaning of the numbers in a Nurikabe grid? As I recall, I clearly stated in the video that Wikipedia's Nurikabe page was required reading. I also linked to it in the source code.
Thanks for your great lectures, I appreciate how you got into the scaling factors of the STL containers. The O factors have never been explained in plain english before!
vector::reserve() can make populating a big list 100x faster! You should mention the performance improvement in future lectures. I use the following function, same as mentioned to check the time:
#include <windows.h> double CurrentTime (){ LARGE_INTEGER freq; LARGE_INTEGER time; QueryPerformanceFrequency( &freq) ; QueryPerformanceCounter(&time); double ct = (double)time.QuadPart / (double)freq.QuadPart; return ct;}
I am a Java programmer, using shared_ptr and STL containers, as well at std::string, the programming style has become intuitively very similar!
The nurikabe program is quite verbose for a puzzle that only needs to follow 8 simple rules. Can someone try to code this in F# and see how it compares?
Your correctly observed in Installment 1 how the triple A-I-C saves us from having A*C implementations. However, this only applies to source code, because the object code will contain (up to) A*C implementations (actually A*C*T). Of course, most code sets do not use all pairs; however, depending on the domain, the object size can skyrocket. This is not a big problem for algorithms like find, and any algorithms you would type inline off your head, but complex and long template algorithms do exist, e.g. sort. That was a significant problem for Adobe when they created their image manipulation library.
On the other hand, a Matrix is a fairly general data structure, and if you promoted your implementation to a separate component, you could use it elsewhere. But then my criticism at your implementation choice would be much more valid, so it was actually clever to hide it
[Scott C]
> Thanks for your great lectures, I appreciate how you got into the scaling factors of the STL containers.
> The O factors have never been explained in plain english before!
I'm glad to be of service.
> vector::reserve() can make populating a big list 100x faster!
> You should mention the performance improvement in future lectures.
Actually, this is not true. Understanding why is enlightening.
Imagine that you're using an STL implementation with a 2x growth factor for vector. Then you push_back() N = 2^20 + 1 = 1048577 elements. (This is not a rigorous mathematical proof because I am not a mathematician, but the logic is sound, and insensitive
to my example N.) How many element copies during reallocation have been performed? (I have sneakily chosen N to maximize the number of element copies relative to the number of final elements; i.e. the worst-case ratio.) Well, look at the vector's capacity()
as it underwent reallocation. It was 0, 1, 2, 4, 8, 16, 32, ..., 1048576 (the capacity before pushing back the last element), 2097152 (the final capacity). The number of element copies performed was 1 + 2 + 4 + 8 + ... + 1048576 = 2097151. So, with N elements,
the worst-case number of element copies during reallocation is almost exactly 2N. (This is what "linear time" means, and we've just discovered the constant factor associated with it.)
Because reserve() eliminates unnecessary element copies during reallocation, when you use it, you'll construct exactly N elements. So, with a 2x growth factor STL (like GCC's libstdc++), calling reserve() will improve your performance by at most 2x, ignoring
other factors (like the cost of an allocation itself). Not 100x.
With a 1.5x growth factor STL, like VC's, the numbers change but the principles stay the same. Suppose you push_back() N elements, where N is just over a capacity boundary. (Because of the 1.5x growth factor and integer arithmetic, these boundaries aren't
convenient to exactly calculate, but 1049869 is the first boundary over a million, so you could use N = 1049870 as a concrete example.)
The last reallocation copied N - 1 elements, and then pushed back 1 more. I'm going to call that approximately N copies (ignoring the "- 1" is okay). The reallocation before that copied N / 1.5 = (2/3) * N elements. The one before that copied (2/3)^2 * N
elements, and so forth. The total number of copies is approximately (ignoring the integer arithmetic is also okay)
N + (2/3) * N + (2/3)^2 * N + (2/3)^3 * N + ... explains that 1 + r + r^2 + r^3 + ... = 1 / (1 - r), so we've performed N * 1 / (1 - (2/3)) = N * 1 / (1/3) = 3N copies.
So with VC's implementation, calling reserve() will improve your performance by at most 3x. Let's test this experimentally:
After the numbers stop bouncing around, the observed speedup is roughly 889.658/314.778 = 2.83x, which agrees with the theoretical calculation above.
> The nurikabe program is quite verbose for a puzzle that only needs to follow 8 simple rules.
Simple rules don't imply simple solvers.
[giecrilj71pl]
> That was a significant problem for Adobe when they created their image manipulation library.
"Template code bloat" can be an issue for other libraries, but it isn't a major problem for the STL itself, which has few truly large algorithms, and doesn't actually have that many containers.
I'll also point out that /OPT:REF,ICF discards unreferenced functions and folds binary-identical functions, so binary-identical template instantiations (like for A *, B *, C *) are harmless. Binary-different template instantiations are maximizing runtime
perf at the (typically minor) cost of executable size. If you want to reduce the amount of generated code, you'll typically need something like type erasure, which has runtime costs.
> On the other hand, a Matrix is a fairly general data structure, and if you promoted your implementation to a separate component, you could use it elsewhere.
The Nurikabe grid isn't a mathematical matrix.
Why not? It is rectangular and it contains numbers and symbols in the cells.
Mathematical matrices undergo operations like addition, multiplication, and so forth. Nurikabe isn't linear algebra.
I stand corrected, yes I understand and have retested that using vector.reserve() only increases performance by at best 3x, and actually become close to 1:1 at larger sizes.
Also, a few authors have mentioned its best to keep objects in STL containers for safer memory management, rather than using STL to hold pointers to object in the heap. Any suggestions how one can push objects into an STL container and use them efficiently? Most of the STL documentation deals with data structures rather than class objects with behaviour. I've found the following function calls the destructor 3 times for my class.
MyFunction() {
vector<GameEntity>.push_back(GameEntity())
GameEntity gameEntity = vector.back();
gameEntity .start();
}
> Also, a few authors have mentioned its best to keep objects in STL containers for safer memory management, rather than using STL to hold pointers to object in the heap.
Correct. vector<T>, vector<shared_ptr<T>>, and vector<unique_ptr<T>> are all good. vector<T *> where the pointers have been newed and must be deleted is bad. It's virtually guaranteed to leak memory; this was covered in Part 3.
(vector<T *> where the pointers point to objects that will outlive the vector is fine, and can occasionally be useful.)
> Any suggestions how one can push objects into an STL container and use them efficiently?
Give your classes move constructors and move assignment operators. Then using them with the STL will generate maximally efficient code. (STL objects already have move constructors and move assignment operators, so things like vector<string> and vector<vector<int>> are already efficient.)
I'll describe what happens with this if GameEntity is copyable but not movable (or if you're using VC9, which you shouldn't be - please, please upgrade to VC10):
vector<GameEntity> v;
v.push_back(GameEntity());
This constructs a temporary GameEntity (that's the GameEntity() expression). Then, a vector element GameEntity is copy-constructed from the temporary. Then the temporary is destroyed (temporaries are destroyed "at the semicolon").
If the vector undergoes reallocation, you'll see copy constructors being invoked for elements in the new memory block, and destructors being invoked for elements in the old memory block.
GameEntity gameEntity = v.back();
v.back() returns a reference to the last element in the vector. Then you copy-construct the local variable gameEntity from this vector element.
gameEntity.start();
You call the start() member function on this local variable, not the vector element (or the original temporary, which is long gone).
If you wanted to call start() on the vector element, you'd say either v.back().start(), or:
GameEntity& r = v.back();
r.start();
This binds a reference r to the last element of the vector, then invokes start() through the reference.
If GameEntity‘s copy constructor has trivial path, there is a workaround, although contrived and against the bitzkrieg convention that objects in C++ should not have an error state: push back a temporary constructed to follow that trivial path and do serious things to v.back() afterwards.
This is a great example of c++ and STL. However, the implementation itself is not able to fully explore puzzles where multiple solutions exist. I want to emphasize that the scope of the solver was never to determine all possible solutions for a puzzle so I am not criticizing here, just observing.
Consider this puzzle, which has 212 solutions:
"big5", 5, 5, " \n" " 7\n" " \n" "8 \n" " \n"
The solver yields "I'm Stumped!" at the second step.
Now this puzzle, which has 2 solutions:
"hasTwo", 5, 5, " 7 \n" " \n" " 4\n" " \n" " 2 2\n"
The solver yields only the first solution, presumably because of the deterministic solving techniques.
I'm not a c++ programmer, but I did write a solver in F# that does find all solutions for a given puzzle using a technique called "recursively expanding neighborhoods" (source: , page 7). I would be interested to see if anyone has explored this further in c++.
@John:
Sorry for the poor formatting. Not sure what happened there.
Remove this comment
Remove this threadclose | http://channel9.msdn.com/Series/C9-Lectures-Stephan-T-Lavavej-Standard-Template-Library-STL-/C9-Lectures-Stephan-T-Lavavej-Standard-Template-Library-STL-4-of-n?format=smooth | CC-MAIN-2015-06 | refinedweb | 5,063 | 63.8 |
jakzaprogramowac.pl
All questions
About the project
How To Program
How To Develop
Data dodania
Pytanie-14 11:09
Rails geocoder gem show results »
I'm using the geocoder gem in order to set the longitude and latitude from the address: class Item < ApplicationRecord geocoded_by :full_addre...
(1) odpowiedzi
2017-09-13 21:09
ActiveRecord is not reloading nested object after it's updated inside a transaction »
I'm using Rails 4 with Oracle 12c and I need to update the status of an User, and then use the new status in a validation for another model I also nee...
(0) odpowiedzi
2017-09-13 17:09
Google api client calendarv3 event initialization argument error »
I'm using google_api_client 0.10.3. I have this call: Google::Apis::CalendarV3::Event.new({ 'summary' => summary, 'description' => descript...
(1) odpowiedzi
2017-09-13 17:09
Rails Has Many Through date field of one model falls between dates of other model »
Setup: I have a Job and a Price model where the Job has two fields start_date and end_date and the Price has another date field effective_at. The Job ...
(1) 20:09
Two ordering parameters - Rails »
I have an application, where I need to sort ideas on the main screen: By the number of votes for an idea By the descending date This is my control...
(1) odpowiedzi
2017-09-11 18:09
Ruby On Rails Error 204 generate an image into a new view from controller »
I have in my controller a method to create a custom qr def generate_qrcode() require 'rqrcode' qrcode = RQRCode::QRCode.new('ejemplo') image = qrcode...
(3)-10 23:09
Ruby on Rails - Make view accessible to certain users »
In my application I have models File & FileAccess. User A can upload files and give access to many other users (by other users asking for access)....
(1) odpowiedzi
2017-09-10 21:09
Rails extract values with join associations »
I have a rails join table between 2 models superhero and superpower. Now I have 3 different superpower id and I want all the superheroes which have al...
(2) odpowiedzi
2017-09-10 18:09
Rails inconsistent model associations call »
I have a rails model for a user as: class Player < ActiveRecord::Base has_and_belongs_to_many :character_factors has_and_belongs_to_many :stat...
(1) odpowiedzi
2017-09-10 14:09
Sort a resource based on the number of associated resources of other type »
I have a Movie model that has many comments, I simply want to sort them (Movies) using SQL Inside active record based on the number of associated comm...
(1) odpowiedzi
2017-09-09 13:09
in search this is not working in jquery datatable in rails 4 »
"search": {'caseInsensitive': true,'regex': true}, this is not working in my project and my search is working as case sensitive how to figure it out ...
(0) odpowiedzi
2017-09-08 20:09
Ruby on Rails - Add & Remove record from table when click twice »
In my application I've a button called Interested. When this button is clicked it'll add a record to interests table with user_id & post_id. This...
(2) odpowiedzi
2017-09-08 19:09
Ruby on Rails, missing FROM-clause entry for table "pages" »
trying to resolve this pesky bug after converting a Rails app from 3.0 to 4.29 I've got a Scope attached to the model PostType that's complaining it ...
(1) odpowiedzi
2017-09-08 08:09
Rails how to query has_many instance in condition of the instance not exist »
Please help! I need to combine those query clauses below into one. Foo.where('bar_id IS NULL') Foo.joins(:bar).where('bar.daily_budget > bar.dai...
(3) odpowiedzi
2017-09-07 19:09
What does specifying the type in an RSpec actually affect? »
I have never been sure what the difference between these options are RSpec.describe V2::DirectMessagesController, type: :controller vs RSpec.descr...
(1) odpowiedzi
2017-09-07 17:09
Is it possible to filter (search) results at query level when using grape gem in Rails 4 app? »
I am using gem grape to build out an api for an app. i am able to get all the endpoints i want working, however it has been difficult to get search fu...
(0) odpowiedzi
2017-09-07 15:09
Rails: elasticsearch query block error »
I'm using elasticsearch on my rails app and every time I try to add a block to the def self.search(query) I get an error: [400] {"error":{"root_cause...
(0) odpowiedzi
2017-09-06 19:09
Rails: Elasticsearch::Transport::Transport::Errors::BadRequest in Search#search »
I'm using the elasticsearch gem on my rails app. I'm trying to implement a basic search and sort the results by the distance from the current location...
(0) 11:09
Xeroizer::ApiException : QueryParseException: No property or field 'inv_id' exists »
I am Trying to get all the invoices in a single API hit. Because, for every user having 100's of invoices. It will exceed the API limit (Minute Limi...
(1) odpowiedzi
2017-09-05 13:09
How to disable previous date on edit using datetime picker »
I am using date time picker.on edit page the selected value is not displaying. when I check the code element, I am seeing the result in value attribu...
(1) odpowiedzi
2017-09-05 13:09
How to redirect user after registration in apartment gem »
I am using apartment gem to achieve multitenancy. When registers on the app I want to redirect him to his own url example for localhost (xyz.localhost...
(1)
import records using .xlsx »
I am trying to import records using excel sheets and so far everything works quite well, the problem comes when I try to add related records to the pr...
(0)-04 09:09
Search In a column which stores an array »
In my table professional_infos table there is one column primary_skill_ids which stores an array of skills for particular user. I want to list all the...
(1) odpowiedzi
2017-09-03 12:09
Running Rails Console Gets Killed »
When i run on my production servers the command: bundle exec rails c production After few seconds i get "Killed", the server has 32GB RAM and have ...
(0) odpowiedzi
2017-09-03 09:09
Two references of the same model in another Rails: 4 »
I ask if it is good to have two references of one model in another and if it can do it how do I do it? Problem: I have a record that will be controll...
(1) odpowiedzi
2017-09-02 22:09
how to fetch data quickly in join query? »
I have 3 tables users, orders and comments every tables has 10087250,24949600 and 26532000 much records, I made this query to counts comments on every...
| http://jakzaprogramowac.pl/lista-pytan-jakzaprogramowac-wg-tagow/97/strona/3 | CC-MAIN-2017-43 | refinedweb | 1,120 | 60.04 |
This article describes how to optimize the performance of enterprise systems that employ extensive time-stamping using the time(2) system call in the Solaris Operating System. This optimization applies especially to the financial market, and is based on our work with a number of different independent software vendors (ISVs).
time(2)
We have observed that the common practice of "time-stamping" messages, transactions, or other objects in a system can consume more resources than the developer might expect. In these systems, the time(2) system call is used to obtain the current time with which to stamp each message or object. (The time(2) system call returns the value of time in seconds since 00:00:00 UTC, January 1, 1970.)
With many -- often thousands, or tens of thousands -- of active objects in typical enterprise system, this can lead to an excessively high use of system CPU cycles. We have observed systems processing thousands of transactions or messages every second, each of which requires a time stamp every time it is acted upon. Such systems can end up calling time(2) several thousands of times per second, incurring a significant overhead in system resources.
Two ways are available to reduce time(2) system call overhead. The first is to use our proposed optimized time(2) replacement solution that uses the caching technique to reduce the time(2) system call frequency. The second is to reduce the frequency of time(2) system calls in the application code. The suggested quick solution employs interposed libraries so there is no need to change the original application code.
As an example, we have taken a sample application that performs data distribution for analysis. The application handles thousands of messages every second. Each message is time stamped with the current time, using the time(2) system call. One way to find out the frequency of use of time(2), or any other system call, is to use the truss(1) command, a utility in the Solaris OS that traces system calls and signals. For example:
truss(1)
% truss -c -p pid
Here pid is the process ID for the sample application and the -c option is used to count traced system calls, faults, and signals (rather than displaying the trace line-by-line, which is the default behavior). A summary report is produced after the traced command terminates or when truss is interrupted by Ctrl C.
-c
truss
In Code Sample 1, we see an example truss output for the sample application process (whose pid was 1365). In this case, the truss command was terminated after a sufficiently long sample interval by a Ctrl-C.
% truss -c -p 1365
^C
syscall seconds calls errors
read .639 18636 956
time 8.376 785118
semop .007 544 170
poll .362 23378
writev .627 32191
recv .000 14
sendmsg .031 1028
------ ------ ----
sys totals: 10.045 860909 1126
usr time: 39.000
elapsed: 84.980
truss -c -p 1365
The results show that 785,118 calls were made to time(2) in the sample time of 84.98 seconds. That is nearly 10,000 calls to time() every second. A large amount of system time (10.045 seconds) was devoted to servicing these calls.
time()
Since the time(2) call has a one-second granularity, making this call several thousand times per second is certainly unnecessary. We can optimize the use of time(2) for the purposes of time stamping by implementing a local time() function which caches the current time, and only makes a system call when enough time has elapsed between calls. If insufficient time has elapsed since the last call to our local time function, we simply return the cached value. We can do this because we have, in the Solaris OS, access to another time function that is substantially faster than time(2), which is gethrtime(3C). (See "Measuring Execution Time in POSIX Compliant Programs and UNIX" in References section.)
gethrtime(3C)
The book Inside Solaris, by Richard Mc Dougall and Jim Mauro, says the following about gethrtime(3C):
gethrtime(3C) is known as a fast trap system call. This means that an invocation of gethrtime(3C) does not incur the normal overhead of a typical system call. Rather, it generates a fast trap into the kernel, which reads the hardware TICK register value and returns. While many system calls may take microseconds to execute (non-I/O system calls, that is; I/O system calls will be throttled by the speed of the device they're reading or writing), gethrtime(3C) takes a few hundred nanoseconds on a 300 MHz UltraSPARC processor. It's about 1,000 times faster than a typical system call.
The source code for the shared library (libfasttime.so) is given below. In this module, the symbol for time(2) is interposed to execute the optimized, caching time() library function. Thus, code changes in the rest of the application are unnecessary. The new function obtains the current high-resolution time (in nanoseconds) using gethrtime(3C), and compares it to the (cached) value of when the function was last called. If the call was issued within a certain delta, in the code below defined to be 1 millisecond, the cached value is returned, and no time-consuming system call is made. Once sufficient time has elapsed between the original call to time() and the current one, the system call is made, the cached value is reset, and the process starts over.
libfasttime.so
To compile the time.c file to build a libfasttime.so library, use:
time.c
% cc -G -Kpic -o libfasttime.so -xO3 -xarch=v8plus time.c
For a quick performance testing, this library can be preloaded for the purposes of linking with an application by setting the following (in bash):
LD_FLAGS_32=preload=/tmp/libfasttime.so
However, the preferred way is to link this libfasttime.so library during the build of your application.
Note: This library can also be compiled in 64-bit mode for 64-bit applications by using:
% cc -G -Kpic -o libfasttime.so -xO3 -xarch=v9 time.c
The library also can be preloaded by setting the following (in bash):
LD_FLAGS_64=preload=/tmp/libfasttime.so
In Code Sample 2, we provide the source code for the time(2) wrapper.
/*
*
* 4150 Network Circle, Santa Clara, CA 95054
*
* This software is the proprietary information of Sun Microsystems, Inc.
* This code is provided by Sun "as is" and "with all faults." Sun
* makes no representations or warranties concerning the quality, safety
* or suitability of the code, either express or implied, including
* without limitation any implied warranties of merchantability, fitness
* for a particular purpose, or non-infringement. In no event will Sun
* be liable for any direct, indirect, punitive, special, incidental
* or consequential damages arising from the use of this code. By
* downloading or otherwise utilizing this codes, you agree that you
* have read, understood, and agreed to these terms.
*
*/
#include <sys/types.h>
#include <time.h>
#include <stdio.h>
#include <dlfcn.h>
/* to compile, use cc -G -Kpic -o libfasttime.so -xO3 -xarch=v8plus time.c */
/* time in nanoseconds to cache the time system call */
#define DELTA 1000000 /* 1 millisecond */
static time_t (*func) (time_t *);
time_t time(time_t *tloc)
{
static time_t global = 0;
static hrtime_t old = 0;
hrtime_t new = gethrtime();
if(new - old > DELTA ){
global = func(tloc);
old = new;
}
return global;
}
#pragma init (init_func)
void init_func()
{
func = (time_t (*) (time_t *)) dlsym (RTLD_NEXT, "time");
if (!func)
{
fprintf(stderr, "Error initializing library\n");
}
}
fasttime
% truss -c -p 1701
^C
syscall seconds calls errors
read 1.205 36702 2766
time .762 71953
semop .006 541 169
poll .672 44705
writev 1.204 59945
recv .000 12
sendmsg .003 84
------ ------ ----
sys totals: 3.855 213942 2935
usr time: 62.183
elapsed: 84.700
truss -c -p 1701
These code samples show that the number of times time(2) was called decreased by 90 percent, and the system time was reduced by 60 percent. This improved the performance of the sample data distribution application overall. The sample application was able to provide noticeably more throughput per second compared to when it was running without the libfasttime.so library. Since sampling theory tells us that to completely capture a signal we need only sample at twice the rate of the highest frequency, DELTA in Code Sample 2 could be changed to 500 milliseconds with no change of behavior and with potentially even more time savings.
So if you have a system that makes extensive use of time stamping, or otherwise makes frequent calls to the time(2) function, try the optimization we have outlined here.
M. Amjad Khan, a senior engineer in the Market Development Engineering organization, has been with Sun for more than five years. He is currently responsible for empowering ISVs and developers to adopt and migrate to Sun's latest technologies. He has worked on a range of technologies, including Java technology APIs for printing, NT migration, Sun compilers, and the Sun Java Enterprise System. Amjad is a certified Sun ONE (JES) Application Server Developer and Java Programmer and holds an M.S. Degree in Computer Science. | http://developers.sun.com/solaris/articles/time_stamp.html | crawl-002 | refinedweb | 1,514 | 64.61 |
perlquestion Anonymous Monk Dear Monks, <p> I have a bunch of XML files from my GPS, and I'd like to extract data from them, and play around with them, displaying them graphically for one. As it's done properly, it has its own schema, and uses its own namespace. One such file can be found at </p> <p> So, in order to parse such an XML file, you have to register it with XML::LibXML (using a variable $string as the prefix) <code> my $parser = XML::LibXML->new->parse_file($file); my $xml = XML::LibXML::XPathContext->new($parser); $xml->registerNs($string,''); </code> Now, extracting the value of an attribute poses no problem: <code> for my $key ($xml->findnodes('//x:Lap')) { $string = norm_date($key->findvalue("\@StartTime")); } </code> Just in case anyone is worried, there (usually) is only one Lap per file. </p> <p> The problems start when I want to extract the timestamps from each recorded datapoint. My first try was <code> for my $node ($xml->findnodes('//y:Trackpoint')) { $time = $node->findvalue("Time"); push @X,$time; } </code> This fails. It does find the set of nodes, but fails to find the timestamp that's in the Time element. Experimenting with the examples I Googled, I found the following, which does give me the timestamps: <code> for my $node ($xml->findnodes("//y:Trackpoint")) { for my $ch ($node->childNodes) { $time = norm_date($ch->textContent)-$epoch if $ch->nodeName =~ /Time/; } push @X,$time; } </code> That's nasty. It does work, but it's nasty. </p> <p> So, the question is: why does the findvalue function fail to work with a non-default namespace? Or am I missing something? </p> 7 | http://www.perlmonks.org/?displaytype=xml;node_id=1003089 | CC-MAIN-2015-32 | refinedweb | 275 | 64.34 |
Excel code creating xml filesJobs
...application for sending bulk sms through Notepad, Excel files and send sms with personalize and Group SMS & also partial sms also. • Re sellers Manage their customers on-their-own. • API Integration for all service ( Need XML integration and HTML integration ) • Separate SMS Sending interface for Excel , Group , And Single ,Personalized ( Look...
.., [log ind for at se URL], SignalR (Real-time web functionality to applications). • Data Bases:
... Thanks, Mark ## Deliverables **VBA Excel: HTTP Downloads and Chart Configuration** This is an initial stage for a system with more functionality. Possible future functionality will be referred to here when it might impact design decisions. **Overview** We want a simple way of creating a chart whose specification and data are downloaded
..
...import product data from .xml file over HTTP into Joomla & Virtuemart based web site. We also got excel sheets of the same data in xml Product files will contain complex product information, including multiple custom attributes like page yield, page density etc. We need to write a php script that will automatically read .xml file over HTTP and import
...unit testing and very strong at XML/XSLT first project requires transformation of Excel into XML, must be able t o take a schema and create the code to import files that will validate. Must be able to code to pre-specified unit test (simple test that will check work is satisfactory such as passing a filepath and getting XML back that validates) E...
...This project is to convert an existing VB application to a Linux application that runs in CentOS. The current VB app reads data from source files (text,excel, xml) dumped in a specific folder and parses the files to grab the requested data and insert them in a table in a MSSQL server database. I am changing my server from Microsoft server 2003
Vær venlig at Tilmelde dig eller Log ind for at se detaljer.
.. row in the Excel file a new word document
I have two csv files that share a common word. A desktop program needs to be developed that gets specific fields from both files and creates an excel spreadsheet (not just a csv file to import into excel). Code needs to be placed on each of the columns on the excel spreadsheet so that clicking it will sort the entire data by the contents of that
This project entails creating a multi-step booking form for existing HTML travel website. The forms (only HTML code) inside 1. Booking form multi-step 2. Contact form 3. Advertising form 4. (not in Tour) 5. ( not av. Flight) 6. (not av. Packages) 7. (not av cars) needs to be create in php and mysql. The MySQL Database needs to create complete
.. development of existing sites and
We have a UK customer with a live Pegasus Opera I accounts system. Pegasus Opera I is written in FoxPro DOS, source code not available, runs on FoxPro database. This project is to create a Customer Sales Returns program that can manage Customer Returns (RMAs) and insert Sales Credit orders into Opera. A Sales return (RMA) is a document that
...accounts system. Pegasus Opera I is written in FoxPro DOS, source code not available, runs on FoxPro database. This project is to create a program that can import XML sales order files and insert Sales orders into Opera, also export Opera Products, Special prices and Discounts to XL files ready fro importing into the standalone Quotations program.
...ecommerce web site - this is a separate project. There are issues such as different prices/discounts for different customers. Pegasus Opera I is written in FoxPro DOS, source code not available, runs on FoxPro database. We need to create a batch mode interface program that will manage Customers, Products, Orders and Receipts between the two systems
...that converts an Excel Spreadsheet to an XML file (simply by creating a node for each row in the Excel spreadsheet, and in each row an attribute for each column value - the first row describes the column/attribute names; build and run the application once to get the feel for what the conversion does). I have attached full source code for a small portion | https://www.dk.freelancer.com/job-search/excel-code-creating-xml-files/ | CC-MAIN-2019-13 | refinedweb | 699 | 62.48 |
deepika deepi wrote:How and where to change the code to get the result. If you can help me
Winston Gutkowski wrote:
deepika deepi wrote:How and where to change the code to get the result. If you can help me
Well, I'd question the need for a DataInputStream for a start. If you look at the documentation for BufferedReader, its specific example is:
BufferedReader in = new BufferedReader(new FileReader("foo.in"));
Is there any reason why you can't just use it?
Winston
Jesper de Jong wrote:I don't understand what the exact problem is. Can you explain, as clearly and in detail as possible, how the current actual output is different from what you expect?
deepika deepi wrote:ya.. At times when i use that it is show some error. so i am using DataInputStream
deepika deepi wrote:
Is it wrong to use ? can you tell me some example why to use BufferedReader and not DataInputStream?
Campbell Ritchie wrote:…But the Java Tutorials are easier to read.
R. Jain wrote:You just need 4 lines of code in regex to get that output.. You would be better off with it..
deepika deepi wrote:
R. Jain wrote:You just need 4 lines of code in regex to get that output.. You would be better off with it..
I have tried with sample code in net for trial. with indexOf
Error is
found : int
required: java.lang.String
String result = s.indexOf("break");
^
1 error
deepika deepi wrote:
and the code is
import java.lang.*;
import java.io.*;
public class ContainsString {
public static void main(String[] args) {
String s = "That was the breaking News and the headlines is important for today because India break the record";
System.out.println(s);
String result = s.indexOf("break");
System.out.println("indexOf(the) -> " +result );
}
}
I want the sentence output leaving the word "break".
deepika deepi wrote:
In this i want to leave the word namah, and in last i have om/shivan i want to remove the word after "/" and get the result like om namah shivaya om is the god
how to change this to string and get the result?
changu mani wrote:Use this Deepika
String result = s.replaceAll("break", "");
The return type of indexOf is int and not string. Please check.
deepika deepi wrote:I want the sentence output leaving the word "break".
...
In this i want to leave the word namah, and in last i have om/shivan i want to remove the word after "/" and get the result...
Winston Gutkowski wrote:
What exactly do you want to do? Right now, you just seem to be flailing around.
You must be precise about your requirements. If you aren't, you will never learn to program properly.
Winston
deepika deepi wrote:But i want to try and get the result using indexOf so that i can be familiar with this. | http://www.coderanch.com/t/591247/java/java/change-character-string-java | CC-MAIN-2014-52 | refinedweb | 482 | 75.1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.