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 |
|---|---|---|---|---|---|
QML Code not running
hi
i just install nokia qt sdk on windows 7. Now i am trying to run qml code of hello world. It says "The process could not be started!". help please
- anselmolsm
More information, please.
here is my code
helloWorld" ]
}
@
helloWorld.qml
@
import Qt 4.7
Rectangle {
width: 200
height: 200
Text {
x: 66
y: 93
text: "Hello World"
}
}
@
this is the error
@
Starting D:/NokiaQtSDK/QML/helloWorld/helloWorld.qml
The process could not be started!
@
this is the information. Can you please tell me what sort of information do you need to solve this particular problem?
well, that's because D:/NokiaQtSDK/QML/helloWorld/helloWorld.qml is not executable)
qml should be opened with qmlviewer
but when i try this same code in ubuntu it works. but on windows it doesnt. Can you tell me how can i make it executable?
on ubuntu it works because i did not install nokia qt sdk on that i simply installed Qt Creator May be that is the reason it works on ubuntu. But i still need help on how can i make this code executable
You can't make qml into executable files. What you can do is create a cpp wrapper application around your qml code.
If you download the qt creator beta 2.1 there is a "qml application" project template that should give you what you are looking for.
By the way: if you install the qt creator beta you should be able to start the qml viewer from qt-creator using CTRL+R.
it is working fine in Qt creator. The problem is when i run the same code in Nokia Qt SDK in windows then it displays me this error. In Linux its perfect.
Have you tried launching qmlviewer.exe in Windows?
how can i launch qmlviewer? i think it is launched when you start qt creator in nokia qt sdk
You can launch any qml app with qmlviewer. It is located in qt\bin folder. Just launch it, and then open your qml file in it.
i could not find qmlviewer in qt/bin folder. I have a bin folder in QtCreator folder. like QtCreator/bin but there is no such thing as qmlviewer
No no, not Qt Creator. The actual Qt. Usually it is located somewhere in c:\qt\4.7.0\qt\bin. | https://forum.qt.io/topic/1891/qml-code-not-running | CC-MAIN-2018-05 | refinedweb | 394 | 85.89 |
Spiceworks 5.0 has started with some new issues. 1; it will not draw in emails from helpdesk to the ticketing program, unless I hit refresh tickets. 2; it will not reply to the user.
If I restart the services it will work for sometime, not sure how long, I do know I need to do this at least once a day.
This topic was created during version 5.0.
The latest version is 7.5.00101.
1 Reply
Jan 24, 2011 at 8:05 UTC
Petes PC Repairs is an IT service provider.
does sound like its got it knickers in a twist
back up your db
unistall then reinstall
import you db
then check through your settings and pluggins to make sure all is well
let us know if this settles it down
This discussion has been inactive for over a year.
You may get a better answer to your question by starting a new discussion. | https://community.spiceworks.com/topic/125157-tickets-not-working-correctly | CC-MAIN-2017-34 | refinedweb | 158 | 79.6 |
Using macros to create “custom verbs”
Day-to-day interaction with Bazel happens primarily through a few commands:
build,
test, and
run. At times, though, these can feel limited: you may want to
push packages to a repository, publish documentation for end-users, or deploy
an application with Kubernetes. But Bazel doesn’t have a
publish or
deploy command – where do these actions fit in?
The versatility of
bazel run
Bazel’s focus on hermeticity, reproducibility, and incrementality means the
build and
test commands aren’t helpful for the above tasks. These actions
may run in a sandbox, with limited network access, and aren’t guaranteed to be
re-run with every
bazel build.
Instead, we rely on
bazel run: the workhorse for tasks we want to have side
effects. Bazel users are accustomed to rules that create executables, and rule
authors can follow a common set of patterns to extend this to “custom verbs”.
In the wild:
rules_k8s
For an example, consider
rules_k8s,
the Kubernetes rules for Bazel. Suppose we have the following target:
# BUILD file in //application/k8s k8s_object( name = "staging", kind = "deployment", cluster = "testing", template = "deployment.yaml", )
The
k8s_object rule builds a
standard Kubernetes YAML file when
bazel build is used on the
staging
target. However, the additional targets are also created by the
k8s_object
macro with names like
staging.apply and
:staging.delete. These build
scripts to perform those actions, and when executed with
bazel run
staging.apply, these behave like our own
bazel k8s-apply or
bazel
k8s-delete commands.
Another example:
ts_api_guardian_test
This pattern can also be seen in the Angular project. The
ts_api_guardian_test macro
produces two targets. The first is a standard
nodejs_test target which compares
some generated output against a “golden” file (that is, a file containing the
expected output). This can be built and run with a normal
bazel
test invocation. In
angular-cli, we can run one such
target
with
bazel test //etc/api:angular_devkit_core_api.
Over time, this golden file may need to be updated for legitimate reasons.
Updating this manually is tedious and error-prone, so this macro also provides
a
nodejs_binary target that updates the golden file, instead of comparing
against it. Effectively, the same test script can be written to run in “verify”
or “accept” mode, based on how it’s invoked. This follows the same pattern
we’ve learned already! There is no native
bazel test-accept command, but the
same effect can be achieved with
bazel run //etc/api:angular_devkit_core_api.accept.
This pattern can be quite powerful, and turns out to be quite common once you learn to recognize it.
Adapting your own rules
Macros are the heart of this pattern. Macros are used like rules, but they can create several targets. Typically, they will create a target with the specified name which performs the primary build action: perhaps it builds a normal binary, a Docker image, or an archive of source code. In this pattern, additional targets are created to produce scripts performing side effects based on the output of the primary target, like publishing the resulting binary or updating the expected test output.
To illustrate this, we’ll wrap an imaginary rule that generates a website with Sphinx with a macro to create an additional target that allows the user to publish it when ready. Consider the following existing rule for generating a website with Sphinx:
_sphinx_site = rule( implementation = _sphinx_impl, attrs = {"srcs": attr.label_list(allow_files = [".rst"])}, )
Next, consider a rule like the following, which builds a script that, when run, publishes the generated pages:
_sphinx_publisher = rule( implementation = _publish_impl, attrs = { "site": attr.label(), "_publisher": attr.label( default = "//internal/sphinx:publisher", executable = True, ), }, executable = True, )
Finally, we define the following macro to create targets for both of the above rules together:
def sphinx_site(name, srcs = [], **kwargs): # This creates the primary target, producing the Sphinx-generated HTML. _sphinx_site(name = name, srcs = srcs, **kwargs) # This creates the secondary target, which produces a script for publishing # the site generated above. _sphinx_publisher(name = "%s.publish" % name, site = name, **kwargs)
In our
BUILD files, we use the macro as though it just creates the primary target:
sphinx_site( name = "docs", srcs = ["index.html", "providers.html"], )
In this example, a “docs” target is created, just as though the macro were a
standard, single Bazel rule. When built, the rule generates some configuration
and runs Sphinx to produce an HTML site, ready for manual inspection. However,
an additional “docs.publish” target is also created, which builds a script for
publishing the site. Once we check the output of the primary target, we can use
bazel run :docs.publish to publish it for public consumption, just like an
imaginary
bazel publish command.
It’s not immediately obvious what the implementation of the
_sphinx_publisher
rule might look like. Often, actions like this write a launcher shell script.
This method typically involves using
ctx.actions.expand_template
to write a very simple shell script, in this case invoking the publisher binary
with a path to the output of the primary target. This way, the publisher
implementation can remain generic, the
_sphinx_site rule can just produce
HTML, and this small script is all that’s necessary to combine the two
together.
In
rules_k8s, this is indeed what
.apply does:
expand_template
writes a very simple Bash script, based on
apply.sh.tpl,
which runs
kubectl with the output of the primary target. This script can
then be build and run with
bazel run :staging.apply, effectively providing a
k8s-apply command for
k8s_object targets. | https://docs.bazel.build/versions/1.1.0/skylark/tutorial-custom-verbs.html | CC-MAIN-2021-17 | refinedweb | 915 | 54.52 |
Final.
Example of Final variable, Final method, and Class in Java
Now, let's understand the final keyword in detail in Java. We will start with final variable then explore final methods and finally the final class in Java. After going through these examples, you will learn the impact of making a variable, method, or a class final in Java.
1. What is a final keyword in Java?
2. What is the final variable in Java?
Any variable either a member variable or local variable (declared inside method or block) modified by final keyword is called final variable. Final variables are often declared with static keyword in java and treated as constant. Here is an example of final variable in Java
public static final String LOAN = "loan";
LOAN = new String("loan") //invalid compilation error
Final variables are by default read-only.
3. What is the final method in Java?
The final keyword in Java can also be applied to methods. A Java method with the final keyword is called a final method and it can not be overridden in the subclass. You should make a method final in Java if you think it’s complete and its behavior should remain constant in sub-classes.
In general, final methods are faster than non-final methods because they are not required to be resolved during run-time and they are bonded at compile-time, See these Java Performance courses for more details.
Here is an example of a final method in Java:
In general, final methods are faster than non-final methods because they are not required to be resolved during run-time and they are bonded at compile-time, See these Java Performance courses for more details.
Here is an example of a final method in Java:
class PersonalLoan{
public final String getName(){
return "personal loan";
}
}
class CheapPersonalLoan extends PersonalLoan{
@Override
public final String getName(){
return "cheap personal loan"; //compilation error: overridden method is final
}
}
4. What is the final class in Java?
Java class with the final modifier is called the final class in Java. The final class is complete in nature and can not be sub-classed or inherited. Several classes in Java are final e.g. String, Integer, and other wrapper classes. Here is an example of final class in java
final class PersonalLoan{
}
class CheapPersonalLoan extends PersonalLoan{ //compilation error: cannot inherit from final class
}
Benefits of final keyword in Java
Here are a few benefits or advantages of using the final keyword in Java:
1. Final keyword improves performance. Not just JVM can cache the final variables but also applications can cache frequently use final variables.
2. Final variables are safe to share in a multi-threading environment without additional synchronization overhead.
Final and Immutable Class in Java
Final keyword helps to write an immutable class. Immutable classes are the one which can not be modified once it gets created and String is a primary example of an immutable and final class which I have discussed in detail on Why String is final or.
Example of Final in Java
Java has several system classes in JDK which are final, some examples of final classes are String, Integer, Double, and other wrapper classes. You can also use a final keyword to make your code better whenever it is required. See the relevant section of the Java final tutorial for examples of the final variable, final method, and final class in Java.
Important points on the final modifier in Java
1. The final keyword can be applied to a member variable, local variable, method, or class in Java.
2. The final member variable must be initialized at the time of declaration or inside the constructor, failure to do so will result in a compilation error.
3. You can not reassign the value to a final variable in Java.
4. The local final variable must be initialized during declaration.
5. The only final variable is accessible inside an anonymous class in Java,, but in Java 8, there is something called effectively final variable, which is non-final local variables but accessible inside the anonymous class.
The only condition is that they should not be reassigned a value once created. If you do so, the compiler will throw an error. See Java SE 8 for Really Impatient for more details.
6. A final method can not be overridden in Java.
7. A final class can not be inheritable in Java.
8. Final is different than finally keyword which is used for Exception handling in Java.
9. Final should not be confused with finalize() method which is declared in Object class and called before an object is garbage collected by JVM.
10. All variables declared inside the Java interface are implicitly final.
11. Final and abstract are two opposite keywords and a final class can not be abstract in Java.
12. Final methods are bonded during compile time also called static binding.
13. Final variables which are not initialized during declaration are called a blank final variable and must be initialized in all constructors either explicitly or by calling this(). Failure to do so compiler will complain as "final variable (name) might not be initialized".
14. Making a class, method, or variable final in Java helps to improve performance because JVM gets an opportunity to make assumptions and optimization.
15. As per Java code convention, final variables are treated as constant and written in all Caps like
private final int COUNT=10;
16. Making a collection reference variable final means only reference can not be changed but you can add, remove or change object inside collection. For example:
private final List loans = new ArrayList();
loans.add(“home loan”); //valid
loans.add("personal loan"); //valid
loans = new Vector(); //not valid
That’s all on final in Java. We have seen what is final variable, the final method is, and the final class in Java and what do those mean. In Summary, whenever possible start using final in java it would result in better and faster code.
Java Tutorial you may like:
How to debug Java program in Eclipse
Thanks for reading this article so far, if you like this tutorial then please share it with your friends and colleagues. If you have any questions then please drop a comment.
Thanks for reading this article so far, if you like this tutorial then please share it with your friends and colleagues. If you have any questions then please drop a comment.
22 comments :
what's the difference between final and immutable?
Great blog!
Happy New Year!
@ Michee - Immutable approximately means the same as a final. Something that cant be changed. But, in Java, the term immutable is usually used along with String objects when we say Java String objects are Immutable.
Anand
Inheriting Java
Can final variables cloned along with object ?
Race conditions occurs when two thread operate on same object without proper synchronization and there operation interleaves on each other. Classical example of Race condition
Read more:
Making a class final is double edged sword, Some Java programmer argue that final class severely limits client's ability to inherit and extend while Some Java programmer are in opinion that final class, which is Immutable are best way to design robust System.It's trade-off. James Gosling suggest that Making a class final in Java for security reason e.g. String can be justified.
What is blank final variable in Java ? is it mandatory to initialize blank final variable in Constructor ? What is my class have multiple constructor, do I need to initialized blank final variable in all constructor or is there any alternative of that ?
A blank final, means that it's not initialized explicitly at it's declaration, can only be initialized in an initialization block or a constructor. A reference, declared final, doesn't make the object final.
Can you please suggest when to use final methods in Java, what are best practices around using final. I mean, I always get confused, should I make a class final or not, is there a rule book which we can follow? I hope my IDE suggest this but not so far.
> "Local final variable must be initializing during declaration."
This doesn't seem to be correct? For example, the following snippet compiles and runs okay under Java 1.7.0:
final int f; // Declare a final local variable
System.out.println(new java.util.Date()); // Do some other things
f = 5; // Initialize the final variable
System.out.println(f); // Use the final variable
If you then attempt to add a second assignment of the f variable, that *does* cause a compile-time error ("variable f might already have been assigned").
Can you please provide some examples of final methods from Java API? I am learning final keywords and want to know more about, how to use final with methods.
Can you provide the solution of this Q??
Q:As we know that if at any point some exception occurs in the code then an instance of Exception class (or its subclass) is thrown from that point. So my question is the instantiation comes into picture at runtime while checked exception are checked at compile time , therefore no instantiation is there, so how compiler comes to know that it is a compile time exception.
One Suggestion
You had cover everything about final here. One thing which as if i know is missing is about final instance variable,final static variable and final local variable (which you cover) missed is about the default values what we get for instance and static variable we will not get for final instance and final static variables , where we can initialize them in constructor and initialization block,final local variable will compile fine if we are not using it in code . Write something about this final keyword will get cover fully .
You can write to me at sudha.enigmatic@gmail.com
"You can not make a class immutable without making it final and hence final keyword is required to make a class immutable in java"
I don't agree with this statement, a very simple example would be:
- a final class can still be mutable if its fields are non-final and are not-private or have setters available for them
- similarly a non-final class can still be immutable if all its fields are final or are either private with no setters provided for them
One more thing to note about final variables in Java is that, till Java 7, you can not use a non final local variable inside anonymous class, but from Java 8 you can. JDK 8 introduced a concept called effective final, a variable is considered effective final if it is not modified after initialization in local block. What this means is you can now use local variable without final keyword inside anonymous class or lambda expression, provided they must be effectively final. In short, you can save some keystroke while declaring local final variables indented to be used by anonymous class. Here is an example of using effective final variable in Java 8 :
public class EffectiveFinalJava8 {
public static void main(String[] args) {
String nonFinal = "I am non final local variable";
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Using non-final local variable inside anonymous class in Java");
System.out.println("Value of non-final variable is : " + nonFinal);
// compile time error - must be final or effective final
// nonFinal = "Can I change non-final variable inside anonymous class";
}
};
}
}
For the last example, shouldn't it be "Loans.add(“home loan”);
Loans.add("personal loan");" ?
Final object references
The fields on any object accessed via a final reference are also guaranteed to be at least as up to date as when the constructor exits. This means that:
Values of final fields, including objects inside collections referred to by a final reference, can be safely read without synchronization.!
Nice article.. very much useful! Thank you! btw....Last example, it should be corrected as follows
Loans.add("home loan"); //valid
Loans.add("personal loan"); //valid
@Anonymous, good catch. That's right, the collection should be Loans there.
private final List Loans = new ArrayList();
list.add(“home loan”); //valid
list.add("personal loan"); //valid
loans = new Vector(); //not valid
In the above code snippet the name of the variable should be list instead of Loans... as per my knowledge
@Sehsh, you are right, that was typo, variable name is loans there not list. Corrected it now.
what about final Object with some member functions. If you make an Object of a non-final class final then How will it behave what sort of member function will it be able to invoked and what will it restrain remember the class is non-final that is regular class
The common perception is that declaring classes or methods final makes it easier for the compiler to inline method calls, but this perception is incorrect (or at the very least, greatly overstated).
{Taken from: } | https://javarevisited.blogspot.com/2011/12/final-variable-method-class-java.html | CC-MAIN-2022-27 | refinedweb | 2,166 | 52.9 |
Kyle wrote:> > I have a digital camera flash card that is locking up my machine (stock> redhat 7.2 w/2.4.9-13 kernel).> > I can mount the card, but as soon as I browse the filesystem, the> machine locks hard. I successfully copied the file system from the raw> device to a file and tried mounting it as:> > mount -o loop flash.img /mnt/flash> > and it still locks up the machine just as before. This makes me think> it has nothing to do with the USB reader or the SCSI emulation, etc.> > My guess is I have a corrupt filesystem on the flash that the filesystem> handler (vfat) is intolerant of (all my other flash cards work fine).> > This seems like a possible kernel bug to me. I'm not much of a kernel> expert but I have a copy of the offending image if anyone wants to or> can look at it. () Is there someone> that knows how to figure out if the driver can spit out a harmless> message about filesystem corruption rather than taking the whole kernel> down?> I don't know a thing about fat layout, but it appears that it uses alinked list of blocks, and if that list ends up pointing back ontoitself, the kernel goes into an infinite loop in several places chasingits way to the end of the list.The below patch fixed it for me, and I was able to mount and readyour filesystem image.Unless someone has a smarter fix, I'll send this to the kernelmaintainers in a week or two.--- linux-2.4.18-pre3/fs/fat/misc.c Fri Oct 12 13:48:42 2001+++ linux-akpm/fs/fat/misc.c Sat Jan 12 23:28:03 2002@@ -478,6 +478,8 @@ static int raw_scan_nonroot(struct super printk("raw_scan_nonroot: start=%d\n",start); #endif do {+ int old_start = start;+ for (count = 0; count < MSDOS_SB(sb)->cluster_size; count++) { if ((cluster = raw_scan_sector(sb,(start-2)* MSDOS_SB(sb)->cluster_size+MSDOS_SB(sb)->data_start+@@ -486,6 +488,11 @@ static int raw_scan_nonroot(struct super } if (!(start = fat_access(sb,start,-1))) { fat_fs_panic(sb,"FAT error");+ break;+ }+ if (start == old_start) {+ /* Prevent infinite loop on corrupt fs */+ fat_fs_panic(sb, "FAT loop"); break; } #ifdef DEBUG--- linux-2.4.18-pre3/fs/fat/inode.c Thu Nov 22 23:02:58 2001+++ linux-akpm/fs/fat/inode.c Sat Jan 12 23:37:44 2002@@ -392,12 +392,18 @@ static void fat_read_root(struct inode * MSDOS_I(inode)->i_start = sbi->root_cluster;;+ } } } } else {@@ -918,9 +924,15 @@ static void fat_fill_inode(struct inode #endif; }-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/2002/1/13/221 | CC-MAIN-2017-09 | refinedweb | 452 | 59.23 |
Why I Love Ruby
The Perl Journal January December's The Perl Journal, my fellow columnist brian d foy presented an introduction to Ruby. Well, he's not the only person who's been taking a look at this relative newcomer to the language scene, and I have to admit that I've been growing a lot more impressed with it recently.
This month, I'll take you on another tour of some of the things that attracted me to Ruby.
Perl 6, Now!
Let's start with a polemic: Ruby provides what Perl 6 promises, right now. If you're excited about Perl 6, you should be very, very excited about Ruby. You want a clean OO model? It's there. You want iterators? Got them, too. You want user-redefinable operators? Check. Even the recent discussion on perl6-language about list operatorsRuby's got them all. In fact, a lot of the things that you're waiting on Perl 6 for are already thereand in some cases, cleaner, too.
Let's start by looking at some code. A typical example of object-oriented Perl 5 is shown in Example 1(a).
Not too bad, right? Except, well, package is a bit of a silly name, since it's actually a class; and it would be nicer if we could take arguments to the method in a bit more normal way. And that hash is a bit disconcerting. In Example 1(b), you can see what Perl 6 makes of it.
Much betterexcept that, unfortunately, you can't actually run Perl 6 code through anything right now. That's always a bit of a problem when you need to get stuff done. So let's see it again, but this time in Ruby; see Example 1(c).
Much neater, no? Apart from the bits that are exactly the same, of course. But what? No dollar signs on the variables? Well, you can have them if you want, but they mean something different in Rubydollar signs make variables global. But hey, don't you need something to tell you what's an array or a hash or a scalar? Not in Rubyand actually, not in Perl 6 either, but for a different reason.
In Perl 6, variable prefixes are just a hint; Larry has said that you should consider them part of the name. You'll be able to dereference an array reference with $myvar[123] and a hash reference with $myvar{hello}, so things looking like scalars won't give you any indication of what's in them.
Ruby takes this approach furthervalues have types, variables do not. Since everything's an object in Ruby, it doesn't make sense to distinguish between "array variables" and "scalar variables"everything's an object, and variables hold references to objects. If you get bored with your variable that has an array in it, you can put a hash in it. Ruby doesn't care; it's just a different kind of object.
So what are those "@" signs about? They're the Ruby equivalent of Perl 6's $.method instance variables. The only slight difference is that we want to ensure that the age is an integer; so we call its to_i method to turn it into an integer. We can do this because, as we've mentioned, in Ruby, everything's an object.
Everything's an Object
They say that a foolish consistency is the hobgoblin of tiny minds, and Perl takes this approach to justify some of its more unusual quirks. But unfortunately, when it comes to programming languages, a lot of consistency isn't foolish at all.
And so with the advent of Perl 6, I found myself wishing for a little more consistency in the area of object-oriented programming. In fact, I really wanted to be able to treat everything as an object, so that I could be sure that it would respond to methods. Ruby gives me that. Let's spend a little time with Ruby's interactive shellanother neat featureand see what that really means:
irb(main):001:0> a = [1, 2, 3, 4] [1, 2, 3, 4] irb(main):002:0> a.class Array
So arrays are objects; that's pretty natural, as you will want to ask an array for its length, run maps and greps on it, and so on.
irb(main):003:0> a.reverse [4, 3, 2, 1]
But what about the individual elements in the array?
irb(main):004:0> a[1].class Fixnum
Mmm, so numbers are just Fixnum objects. But wait, what's a Fixnum?
irb(main):005:0> a[1].class.class Class
Ah, so even classes are objects; they're just objects of class Class. Fair enough. So this shouldn't be a surprise either:
irb(main):006:0> a[1].class.class.class Class
It's objects all the way down!
Naturally, this allows pretty interesting introspection possibilities. For instance, we can ask an Array what it can do for us:
irb(main):007:0> a.public_methods ["sort!", "clone", "&", "reverse", ...]
And of course, this list of methods is itself an Array, so we can tidy it up a bit:
irb(main):009:0> a.public_methods.sort ["&", "*", "+", "-", "<<", "<=>", "==", "===", "=~", "[]", "[]=", "__id__", "__send__", "assoc", "at", "class", "clear", "clone", "collect", "collect!", "compact", "compact!", "concat", "delete", "delete_at", "delete_if", "detect", "display", "dup", "each", ...]
Notice that since everything's an object, almost all operators are just methods on objects. One of those operator methods, ===, is particularly interesting; Ruby calls this the "Case equality operator," and it's very similar to a concept you'll see bandied around in Perl 6...
Making the Switch
Perl 6 is touted to have an impressive new syntax for switch/case statements called "given statements." With a given block, you can pretty much compare anything to anything else using the =~ "smart match" operator and Perl will do the right thing. Use when and a string, and it will test whether the given argument is string equivalent; use when and a regular expression, and it will test whether the argument matches the regex; use when and a class name, and it will test whether the argument is an object of that class. Really neat, huh?
Now I want to make you wonder where that idea came from.
Here's a piece of Perl 6 code taken directly from Exegesis 4:
my sub get_data ($data) { given $data { when /^\d+$/ { return %var{""} = $_ } when 'previous' { return %var{""} // fail NoData } when %var { return %var{""} = %var{$_} } default { die Err::BadData : msg=>"Don't understand $_" } } }
And translated into Ruby:
def get_data (data) case data when /^\d+$/ ; return var[""] = data when 'previous' ; return var[""] || (fail No Data) when var ; return var[""] = var[data] else raise Err::BadData, "Don't understand #{data}" end end
Of course, this doesn't quite do what we want because Ruby's default case comparison operator for hashes just checks to see whether two things are both the same hash. The Perl 6ish smart match operator checks through the hash to see whether data is an existing hash key. This code looks very much like the Perl 6 version, but it's not the same.
And we were doing so well.
Everything is Overridable
Not to worry. Not only is everything an object in Ruby, (almost) everything can be overriden, and the Hash class's === method is no exception. So all we need to do is write our own === method that tests to see if its argument is a valid hash key:
class Hash def === (x) return has_key?(x) end end
And presto, our case statement now does the right thing. The has_key? method on a Hash object checks to see whether the hash has a given key. But wait, where's the Hash object? Because we're defining an object method, the receiver for the method is implicitly defined as self. And it just so happens that self is the default receiver for any other methods we call inside our definition, so has_key?(x) is equivalent to self.has_key?(x). Now it all makes sense.
Of course, it's a little dangerous to redefine Hash#=== globally, in case other things depend on it. Maybe it would be better to create a variant of Hash by subclassing it:
class MyHash < Hash def === (x) return has_key?(x) end end var = MyHash[...];
As you can see, this means that we can define === methods for our own classes, and they'll also do the right thing inside of when statements.
It also means that we can redefine some of the built-in operators to do whatever we want. For instance, Ruby doesn't support Perl-style string-to-number conversion:
irb(main):001:0> 1 + "0.345" TypeError: String can't be coerced into Fixnum from (irb):1:in '+' from (irb):1 irb(main):002:0>
And this is one of the things people like about Perl; "scalar" is the basic type, and strings are converted to numbers and back again when context allows for it. Ruby can't do that. Bah, Ruby must really suck, then.
Now we are going to do something very unRubyish.
class Fixnum alias old_plus + def + (x) old_plus(x.to_f) end end irb(main):003:0> 1 + "2" 3.0
Ruby lovers would hate me for this. But at least it's possible.
First, we copy the old addition method out of the way because we really don't want to have to redefine addition without it. Now we define our own addition operator, which converts its argument to a float before calling the old method. Why is the addition operator unary? Well, remember that 1 + "2" is nothing more than syntactic sugar, and what we're actually calling is a method:
1.+("2")
and the receiver of this method is our self, 1. It's consistent, is it not?
You Want Iterators?
There are a set of people on perl6-language who become amazingly vocal when anyone mentions iterators. I don't know why this is. Iterators aren't amazingly innovative or particularly interesting, nor do they solve all known programming ills. But hey, if you really get fired up about iterators, Ruby has those, too.
The most boring iterator Ruby supplies is Array#each. (# is not Ruby syntaxit's just a convention to show that this is an object method on an Array object, not an Array class method.) This is equivalent to Perl's for(@array):
[1,2,3,4].each { |x| print "The square of #{ x } is #{ x * x }\n" }
By the way, here's Ruby's block syntax: We're passing an anonymous block to each, and it's being called back with each element of the array. The block takes an argument, and we define the arguments inside parallel bars. Some people don't like the { |x| ... } syntax. If that includes you, you have two choices: the ever-beautiful sub{ my $x = shift; ... }, or waiting until Perl 6. See? { |x| ... } isn't that bad after all.
You can call each on ranges, too:
1..4.each { |x| print "The square of #{ x } is #{ x * x }\n" }
Or maybe you prefer the idea of going from 1 up to 4, doing something for every number you see:
1.upto(4) { |x| print "The square of #{ x } is #{ x * x }\n" }
Or even:
100.times { |x| puts "I must not talk in class" }
(puts is just print ..., "\n", after all.)
Another frequent request is for some kind of array iterator that also keeps track of which element number in the array you're visiting. Well, guess what? Ruby's got that, too.
irb(main):001:0> a = [ "Spring", "Summer", "Fall", "Winter" ] ["Spring", "Summer", "Fall", "Winter"] irb(main):002:0> a.each_with_index { |elem, index| puts "Season #{ index } is #{ elem }" } Season 0 is Spring Season 1 is Summer Season 2 is Fall Season 3 is Winter ["Spring", "Summer", "Fall", "Winter']
Oh yesthese iterators return the original object, so that they can be chained, just in case you wanted to do something like that.
Those were the boring iterators. What about more interesting uses? I saw an interesting Perl idiom the other day for reading key=value lists out of a configuration file into a hash. Here it is:
open(EMAIL, "<$EMAIL_FILE") or die "Failed to open $EMAIL_FILE"; my %hash = map {chomp; split /=/} (<EMAIL>);
Of course, how does this translate to Ruby? There was quite a long thread about this on comp.lang.ruby, and I picked out three translations that impressed me for different reasonsof course, there's more than one way to do it. Here's the first:
h = [] File.open('fred.ini').read.scan(/(\w+)=(\w+)/) { h[$1] = $2 }
We open a file, read the whole lot into a string, and then iterate on a regular expressioneach time the regular expression matches, a block is called, and this associates the hash key with its element. Nice.
Established Perl programmers will see this and jump up and down about depending on the open call never failing. Good thinking, but Ruby has decent structured exceptions; if the open fails, an exception will be raised and hopefully caught somewhere else in your program.
Now that method is cute, but it reads the whole file into a single string. This can be memory hungry if you have 120-MB configuration files. Of course, if you do, you probably have other problems, but people will be pedantic. It'd be much better to read the file one line at a time, right? No problem.
File.foreach("fred.ini") { |l| s = l.chomp.split("="); h[s[0]] = s[1] }
This is a more literal translation of what the Perl code is doing. Notice that Ruby's chomp returns the chomped string, without modifying the original. If you want to modify the original, you need chomp!methods ending with ! are a warning that something is going to happen to the original object.
But even this method lacks the sweetness of the Perl idiom, which builds the whole hash in one go. Okay. In Ruby, you can construct a hash like this:
h = Hash[ "key" => "value", "key2" => "value2"];
So if we could read in our file, split it into keys and values, and then dump it into a hash constructor like that, we'd have it. Here's our first attempt:
h = Hash[File.open("fred.ini").read.split(/=|\n/)]
That's close, but it has a bit of a problem. Because objects can be hash keys in Ruby, what we've actually done is create a hash with an Array as the key and no value. Oops. To get around this, we need to invoke a bit of Perl 6 magic:
h = Hash[*File.open("fred.ini").read.split(/=|\n/)]
There we go, our old friend unary * turns the Array object into a proper list, and all is well.
So there are built-in iterators. But what if you want to define your own? All methods in Ruby can optionally take a block, and the keyword yield calls back the block. So, assuming we've already defined Array#randomize to put an array in random order, we can create a random iterator like so:
class Array def random_each self.randomize.each { |x| yield x } end end
What does this mean? First, get the array in random order, and then for each element of that array, call back the block we were given, passing in the element. Simple, hmm?
Messing with the Class Model
Let's move on to some less simple stuff, then. In a recent perl6-language post, the eminent Piers Cawley wondered whether or not it would be possible to have anonymous classes defined at run time via Class.new or some such. Man, that would be cool. I'd love to see a language that could do that. You can see this coming, can't you?
c = Class.new; c.class_eval { def initialize puts "Just another Ruby hacker" end } o = c.new;
First, we create a new class, c, at run time, in an object. Now, in the context of that class, we want to set up an initializer; Object#initialize is called as part of Object#new. So now our class has a decent new method that does something; we can instantiate new objects of our anonymous class. But they can't do very much at the moment. Now, we could add new methods to the class with class_eval as before, but that's kinda boring. We've seen that. How about adding individual methods to the object itself?
class << o def honk raise "Honk! Honk!" end end o.honk;
This doesn't do anything to our class c; it just specializes o with what's called a singleton methodo and only o gets a honk method.
What about AUTOLOAD? This is a lovely feature of Perl that allows you to trap calls to unresolved subroutines. Ruby calls this method_missing:
class << o def method_missing (method, *args) puts "I don't know how to #{ method } (with arguments #{ args })"; end end
And notice there the Perl 6 unary star again, collecting the remaining arguments into an array.
There are many other tricks we can play if we do evil things such as override Object#new or play about with the inheritance tree by messing with Object#ancestors. But time is short, and I'm sure you're dying to move onto the last bit: What I hate about Ruby.
Ruby Gripes
Ruby is a comparitively young language, which is a mixed blessing. It's been developed at the right time to learn from the mistakes of other languagestry explaining why Python's array length operator len is a built-in function and not a method, and you'll appreciate the consistency of Ruby's OO paradigm. But, even though it's coming up to its 10th birthday, it's also still finding its way around, and the changes between minor releases are sometimes quite significant.
So what are the things I don't think Ruby has got right quite yet? First, I really, really, really miss using curly braces for my subroutine definitions. You can write subroutines in one line using Ruby; it's not as white-space significant as people make out:
def foo; puts "Hi there!"; end
but braces for blocks just seems so much neater.
I also miss default values for blocks; there is a special variable $_ in Ruby, but it contains the last line read in from the terminal or a file. So you really do have to say
array.each{|x| print x} because array.each { print }
won't do what you want.
There are a few other odd things: For instance, variables have to be assigned before they're used, which is probably a good thing but can confuse me at times. I also find myself tripping over Ruby's for syntax; Ruby supports statements modifying if, unless, while, and until, but not for, as for is just syntactic sugar for stuff.each anyway.
But there is one major problem I have with Ruby, and that's basically the reason why I haven't switched over to it wholesale: CPAN. Perhaps Perl's greatest asset is the hundreds and thousands of modules already available. Ruby has a project similar to the CPAN, the Ruby Application Archive. But as the language is still quite young, it hasn't had the time to grow a massive collection of useful code, and the RAA itself has some flawsit's a collection of links, rather than a mirrored collection of material, and it can be pretty hard to find stuff on it at times.
This is, I'm sure, something that will be sorted out over time, but I have to sadly admit that Ruby's not quite there yet. Of course, Perl 6 will also need to spend time developing a large collection of useful modules; so at least Ruby does have a massive head startit has a real, existing interpreter that you can download, play with, and use for real code today. And if you're at all interested in Perl 6, I heartily encourage you to do so.
Finally, thanks to David Black and the other members of #ruby-lang who helped review this article.
TPJ | http://www.drdobbs.com/web-development/why-i-love-ruby/184415977 | CC-MAIN-2014-49 | refinedweb | 3,384 | 72.36 |
This,.
. All Rights Reserved.
Figures and Listings Chapter 1 Objects. Mid. .. All Rights Reserved. .
Objective-C is designed to give C full object-oriented programming capabilities. and provides a foundation for learning about the second component. which introduces the associative references feature (see “Associative References” (page 83)).0 of the Objective-C language (available in in Mac OS X v10. it doesn’t have to be an extensive acquaintance. Its additions to C are mostly based on Smalltalk. Who Should Read This Document 2010-07-13 | © 2010 Apple Inc.6. it assumes some prior acquaintance with that language. Objective-C is defined as a small but powerful set of extensions to the standard ANSI C language. described in Xcode Workspace Guide and Interface Builder respectively. Important: This document describes the version of the Objective-C language released in Mac OS X v10. and to do so in a simple and straightforward way. Because this isn’t a document about C. 9 .INTRODUCTION Introduction to The Objective-C Programming Language The Objective-C language is a simple computer language designed to enable sophisticated object-oriented programming. The two main development tools you use are Xcode and Interface Builder. You can start to learn more about Cocoa by reading Getting Started with Cocoa. not on the C language itself. read Object Oriented Programming and the Objective-C Programming Language 1. It fully describes the Objective-C language. Object-oriented programming in Objective-C is sufficiently different from procedural programming in ANSI C that you won’t be hampered if you’re not an experienced C programmer. the Mac OS X Objective-C application frameworks—collectively known as Cocoa.0. To learn about version 1.4 and earlier). one of the first object-oriented programming languages. All Rights Reserved. It concentrates on the Objective-C extensions to C. Objective-C Runtime Programming Guide. Most object-oriented development environments consist of several parts: ■ ■ ■ ■ An object-oriented programming language A library of objects A suite of development tools A runtime environment This document is about the first component of the development environment—the programming language. The runtime environment is described in a separate document..
but that you can choose the class name and category name. the syntax: @interfaceClassName(CategoryName) means that @interface and the two parentheses are required. just as it recognizes files containing only standard C syntax by filename extension .m. and the Objective-C compiler works for C. Other issues when using Objective-C with C++ are covered in “Using C++ With Objective-C” (page 111). and other programming elements. Objective-C syntax is a superset of GNU C/C++ syntax.mm. The following chapters cover all the features Objective-C adds to standard C. methods. Conventions Where this document discusses functions. the compiler recognizes C++ files that use Objective-C by the extension . For example. All Rights Reserved. The compiler recognizes Objective-C source files by the filename extension ..INTRODUCTION Introduction to The Objective-C Programming Language Organization of This Document This document is divided into several chapters and one appendix. C++ and Objective-C source code.c. Computer voice denotes words or characters that are to be taken literally (typed as they appear). it makes special use of computer voice and italic fonts. The appendix contains reference material that might be useful for understanding the language: ■ “Language Summary” (page 117) lists and briefly comments on all of the Objective-C extensions to the C language. . Similarly. ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ “Objects. Classes. Italic denotes words that represent something else or can be varied. 10 Organization of This Document 2010-07-13 | © 2010 Apple Inc.
ellipsis points indicates the parts. You should also consider reading it if you have used other object-oriented development environments such as C++ and Java. 11 . .) Memory Management Programming Guide describes the reference counting system used by Cocoa. that have been omitted: ... since those have many different expectations and conventions from Objective-C. For example. you can add classes or methods. (Not available on iOS—you cannot access this document through the iPhone Dev Center. It spells out some of the implications of object-oriented design and gives you a flavor of what writing an object-oriented program is really like. Object-Oriented Programming with Objective-C is designed to help you become familiar with object-oriented development from the perspective of an Objective-C developer. See Also If you have never used object-oriented programming to create applications before. All Rights Reserved. often substantial parts. Runtime Objective-C Runtime Programming Guide describes aspects of the Objective-C runtime and how you can use it. Objective-C Release Notes describes some of the changes in the Objective-C runtime in the latest release of Mac OS X.(void)encodeWithCoder:(NSCoder *)coder { [super encodeWithCoder:coder]. Your programs can use these interfaces to interact with the Objective-C runtime system. ■ See Also 2010-07-13 | © 2010 Apple Inc. or obtain a list of all class definitions for loaded classes. Objective-C Runtime Reference describes the data structures and functions of the Objective-C runtime support library.INTRODUCTION Introduction to The Objective-C Programming Language Where example code is shown. } The conventions used in the reference appendix are described in that appendix. Memory Management Objective-C supports two environments for memory management: automatic garbage collection and reference counting: ■ Garbage Collection Programming Guide describes the garbage collection system used by Cocoa. you should read Object-Oriented Programming with Objective-C.
INTRODUCTION Introduction to The Objective-C Programming Language 12 See Also 2010-07-13 | © 2010 Apple Inc. All Rights Reserved. .
13 . Moreover. and messaging as used and implemented by the Objective-C language. In Objective-C. Runtime The Objective-C language defers as many decisions as it can from compile time and link time to runtime. the data they affect are its instance variables (in other environments they may be referred to as ivars or member variables). though. Objects As the name implies. an object bundles a data structure (instance variables) and a group of procedures (methods) into a self-contained programming unit. there has to be a method to supply the information. In essence. see “The Scope of Instance Variables” (page 40)). however. object-oriented programs are built around objects. For others to find out something about an object. To understand more about the functionality it offers. an object’s instance variables are internal to the object. an object hides both its instance variables and its method implementations. it’s what makes the language work. Classes. Objective-C provides a data type to identify an object variable without specifying a particular class of the object—this allows for dynamic typing.CHAPTER 1 Objects. it dynamically performs operations such as creating objects and determining what method to invoke. classes. This means that the language requires not just a compiler. An object associates data with the particular operations that can use or affect that data. It also introduces the Objective-C runtime. you don’t need to interact with the runtime directly. these operations are known as the object’s methods. hiding them from the rest of the program. and Messaging This chapter describes the fundamentals of objects. For example. an object sees only the methods that were designed for it. it can’t mistakenly perform methods intended for other types of objects. Runtime 2010-07-13 | © 2010 Apple Inc. Just as a C function protects its local variables. Object Basics An object associates data with the particular operations that can use or affect that data. a Rectangle would have methods that reveal its size and its position. In Objective-C. generally. see Objective-C Runtime Programming Guide. you get access to an object’s state only through the object’s methods (you can specify whether subclasses or other objects can access instance variables directly by using scope directives. All Rights Reserved. but also a runtime system to execute the compiled code. Whenever possible. Typically. The runtime system acts as a kind of operating system for the Objective-C language.
just by asking the object. . Classes. Classes are particular kinds of objects. Objects with the same behavior (methods) and the same kinds of data (instance variables) are members of the same class. All objects thus have an isa variable that tells them of what class they are an instance. the runtime system can find the exact class that an object belongs to. an id with a value of 0. and the class name can serve as a type name. and Messaging id In Objective-C.) Dynamic typing in Objective-C serves as the foundation for dynamic binding. It’s also possible to give the compiler information about the class of an object by statically typing it in source code using the class name. id anObject. and can be used for both instances of a class and class objects themselves. int remains the default type. See “Class Types” (page 26) and “Enabling Static Behavior” (page 91). discussed later. For the object-oriented constructs of Objective-C. for example. Whenever it needs to. see Objective-C Runtime Programming Guide. or discover the name of its superclass. to find this information at runtime. and the other basic types of Objective-C are defined in the header file objc/objc. object identifiers are a distinct data type: id. The compiler records information about class definitions in data structures for the runtime system to use. The functions of the runtime system use isa. 14 Objects 2010-07-13 | © 2010 Apple Inc. the isa variable is frequently referred to as the “isa pointer. you can. Since the id type designator can’t supply this information to the compiler. nil. such as function return values. } *id. it yields no information about an object. such as method return values.) The keyword nil is defined as a null object. determine whether an object implements a particular method.h. Objects are thus dynamically typed at runtime. The isa variable also enables objects to perform introspection—to find out about themselves (or other objects). id replaces int as the default data type. except that it is an object. a program typically needs to find more specific information about the objects it contains. id. id is defined as pointer to an object data structure: typedef struct objc_object { Class isa. By itself. each object has to be able to supply it at runtime. Object classes are discussed in more detail under “Classes” (page 23). Since the Class type is itself defined as a pointer: typedef struct objc_class *Class. All Rights Reserved. The isa instance variable identifies the object’s class—what kind of object it is.CHAPTER 1 Objects. (For strictly C constructs.” Dynamic Typing The id type is completely nonrestrictive. Using the runtime system. At some point. (To learn more about the runtime. This is the general type for any kind of object regardless of class.
including how you can nest message expressions. It also discusses the “visibility” of an object’s instance variables.” as is normal for any line of code in C. and Messaging Memory Management In any program. [myRectangle setWidth:20. the runtime system selects the appropriate method from the receiver’s repertoire and invokes it. Objective-C offers two environments for memory management that allow you to meet these goals: ■ Reference counting. Classes.” Garbage collection is described in Garbage Collection Programming Guide.CHAPTER 1 Objects. where you are ultimately responsible for determining the lifetime of objects. All Rights Reserved.” A message with a single argument affixes a colon (:) to the name and puts the argument right after the colon. or “arguments. you send it a message telling it to apply a method. where you pass responsibility for determining the lifetime of objects to an automatic “collector. When a message is sent. Methods can also take parameters. method names in messages are often referred to as selectors. For example. The method name in a message serves to “select” a method implementation. ■ Garbage collection. Reference counting is described in Memory Management Programming Guide. The message is followed by a “. Message Syntax To get an object to do something. which causes the rectangle to display itself: [myRectangle display]. the message is simply the name of a method and any arguments that are passed to it. this message tells the myRectangle object to perform its display method.0]. (Not available on iOS—you cannot access this document through the iPhone Dev Center. It is also important to ensure that you do not deallocate objects while they’re still being used. and the concepts of polymorphism and dynamic binding. Object Messaging 2010-07-13 | © 2010 Apple Inc. In Objective-C. In source code. For this reason. 15 . message expressions are enclosed in brackets: [receiver message] The receiver is an object. it is important to ensure that objects are deallocated when they are no longer needed—otherwise your application’s memory footprint becomes larger than necessary. and the message tells it what to do.) Object Messaging This section explains the syntax of sending messages.
For all intents and purposes. Objective-C's method names are interleaved with the arguments such that the method’s name naturally describes the arguments expected by the method. so the method is named setOriginX:y:. Extra arguments are separated by commas after the end of the method name. b. can be in a different order. One message expression can be nested inside another. can have default values. BOOL isFilled. the second argument is effectively unlabeled and it is difficult to determine the kind or purpose of the method’s arguments. however. memberOne.0 y: 50. This is not the case with Objective-C. This is typically used in conjunction with the declared properties feature (see “Declared Properties” (page 67)). The imaginary message below tells the myRectangle object to set its origin to the coordinates (30. such as return type or parameter types. nor can their order be varied. All Rights Reserved.0]. or NO if it’s drawn in outline form only. and is described in “Dot Syntax” (page 19).CHAPTER 1 Objects. methods can return values. It has two colons as it takes two arguments. though they’re somewhat rare. 16 Object Messaging 2010-07-13 | © 2010 Apple Inc.0]. the color of one rectangle is set to the color of another: [myRectangle setPrimaryColor:[otherRect primaryColor]]. // This is a bad example of multiple arguments This particular method does not interleave the method name with the arguments and. the commas aren’t considered part of the name. memberTwo. the imaginary makeGroup: method is passed one required argument (group) and three that are optional: [receiver makeGroup:group. Objective-C also provides a dot (. (Unlike colons. 50. NeatMode=SuperNeat. can possibly have additional named arguments. thus. // This is a good example of multiple arguments A selector name includes all the parts of the name. and Messaging For methods with multiple arguments. including the colons. . the Rectangle class could instead implement a setOrigin:: which would be invoked as follows: [myRectangle setOrigin:30.0 :50. The selector name does not. memberThree]. Important: The sub-parts of the method name—of the selector—are not optional. an Objective-C method declaration is simply a C function that prepends two additional arguments (see Messaging in the Objective-C Runtime Programming Guide).) operator that offers a compact and convenient syntax for invoking an object’s accessor methods. Note that a variable and a method can have the same name.0): [myRectangle setOriginX: 30. isFilled = [myRectangle isFilled].) In the following example. This is different from the named or keyword arguments available in a language like Python: def func(a.0. “Named arguments” and “keyword arguments” often carry the implication that the arguments to a method can vary at runtime. In principle. Classes. Here. Like standard C functions. The following example sets the variable isFilled to YES if myRectangle is drawn as a solid rectangle. Methods that take a variable number of arguments are also possible. include anything else. Thing=DefaultThing): pass where Thing (and NeatMode) might be omitted or might have different values when called.
as defined by the Mac OS X ABI Function Call Guide to be returned in registers.. for example: Person *motherInLaw = [[aPerson spouse] mother]. 17 . a float. Every method assumes the receiver and its instance variables. For example. a message sent to nil returns nil. Other struct data types will not be filled with zeros. void. It also supports the way object-oriented programmers think about objects and messages. or any integer scalar of size less than or equal to sizeof(void*). and Messaging Sending Messages to nil In Objective-C. then mother is sent to nil and the method returns nil. a long double. then a message sent to nil returns 0 (nil). or a long long. On Mac OS X v10.4 and earlier. any integer scalar of size less than or equal to sizeof(void*).0) { // implementation continues.. id anObjectMaybeNil = nil. they don’t need to bring the receiver to itself. If the method returns a struct. a message to nil also is valid. without having to declare them as arguments. as long as the message returns an object. if it does. then a message sent to nil returns 0. yet it can find the primary color for otherRect and return it.CHAPTER 1 Objects. ■ ■ The following code fragment illustrates valid use of sending a message to nil. This convention simplifies Objective-C source code. If the method returns anything other than the aforementioned value types the return value of a message sent to nil is undefined. You don’t need to pass them to the method as arguments. If the message sent to nil returns anything other than the aforementioned value types (for example. Object Messaging 2010-07-13 | © 2010 Apple Inc. any pointer type.0 for every field in the data structure. The Receiver’s Instance Variables A method has automatic access to the receiving object’s instance variables. or any vector type) the return value is undefined. a double. Classes. or any integer scalar of size less than or equal to sizeof(void*). } Note: The behavior of sending messages to nil changed slightly with Mac OS X v10. All Rights Reserved. If aPerson’s spouse is nil. it is valid to send a message to nil—it simply has no effect at runtime. any floating-point type. then a message sent to nil returns 0. if it returns any struct type. Message arguments bring information from the outside to the receiver. The value returned from a message to nil may also be valid: ■ If the method returns an object. the primaryColor method illustrated above takes no arguments.5. There are several patterns in Cocoa that take advantage of this fact. Messages are sent to receivers much as letters are delivered to your home. any pointer type. // this is valid if ([anObjectMaybeNil methodThatReturnsADouble] == 0. ■ If the method returns any pointer type. You should therefore not rely on the return value of messages sent to nil unless the method’s return type is an object.
each kind of object sent a display message could display itself in a unique way. In particular. not when the code is compiled. the exact method that’s invoked to respond to a message can only be determined at runtime. by other programmers working on other projects.CHAPTER 1 Objects. it permits you to write code that might apply to any number of different kinds of objects. messages in Objective-C appear in the same syntactic positions as function calls in standard C. it must send a message to the object asking it to reveal the contents of the variable. receivers can be decided “on the fly” and can be made dependent on external factors such as user actions. referred to as polymorphism. even if another object has a method with the same name. Since each object can have its own version of a method. but by varying just the object that receives the message. without you having to choose at the time you write the code what kinds of objects they might be. This means that two objects can respond differently to the same message. see Messaging in the Objective-C Runtime Programming Guide. When a message is sent. Together with dynamic binding. If it requires information about a variable stored in another object. They might even be objects that will be developed later. but a message and a receiving object aren’t united until the program is running and the message is sent. For example. messages behave differently than function calls. an object can be operated on by only those methods that were defined for it. The precise method that a message invokes depends on the receiver. This is information the receiver is able to reveal at runtime when it receives a message (dynamic typing). . This can be done as the program runs. but it’s not available from the type declarations found in source code. Therefore. it would have to know what kind of object the receiver is—what class it belongs to. (For more on this routine. a runtime messaging routine looks at the receiver and at the method named in the message. It locates the receiver’s implementation of a method matching the name. Dynamic Binding A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code. For the compiler to find the right method implementation for a message. Classes. See “Defining a Class” (page 35) for more information on referring to instance variables. “calls” the method. But. Different receivers may have different method implementations for the same method name (polymorphism). not by varying the message itself. All Rights Reserved. any object that has a display method is a potential receiver. The selection of a method implementation happens at runtime. because methods “belong to” an object. a program can achieve a variety of results. If you write code that sends a display message to an id variable. 18 Object Messaging 2010-07-13 | © 2010 Apple Inc. and Messaging A method has automatic access only to the receiver’s instance variables. and passes it a pointer to the receiver’s instance variables. A Circle and a Rectangle would respond differently to identical instructions to track the cursor. The primaryColor and isFilled methods shown above are used for just this purpose. Polymorphism As the examples above illustrate.) This dynamic binding of methods to messages works hand-in-hand with polymorphism to give object-oriented programming much of its flexibility and power. This feature. It can’t confuse them with methods defined for other kinds of object. plays a significant role in the design of object-oriented programs.
) operator that offers a compact and convenient syntax you can use as an alternative to square bracket notation ([]s) to invoke accessor methods. and Paste. See Dynamic Method Resolution in the Objective-C Runtime Programming Guide for more details. It is particularly useful when you want to access or modify a property that is a property of another object (that is a property of another object. for example. 19 . The message goes to whatever object controls the current selection.) operator. An object that displays text would react to a copy message differently from an object that displays scanned images. General Use You can read and write properties using the dot (. All Rights Reserved. Copy. Dynamic Method Resolution You can provide implementations of class and instance methods at runtime using dynamic method resolution. Listing 1-1 Accessing properties using the dot syntax Graphic *graphic = [[Graphic alloc] init]. printf("myInstance value: %d". The dot syntax is purely “syntactic sugar”—it is transformed by the compiler into invocation of accessor methods (so you are not actually accessing an instance variable directly). it doesn’t even have to enumerate the possibilities. Objective-C takes dynamic binding one step further and allows even the message that’s sent (the method selector) to be a variable that’s determined at runtime.value). Dot Syntax Objective-C provides a dot (. The code that sends the message doesn’t have to be concerned with them. and so on).CHAPTER 1 Objects. as illustrated in the following example. An object that represents a set of shapes would respond differently from a Rectangle. Using the Dot Syntax Overview You can use the dot syntax to invoke accessor methods using the same pattern as accessing structure elements as illustrated in the following example: myInstance. The code example above is exactly equivalent to the following: [myInstance setValue:10]. printf("myInstance value: %d". Classes. and Messaging When executing code based upon the Application Kit. Since messages don’t select methods (methods aren’t bound to messages) until runtime. This is discussed in the section Messaging in the Objective-C Runtime Programming Guide. Each application can invent its own objects that respond in their own way to copy messages. these differences are isolated in the methods that respond to the message.value = 10. myInstance. users determine which objects receive messages from menu commands like Cut. Object Messaging 2010-07-13 | © 2010 Apple Inc. [myInstance value]).
) Accessing a property property calls the get method associated with the property (by default. the dot syntax therefore preserves encapsulation—you are not accessing an instance variable directly.0).0. [data setLength:[data length] / 4]. data. you could update the length property of an instance of NSMutableData using compound assignments: NSMutableData *data = [NSMutableData dataWithLength:1024]. and Messaging NSColor *color = graphic.length /= 4.color.length += 1024. the meaning of compound assignments is well-defined. 10. 120. Consider the following code fragment: id y. data.0. if ([graphic isTextHidden] != YES) { [graphic setText:@"Hello"].bounds = NSMakeRect(10. BOOL hidden = graphic.length. which is equivalent to: [data setLength:[data length] + 1024]. NSColor *color = [graphic color]. BOOL hidden = [graphic hidden].0.0. 10. 20 Object Messaging 2010-07-13 | © 2010 Apple Inc.text = @"Hello". For example. } graphic. } [graphic setBounds:NSMakeRect(10. Despite appearances to the contrary. CGFloat xLoc = [graphic xLoc]. if (graphic. setProperty:). 20. 120. There is one case where properties cannot be used. CGFloat xLoc = graphic.0. property) and setting it calls the set method associated with the property (by default.textHidden != YES) { graphic. All Rights Reserved. int textCharacterLength = graphic. (@"Hello" is a constant NSString object—see “Compiler Directives” (page 118).xLoc.length *= 2. Classes. data. You can change the methods that are invoked by using the Declared Properties feature (see “Declared Properties” (page 67)). The following statements compile to exactly the same code as the statements shown in Listing 1-1 (page 19).0. which will fail at runtime. but use square bracket syntax: Listing 1-2 Accessing properties using bracket syntax Graphic *graphic = [[Graphic alloc] init]. [data setLength:[data length] * 2]. An advantage of the dot syntax is that the compiler can signal an error when it detects a write to a read-only property. For properties of the appropriate C language type.0)]. int textCharacterLength = [[graphic text] length]. 20.CHAPTER 1 Objects.text. whereas at best it can only generate an undeclared method warning that you invoked a non-existent setProperty: method.hidden. .
In the following example.name = @"Oxford Road". 21 . // the path contains a C struct // will crash if window is nil or -contentView returns nil y = window.bounds.. x = [[[person address] street] name]. Since the dot syntax simply invokes methods. All Rights Reserved. passing @"New Name" as the argument. the statement is treated as an undeclared property error. [[[person address] street] setName: @"Oxford Road"].address. the result is the same as sending the equivalent message to nil. otherwise you get a compiler warning. and Messaging x = y.aProperty. // an example of using a setter. Invokes the setName: method on anObject. Classes. person.street. If there are multiple declarations of a z property. // z is an undeclared property Note that y is untyped and the z property is undeclared.name = @"New Name".name. as long as they all have the same type (such as BOOL) then it is legal. the set accessor method for the age property is not invoked: age = 10.age = 10. Since this is ambiguous. self If you want to access a property of self using accessor methods.z. The type of the property aProperty and the type of aVariable must be compatible. you must explicitly call out self as illustrated in this example: self. y = [[window contentView] bounds].CHAPTER 1 Objects. the following pairs are all equivalent: // each member of the path is an object x = person.street. Invokes the aProperty method and assigns the return value to aVariable. For example.address.origin.. you access the instance variable directly. then it is not ambiguous if there's only one declaration of a z property in the current compilation unit. nil Values If a nil value is encountered during property traversal. code using the dot syntax performs exactly the same as code written directly using the accessor methods. One source of ambiguity would also arise from one of them being declared readonly. Usage Summary aVariable = anObject. There are several ways in which this could be interpreted.contentView.. If you do not use self.y. If z is declared. no additional thread dependencies are introduced as a result of its use. Performance and Threading The dot syntax generates code equivalent to the standard method invocation syntax.y.. anObject.origin. Object Messaging 2010-07-13 | © 2010 Apple Inc. As a result.
/* property declaration */ @property(readonly) NSInteger readonlyProperty. Because the setter method is present.(BOOL) setFooIfYouCan: (MyClass *)newFoo. 22 Object Messaging 2010-07-13 | © 2010 Apple Inc. /* method declaration */ . Generates a compiler warning that setFooIfYouCan: does not appear to be a setter method because it does not return (void). NSInteger i = 10.CHAPTER 1 Objects. but simply adding a setter for a property does not imply readwrite.x. /* code fragment */ anObject. All Rights Reserved. flag = aView.integerProperty and anotherObject. anObject. Assigns 11 to both anObject.integerProperty = anotherObject. Invokes lockFocusIfCanDraw and assigns the return value to flag.x structure element of the NSRect returned by bounds. Since the property is declared readonly. it will work at runtime.readonlyProperty = 5.(void) setReadonlyProperty: (NSInteger)newValue. xOrigin = aView. Incorrect Use The following patterns are strongly discouraged.floatProperty. if the property name does not exist.bounds. anObject.lockFocusIfCanDraw.retain.fooIfYouCan = myInstance. /* method declaration */ .origin. this code generates a compiler warning (warning: assignment to readonly property 'readonlyProperty'). The pre-evaluated result is coerced as required at each point of assignment. or if setName: returns anything but void.). /* code fragment */ self. Classes. Invokes the bounds method and assigns xOrigin to be the value of the origin. Generates a compiler warning (warning: value returned from property not used. This does not generate a compiler warning unless flag’s type mismatches the method’s return type. and Messaging You get a compiler warning if setName: does not exist. the right hand side of the assignment is pre-evaluated and the result is passed to setIntegerProperty: and setFloatProperty:. That is. .floatProperty = ++i.
and any class (including a root class) can be the superclass for any number of subclasses one step farther from the root. Inheritance links all classes together in a hierarchical tree with a single class at its root. Each object gets its own instance variables. and it defines a set of methods that all objects in the class can use. that root class is typically NSObject. the names of instances typically begin with a lowercase letter (such as “myRectangle”). NSDictionary objects. All Rights Reserved. it declares the instance variables that become part of every member of the class. Inheritance Class definitions are additive. and Messaging Classes An object-oriented program is typically built from a variety of objects. By convention. each new class that you define is based on another class from which it inherits methods and instance variables. and they all have a set of instance variables cut from the same mold. Figure 1-1 Some Drawing Program Classes NSObject Graphic Image Text Shape Line Rectangle Square Circle Classes 2010-07-13 | © 2010 Apple Inc. In Objective-C. NSFont objects.CHAPTER 1 Objects. a class object that knows how to build new objects belonging to the class. The new class simply adds to or modifies what it inherits. All instances of a class have the same set of methods. for example. (For this reason it’s traditionally called a “factory object. Every class (except a root class) has a superclass one step nearer the root. The class definition is a prototype for a kind of object. Figure 1-1 illustrates the hierarchy for a few of the classes used in the drawing program. The objects that do the main work of your program are instances created by the class object at runtime. A program based on the Cocoa frameworks might use NSMatrix objects. Programs often use more than one object of the same kind or class—several NSArray objects or NSWindow objects. When writing code that is based upon the Foundation framework. 23 . NSText objects. you define objects by defining their class.”) The class object is the compiled version of the class. class names begin with an uppercase letter (such as “Rectangle”). It doesn’t need to duplicate inherited code. and many others. but the methods are shared. NSWindow objects. The compiler creates just one accessible object for each class. the objects it builds are instances of the class. Classes.
You can thus create very sophisticated objects by writing only a small amount of code. This is simply to say that a Square object isn’t only a Square. and reusing work done by the programmers of the framework. Plenty of potential superclasses are available. The class must duplicate much of what the NSObject class does. It defines the basic framework for Objective-C objects and object interactions. Figure 1-2 shows some of the instance variables that could be defined for a particular implementation of Rectangle.CHAPTER 1 Objects. Note: Implementing a new root class is a delicate task and one with many hidden hazards. all the way back to the root class. isa connects each object to its class. the Rectangle class is a subclass of Shape. the new object contains not only the instance variables that were defined for its class but also the instance variables defined for its superclass and for its superclass’s superclass. such as allocate instances. Inheritance is cumulative. Inheriting this ability from the NSObject class is much simpler and much more reliable than reinventing it in a new class definition. Others you might want to adapt to your own needs by defining a subclass. The NSObject Class NSObject is a root class. Shape. and so doesn’t have a superclass. but leave some specifics to be implemented in a subclass. you link it to the hierarchy by declaring its superclass. Every class but NSObject can thus be seen as a specialization or an adaptation of another class. see the Foundation framework documentation for the NSObject class and the NSObject protocol. Some framework classes define almost everything you need. as well as those defined specifically for Square. and NSObject. the isa instance variable defined in the NSObject class becomes part of every object. All Rights Reserved. Classes. you should generally use the NSObject class provided with Cocoa as the root class. Each successive subclass further modifies the cumulative total of what’s inherited. and an NSObject. and so on. So a Square object has the methods and instance variables defined for Rectangle. Cocoa includes the NSObject class and several frameworks containing definitions for more than 250 additional classes. When you define a class. connect them to their class. 24 Classes 2010-07-13 | © 2010 Apple Inc. Graphic. Thus. The Square class defines only the minimum needed to turn a Rectangle into a Square. Inheriting Instance Variables When a class object creates a new instance. and Graphic is a subclass of NSObject. . For this reason. and where they may come from. Shape is a subclass of Graphic. Some are classes that you can use “off the shelf”—incorporate into your program as is. a Graphic. and identify them to the runtime system. every class you create must be the subclass of another class (unless you define a new root class). Instances of the class must at least have the ability to behave like Objective-C objects at runtime. A class that doesn’t need to inherit any special behavior from another class should nevertheless be made a subclass of the NSObject class. Note that the variables that make the object a Rectangle are added to the ones that make it a Shape. and the ones that make it a Shape are added to the ones that make it a Graphic. a Shape. it’s also a Rectangle. It imparts to the classes and instances of classes that inherit from it the ability to behave as objects and cooperate with the runtime system. and Messaging This figure shows that the Square class is a subclass of the Rectangle class. For more information.
other methods defined in the new class can skip over the redefined method and find the original (see “Messages to self and super” (page 43) to learn how). declared in NSObject declared in Graphic declared in Shape declared in Rectangle A class doesn’t have to declare instance variables. instances of the new class perform it rather than the original. origin. height. rather than replace it outright. Graphic defines a display method that Rectangle overrides by defining its own version of display. width. *fillColor. you can implement a new method with the same name as one defined in a class farther up the hierarchy. Classes.CHAPTER 1 Objects. and NSObject classes as well as methods defined in its own class. and Messaging Figure 1-2 Class NSPoint NSColor Pattern . This type of inheritance is a major benefit of object-oriented programming. A redefined method can also incorporate the very method it overrides. all the way back to the root of the hierarchy.. the implementation of the method is effectively spread over all the classes. Graphic. When it does. Rectangle Instance Variables isa. Classes 2010-07-13 | © 2010 Apple Inc. All Rights Reserved. But because they don’t have instance variables (only instances do). linePattern. The new method overrides the original.. It can simply define new methods and rely on the instance variables it inherits. *primaryColor. You have to add only the code that customizes the standard functionality to your application. Shape. they inherit only methods... and for its superclass’s superclass. Although overriding a method blocks the original version from being inherited. a Square object can use methods defined in the Rectangle. filled. Square might not declare any new instance variables of its own. which instead perform the Rectangle version of display. if it needs any instance variables at all. For instance. but each new version incorporates the version it overrides. Class objects also inherit from the classes above them in the hierarchy. When you use one of the object-oriented frameworks provided by Cocoa. and subclasses of the new class inherit it rather than the original. your programs can take advantage of the basic functionality coded into the framework classes. When several classes in the hierarchy define the same method. but also to methods defined for its superclass. The Graphic method is available to all kinds of objects that inherit from the Graphic class—but not to Rectangle objects. 25 . float float BOOL NSColor . For example. Overriding One Method With Another There’s one useful exception to inheritance: When you define a new class. Inheriting Methods An object has access not only to the methods defined for its class. Any new class you define in your program can therefore make use of the code written for all the classes above it in the hierarchy. the new method serves only to refine or modify the method it overrides. For example.
Abstract Classes Some classes are designed only or primarily so that other classes can inherit from them. The type is based not just on the data structure the class defines (instance variables). Objective-C does not have syntax to mark classes as abstract. the compiler will complain. The NSObject class is the canonical example of an abstract class in Cocoa. In addition. A class name can appear in source code wherever a type specifier is permitted in C—for example. Because this way of declaring an object type gives the compiler information about the kind of object it is. they’re sometimes also called abstract superclasses. to warn if an object could receive a message that it appears not to be able to respond to—and to loosen some restrictions that apply to objects generically typed id. as an argument to the sizeof operator: int i = sizeof(Rectangle). it can’t override inherited instance variables.) Unlike some other languages. Abstract classes often contain code that helps define the structure of an application. You never use instances of the NSObject class in an application—it wouldn’t be good for anything. provides an example of an abstract class instances of which you might occasionally use directly. Classes. If you try. The class. When you create subclasses of these classes. instances of your new classes fit effortlessly into the application structure and work automatically with other objects. Static typing makes the pointer explicit. Static Typing You can use a class name in place of id to designate an object’s type: Rectangle *myRectangle. Since an object has memory allocated for every instance variable it inherits. but also on the behavior included in the definition (methods). it’s known as static typing. (Because abstract classes must have subclasses to be useful. . defines a data type. you can’t override an inherited variable by declaring a new one with the same name. All Rights Reserved. Just as id is actually a pointer. it would be a generic object with the ability to do nothing in particular. on the other hand. but contains useful code that reduces the implementation burden of its subclasses. nor does it prevent you from creating an instance of an abstract class. id hides it. in effect. Class Types A class definition is a specification for a kind of object. These abstract classes group methods and instance variables that can be used by a number of different subclasses into a common definition. objects are statically typed as pointers to a class. it can make your intentions clearer to others who read your source code. Objects are always typed by a pointer.CHAPTER 1 Objects. The abstract class is typically incomplete by itself. and Messaging Although a subclass can override inherited methods. 26 Classes 2010-07-13 | © 2010 Apple Inc. However. The NSView class. Static typing permits the compiler to do some type checking—for example. it doesn’t defeat dynamic binding or alter the dynamic determination of a receiver’s class at runtime.
. The class object has access to all the information about the class. checks more generally whether the receiver inherits from or is a member of a particular class (whether it has the class in its inheritance path): if ( [anObject isKindOfClass:someClass] ) . Type Introspection Instances can reveal their types at runtime. Introspection isn’t limited to type information. See the NSObject class specification in the Foundation framework reference for more on isKindOfClass:. and Messaging An object can be statically typed to its own class or to any class that it inherits from. For example. 27 .. Later sections of this chapter discuss methods that return the class object.. isMemberOfClass:. The set of classes for which isKindOfClass: returns YES is the same set to which the receiver can be statically typed. See “Enabling Static Behavior” (page 91) for more on static typing and its benefits. checks whether the receiver is an instance of a particular class: if ( [anObject isMemberOfClass:someClass] ) . to represent the class. and reveal other information. The compiler creates just one object. Classes.. All Rights Reserved. also defined in the NSObject class. For purposes of type checking. Class Objects A class definition contains various kinds of information. It’s more than a Graphic since it also has the instance variables and method capabilities of a Shape and a Rectangle. This is possible because a Rectangle is a Graphic. a Rectangle instance could be statically typed to the Graphic class: Graphic *myRectangle. which means mainly information about what instances of the class are like. a class object. report whether an object can respond to a message. The isMemberOfClass: method. The isKindOfClass: method.. defined in the NSObject class. the compiler considers myRectangle to be a Graphic. but it’s a Graphic nonetheless. but at runtime it’s treated as a Rectangle.CHAPTER 1 Objects. since inheritance makes a Rectangle a kind of Graphic. It’s able to produce new instances according to the plan put forward in the class definition. and related methods. Classes 2010-07-13 | © 2010 Apple Inc.
just as instances inherit instance methods. As these examples show. All class objects are of type Class. class objects can. id rectClass = [Rectangle class]. or one like it. receive messages. and every instance has at least one method (like init) that 28 Classes 2010-07-13 | © 2010 Apple Inc. Class objects are thus full-fledged objects that can be dynamically typed. Using this type name for a class is equivalent to using the class name to statically type an instance. This line of code. the Rectangle class returns the class version number using a method inherited from the NSObject class: int versionNumber = [Rectangle version]. Note: The compiler also builds a “metaclass object” for each class. They’re special only in that they’re created by the compiler. Initialization typically follows immediately after allocation: myRectangle = [[Rectangle alloc] init]. In the following example. it’s not an instance itself. It has no instance variables of its own and it can’t perform methods intended for instances of the class. In source code. it generally needs to be more completely initialized. The alloc method dynamically allocates memory for the new object’s instance variables and initializes them all to 0—all. Both respond to a class message: id aClass = [anObject class]. and are the agents for producing instances at runtime. Every class object has at least one method (like alloc) that enables it to produce new objects. the class name stands for the class object only as the receiver in a message expression. But class objects can also be more specifically typed to the Class data type: Class aClass = [anObject class]. except the isa variable that connects the new instance to its class. that is. This code tells the Rectangle class to create a new Rectangle instance and assign it to the myRectangle variable: id myRectangle. and inherit methods from other classes. Class rectClass = [Rectangle class]. like all other objects. be typed id. the metaclass object is used only internally by the runtime system. and Messaging Although a class object keeps the prototype of a class instance. a class definition can include methods intended specifically for the class object—class methods as opposed to instance methods. That’s the function of an init method. But while you can send messages to instances and to the class object. . A class object inherits class methods from the classes above it in the hierarchy. Elsewhere. would be necessary before myRectangle could receive any of the messages that were illustrated in previous examples in this chapter. For an object to be useful. Creating Instances A principal function of a class object is to create new instances. However. The alloc method returns a new instance and that instance performs an init method to set its initial state. the class object is represented by the class name. Classes. lack data structures (instance variables) of their own other than those built from the class definition. It describes the class object just as the class object describes instances of the class. myRectangle = [Rectangle alloc].CHAPTER 1 Objects. All Rights Reserved. However. you need to ask an instance or the class to return the class id.
Customization With Class Objects It’s not just a whim of the Objective-C language that classes are treated as objects. Since an application might need more than one kind of NSMatrix. Classes 2010-07-13 | © 2010 Apple Inc. but there are many different kinds. even types that haven’t been invented yet. All Rights Reserved. users of the class could be sure that the objects they created were of the right type. for example. is a method that might initialize a new Rectangle instance). Initialization methods often take arguments to allow particular values to be passed and have keywords to label the arguments (initWithPosition:size:. The visible matrix that an NSMatrix object draws on the screen can grow and shrink at runtime. it could become cluttered with NSMatrix subclasses. or some other kind of NSCell? The NSMatrix object must allow for any kind of cell. an NSMatrix object can be customized with a particular kind of NSCell object. Classes.. and it unnecessarily proliferates the number of classes. But what kind of objects should they be? Each matrix displays just one kind of NSCell. The inheritance hierarchy in Figure 1-3 shows some of those provided by the Application Kit. but they all begin with “init” . where the class belongs to an open-ended set. It’s possible. benefits for design. Moreover. and sometimes surprising. all to make up for NSMatrix's failure to do it. to customize an object with a class. One solution to this problem is to define the NSMatrix class as an abstract class and require everyone who uses it to declare a subclass and implement the methods that produce new cells. NSTextFieldCell objects to display fields where the user can enter and edit text. But this requires others to do work that ought to be done in the NSMatrix class. should they be NSButtonCell objects to display a bank of buttons or switches. It’s a choice that has intended. for example. for example. the matrix needs to be able to produce new objects to fill the new slots that are added. Every time you invented a new kind of NSCell. 29 . programmers on different projects would be writing virtually identical code to do the same job. An NSMatrix object can take responsibility for creating the individual objects that represent its cells. Because they would be implementing the methods. and Messaging prepares it for use. In the Application Kit. When it grows.CHAPTER 1 Objects. each with a different kind of NSCell. It can do this when the matrix is first initialized and later when new cells are needed. you’d also have to define a new kind of NSMatrix. perhaps in response to user actions.
it can’t initialize. however.) This pattern is commonly used to define shared instances of a class (such as singletons. It defines a setCellClass: method that passes the class object for the kind of NSCell object an NSMatrix should use to fill empty slots: [myMatrix setCellClass:[NSButtonCell class]]. In the case when you need only one object of a particular class. All Rights Reserved. (Thus unlike instance variables. Declaring a variable static limits its scope to just the class—and to just the part of the class that’s implemented in the file. see “Creating a Singleton Instance” in Cocoa Fundamentals Guide). Variables and Class Objects When you define a new class. @implementation MyClass + (MyClass *)sharedInstance { // check for existence of shared instance // create if necessary return MCLSSharedInstance. no “class variable” counterpart to an instance variable. and provide class methods to manage it. int MCLSGlobalVariable. or manage other processes essential to the application. you can declare a variable to be static. it can approach being a complete and versatile object in its own right. There is. static variables cannot be inherited by. is to allow NSMatrix instances to be initialized with a kind of NSCell—with a class object.CHAPTER 1 Objects. The NSMatrix object uses the class object to produce new cells when it’s first initialized and whenever it’s resized to contain more cells. a class object has no access to the instance variables of any instances. subclasses. This saves the step of allocating and initializing an instance. Moreover. This kind of customization would be difficult if classes weren’t objects that could be passed in messages and assigned to variables. are provided for the class. 30 Classes 2010-07-13 | © 2010 Apple Inc. @implementation MyClass // implementation continues In a more sophisticated implementation. static MyClass *MCLSSharedInstance. and Messaging A better solution. dispense instances from lists of objects already created. Classes. initialized from the class definition. . or alter them. or directly manipulated by. the solution the NSMatrix class actually adopts. } // implementation continues Static variables help give the class object more functionality than just that of a “factory” producing instances. For all the instances of a class to share data. you must define an external variable of some sort. read. you can put all the object’s state into static variables and use only class methods. you can specify instance variables. A class object can be used to coordinate the instances it creates. Only internal data structures. The simplest way to do this is to declare a variable in the class implementation file as illustrated in the following code fragment. Every instance of the class can maintain its own copy of the variables you declare—each object controls its own data.
If a class makes use of static or global variables. Just before class B is to receive its first message. Although programs don’t allocate class objects. } } Note: Remember that the runtime system sends initialize to each class individually. Listing 1-3 Implementation of the initialize method + (void)initialize { if (self == [ThisClass class]) { // Perform initialization here. For example. use the template in Listing 1-3 when implementing the initialize method. but the limited scope of static variables better serves the purpose of encapsulating data into separate objects. and Messaging Note: It is also possible to use external variables that are not declared static. you may need to initialize it just as you would an instance. if a class maintains an array of instances. Methods of the Root Class All objects. Objective-C does provide a way for programs to initialize them. and class B inherits from class A but does not implement the initialize method. an initialize message sent to a class that doesn’t implement the initialize method is forwarded to the superclass.. the initialize method could set up the array and even allocate one or two default instances to have them ready. Classes. For example. If no initialization is required. class A’s initialize is executed instead.CHAPTER 1 Objects. the initialize method is a good place to set their initial values. Because of inheritance. It’s the province of the NSObject class to provide this interface. in a class’s implementation of the initialize method. But. Therefore. even though the superclass has already received the initialize message. All Rights Reserved. Both class objects and instances should be able to introspect about their abilities and to report their place in the inheritance hierarchy. because class B doesn’t implement initialize. class A should ensure that its initialization logic is performed only once. the runtime system sends initialize to it. To avoid performing initialization logic more than once. assume class A implements the initialize method. . Classes 2010-07-13 | © 2010 Apple Inc. Therefore. This gives the class a chance to set up its runtime environment before it’s used. 31 . The runtime system sends an initialize message to every class object before the class receives any other messages and after its superclass has received the initialize message. you don’t need to write an initialize method to respond to the message.. classes and instances alike. need an interface to the runtime system. Initializing a Class Object If you want to use a class object for anything besides allocating instances. you must not send the initialize message to its superclass. and for the appropriate class.
you can use NSClassFromString to return the class object: NSString *className.. It would have been illegal to simply use the name “Rectangle” as the argument.. if ( [anObject isKindOfClass:NSClassFromString(className)] ) . .. The example below passes the Rectangle class as an argument in an isKindOfClass: message. When a class object receives a message that it can’t respond to with a class method.. All Rights Reserved. but rather belong to the Class data type. class objects can’t be. Class Names in Source Code In source code. the class name refers to the class object. The class name can only be a receiver.. 32 Classes 2010-07-13 | © 2010 Apple Inc. Here anObject is statically typed to be a pointer to a Rectangle. Classnames are about the only names with global visibility in Objective-C. The compiler expects it to have the data structure of a Rectangle instance and the instance methods defined and inherited by the Rectangle class. These contexts reflect the dual role of a class as a data type and as an object: ■ The class name can be used as a type name for a kind of object. you must ask the class object to reveal its id (by sending it a class message).. class names can be used in only two very different contexts. A class and a global variable can’t have the same name. Classes. This function returns nil if the string it’s passed is not a valid class name. and only if there’s no class method that can do the job. For more on this peculiar ability of class objects to perform root instance methods. For example: Rectangle *anObject. since they aren’t members of a class. This usage was illustrated in several of the earlier examples.. Static typing enables the compiler to do better type checking and makes source code more self-documenting. if ( [anObject isKindOfClass:[Rectangle class]] ) . In any other context. The class name can stand for the class object only as a message receiver. If you don’t know the class name at compile time but have it as a string at runtime. Only instances can be statically typed. Classnames exist in the same namespace as global variables and function names. The only instance methods that a class object can perform are those defined in the root class. . see the NSObject class specification in the Foundation framework reference. See “Enabling Static Behavior” (page 91) for details. ■ As the receiver in a message expression. the runtime system determines whether there’s a root instance method that can respond.CHAPTER 1 Objects.
When this happens. When testing for class equality. 33 .. key-value observing and Core Data—see Key-Value Observing Programming Guide and Core Data Programming Guide respectively). It is important. All Rights Reserved. the class method is typically overridden such that the dynamic subclass masquerades as the class it replaces.. and Messaging Testing Class Equality You can test two class objects for equality using a direct pointer comparison. though. There are several features in the Cocoa frameworks that dynamically and transparently subclass existing classes to extend their functionality (for example.CHAPTER 1 Objects. Put in terms of API: [object class] != object_getClass(object) != *((Class*)object) You should therefore test two classes for equality as follows: if ([objectA class] == [objectB class]) { //. you should therefore compare the values returned by the class method rather than those returned by lower-level functions. Classes 2010-07-13 | © 2010 Apple Inc. Classes. to get the correct class.
Classes. All Rights Reserved. and Messaging 34 Classes 2010-07-13 | © 2010 Apple Inc.CHAPTER 1 Objects. .
h and defined in Rectangle. All Rights Reserved. The name of the implementation file has the . classes are defined in two parts: ■ ■ An interface that declares the methods and instance variables of the class and names its superclass An implementation that actually defines the class (contains the code that implements its methods) These are typically split between two files. the Rectangle class would be declared in Rectangle.m extension.m. the interface and implementation are usually separated into two different files. Because it’s included in other source files. The interface file must be made available to anyone who uses the class. A single file can declare or implement more than one class. Interface and implementation files typically are named after the class. Source Files Although the compiler doesn’t require it. An object is a self-contained entity that can be viewed from the outside almost as a “black box. Separating an object’s interface from its implementation fits well with the design of object-oriented programs. In Objective-C. if not also a separate implementation file. The interface file can be assigned any other extension. it’s customary to have a separate interface file for each class. Categories are described in “Categories and Extensions” (page 79). (All Objective-C directives to the compiler begin with “@” . For example.CHAPTER 2 Defining a Class Much of object-oriented programming consists of writing the code for new objects—defining new classes.h extension typical of header files. indicating that it contains Objective-C source code.” Categories can compartmentalize a class definition or extend an existing one. once you’ve declared its interface—you can freely alter its implementation without affecting any other part of the application. the name of the interface file usually has the . sometimes however a class definition may span several files through the use of a feature called a “category. Keeping class interfaces separate better reflects their status as independent entities.” Once you’ve determined how an object interacts with other elements in your program—that is.) @interface ClassName : ItsSuperclass { instance variable declarations } method declarations @end Source Files 2010-07-13 | © 2010 Apple Inc. 35 . Nevertheless. Class Interface The declaration of a class interface begins with the compiler directive @interface and ends with the directive @end.
Here’s a partial list of instance variables that might be declared in the Rectangle class: float width. as discussed under “Inheritance” (page 23).CHAPTER 2 Defining a Class The first line of the declaration presents the new class name and links it to its superclass. the new class is declared as a root class. The superclass defines the position of the new class in the inheritance hierarchy.. the arguments are declared within the method name after the colons.makeGroup:group. the data structures that are part of each instance of the class. All Rights Reserved. Methods for the class are declared next. When there’s more than one argument.(void)setRadius:(float)aRadius. it’s assumed to be the default type for methods and messages—an id. 36 Class Interface 2010-07-13 | © 2010 Apple Inc. class methods. are preceded by a plus sign: + alloc.(float)radius. NSColor *fillColor. .. The names of methods that can be used by class objects. Following the first part of the class declaration. If the colon and superclass name are omitted. A method can also have the same name as an instance variable. Argument types are declared in the same way: . just as in a message. float height. are marked with a minus sign: .(void)setWidth:(float)width height:(float)height. For example: . . especially if the method returns the value in the variable.(void)display. Method return types are declared using the standard C syntax for casting one type to another: . Arguments break the name apart in the declaration. This is more common. Although it’s not a common practice. a rival to the NSObject class. instance methods. For example.. If a return or argument type isn’t explicitly declared. Circle has a radius method that could match a radius instance variable. just as a function would: . you can define a class method and an instance method with the same name. BOOL filled. The methods that instances of a class can use. braces enclose declarations of instance variables. The alloc method illustrated earlier returns id. Methods that take a variable number of arguments declare them using a comma and ellipsis points. after the braces enclosing instance variables and before the end of the class declaration.
Class Interface 2010-07-13 | © 2010 Apple Inc. it gets interfaces for the entire inheritance hierarchy that the class is built upon. Since declarations like this simply use the class name as a type and don’t depend on any details of the class interface (its methods and instance variables). mentions the NSColor class.h" @interface ClassName : ItsSuperclass { instance variable declarations } method declarations @end This convention means that every interface file includes. It’s therefore preferred and is used in place of #include in code examples throughout Objective-C–based documentation. An interface file mentions class names when it statically types instance variables. When a source module imports a class interface. Referring to Other Classes An interface file declares a class and. and arguments. sends a message to invoke a method declared for the class.h" This directive is identical to #include. from NSObject on down through its superclass. The interface is usually included with the #import directive: #import "Rectangle. To reflect the fact that a class definition builds on the definitions of inherited classes. the interface files for all inherited classes. where the interface to a class is actually used (instances created.CHAPTER 2 Defining a Class Importing the Interface The interface file must be included in any source module that depends on the class interface—that includes any module that creates an instance of the class. All Rights Reserved. messages sent). by importing its superclass. Note that if there is a precomp—a precompiled header—that supports the superclass. this declaration . implicitly contains declarations for all inherited classes. you may prefer to import the precomp instead. Circle. it must import them explicitly or declare them with the @class directive: @class Rectangle. indirectly. or mentions an instance variable declared in the class. It doesn’t import their interface files. However. This directive simply informs the compiler that “Rectangle” and “Circle” are class names.(void)setPrimaryColor:(NSColor *)aColor. 37 . For example. the @class directive gives the compiler sufficient forewarning of what to expect. If the interface mentions classes not in this hierarchy. an interface file begins by importing the interface for its superclass: #import "ItsSuperclass. return values. except that it makes sure that the same file is never included more than once.
It contains all the information they need to work with the class (programmers might also appreciate a little documentation). they must nevertheless be declared in the interface file. and their two interface files import each other. neither class may compile correctly. except when defining a subclass. if one class declares a statically typed instance variable of another class. The @class directive minimizes the amount of code seen by the compiler and linker. it can safely omit: ■ ■ The name of the superclass The declarations of instance variables 38 Class Implementation 2010-07-13 | © 2010 Apple Inc. the interface file lets other modules know what messages can be sent to the class object and instances of the class. ■ ■ Class Implementation The definition of a class is structured very much like its declaration. . not just where it’s defined. For example. and the corresponding implementation file imports their interfaces (since it will need to create instances of those classes or send them messages). methods that are internal to the class implementation can be omitted. ■ The interface file tells users how the class is connected into the inheritance hierarchy and what other classes—inherited or simply referred to somewhere in the class—are needed. As a programmer. and is therefore the simplest way to give a forward declaration of a class name. All Rights Reserved. Typically. Rectangle. Being simple. For example. you can generally ignore the instance variables of the classes you use. Because the implementation doesn’t need to repeat any of the declarations it imports. every implementation file must import its own interface.h. The interface file also lets the compiler know what instance variables an object contains. Although instance variables are most naturally viewed as a matter of the implementation of a class rather than its interface. The Role of the Interface The purpose of the interface file is to declare the new class to other source modules (and to other programmers). Finally.CHAPTER 2 Defining a Class the class interface must be imported. and tells programmers what variables subclasses inherit.m imports Rectangle. This is because the compiler must be aware of the structure of an object where it’s used. it avoids potential problems that may come with importing files that import still other files. however. It begins with the @implementation directive and ends with the @end directive: @implementation ClassName : ItsSuperclass { instance variable declarations } method definitions @end However. Every method that can be used outside the class definition is declared in the interface file. an interface file uses @class to declare classes. through its list of method declarations.
Class Implementation 2010-07-13 | © 2010 Apple Inc. the exact nature of the structure is hidden. but without the semicolon. { va_list ap.. .CHAPTER 2 Defining a Class This simplifies the implementation and makes it mainly devoted to method definitions: #import "ClassName.getGroup:group.. It can refer to them simply by name. group). . } . like C functions. va_start(ap..(void)setFilled:(BOOL)flag { filled = flag.. } Referring to Instance Variables By default. they’re declared in the same manner as in the interface file. } .. Before the braces. the following method definition refers to the receiver’s filled instance variable: . or ->) to refer to an object’s data.. All Rights Reserved.. within a pair of braces. } Neither the receiving object nor its filled instance variable is declared as an argument to this method....(void)setFilled:(BOOL)flag { ....h" @implementation ClassName method definitions @end Methods for a class are defined. the definition of an instance method has all the instance variables of the object within its scope. Although the compiler creates the equivalent of C structures to store instance variables. For example: + (id)alloc { . For example.. . .(BOOL)isFilled { . yet the instance variable falls within its scope. 39 .h> . You don’t need either of the structure operators (. } Methods that take a variable number of arguments handle them just as a function would: #import <stdarg. This simplification of method syntax is a significant shorthand in the writing of Objective-C code.
To enforce the ability of an object to hide its data. Often there’s a one-to-one correspondence between a method and an instance variable. as an instance variable: @interface Sibling : NSObject { Sibling *twin. the structure pointer operator (->) is used. } As long as the instance variables of the statically typed object are within the scope of the class (as they are here because twin is typed to the same class). the object’s type must be made explicit to the compiler through static typing. But to provide flexibility. twin. these changes won’t really affect its interface. not in its internal data structures. twin->gender = gender. that the Sibling class declares a statically typed object. even though the methods it declares remain the same. for example. . An object’s interface lies in its methods. } return twin. it also lets you explicitly set the scope at three different levels. } But this need not be the case.CHAPTER 2 Defining a Class When the instance variable belongs to an object that’s not the receiver. Each level is marked by a compiler directive: Directive @private Meaning The instance variable is accessible only within the class that declares it. As a class is revised from time to time. as in the following example: . In referring to the instance variable of a statically typed object. and some instance variables might store information that an object is unwilling to reveal. Suppose. As long as messages are the vehicle for interacting with instances of the class. a Sibling method can set them directly: . twin->appearance = appearance. Some methods might return information not stored in instance variables. 40 Class Implementation 2010-07-13 | © 2010 Apple Inc.(BOOL)isFilled { return filled. limits their visibility within the program.makeIdenticalTwin { if ( !twin ) { twin = [[Sibling alloc] init]. } The Scope of Instance Variables Although they’re declared in the class interface. the choice of instance variables may change. the compiler limits the scope of instance variables—that is. All Rights Reserved. struct features *appearance. instance variables are more a matter of the way a class is implemented than of the way it’s used. int gender.
the age and evaluation instance variables are private. @interface Worker : NSObject { char *name.CHAPTER 2 Defining a Class Directive Meaning @protected The instance variable is accessible within the class that declares it and within classes that inherit it. float wage. and wage are protected. 41 . up to the next directive or the end of the list. Using the modern runtime. All Rights Reserved. where @private may be too restrictive but @protected or @public too permissive. This is analogous to private_extern for variables and functions. In the following example. char *evaluation. Class Implementation 2010-07-13 | © 2010 Apple Inc. and boss is public. This is illustrated in Figure 2-1. @private int age. job. an @package instance variable acts like @public inside the image that implements the class. but @private outside. name. @public @package The instance variable is accessible everywhere. Any code outside the class implementation’s image that tries to use the instance variable will get a link error. Figure 2-1 The scope of instance variables The class that declares the instance variable @private @protected A class that inherits the instance variable @public Unrelated code A directive applies to all the instance variables listed after it. This is most useful for instance variables in framework classes. @protected id
and still incorporate the original method in the modification: . } the messaging routine will find the version of negotiate defined in High.CHAPTER 2 Defining a Class . since Mid is where makeLastingPeace is defined. ■ Mid’s version of negotiate could still be used. In sending the message to super. All Rights Reserved. if (self) { . But before doing so. under the circumstances. the author of Mid’s makeLastingPeace method intentionally skipped over Mid’s version of negotiate (and over any versions that might be defined in classes like Low that inherit from Mid) to perform the version defined in the High class. it sends an init message to super to have the classes it inherits from initialize their instance variables. The init method. is designed to work like this. Neither message finds Mid’s version of negotiate. Here it enabled makeLastingPeace to avoid the Mid version of negotiate that redefined the original High version.makeLastingPeace { [super negotiate]. Each version of init follows this procedure. Each init method has responsibility for initializing the instance variables defined in its class. which initializes a newly allocated instance. it’s right to avoid it: ■ The author of the Low class intentionally overrode Mid’s version of negotiate so that instances of the Low class (and its subclasses) would invoke the redefined version of the method instead. } For some tasks.. You can override an existing method to modify or add to it. } } Messages to self and super 2010-07-13 | © 2010 Apple Inc. Not being able to reach Mid’s version of negotiate may seem like a flaw.. so classes initialize their instance variables in the order of inheritance: . each class in the inheritance hierarchy can implement a method that does part of the job and passes the message on to super for the rest.negotiate { .. Using super Messages to super allow method implementations to be distributed over more than one class. return [super negotiate].. but it would take a direct message to a Mid instance to do it. super provides a way to bypass a method that overrides another method.(id)init { self = [super init]. .. The designer of Low didn’t want Low objects to perform the inherited method.. As this example illustrates. 45 . It ignores the receiving object’s class (Low) and skips to the superclass of Mid. but. Mid’s designer wanted to use the High version of negotiate and no other.
and are described in more detail in “Allocating and Initializing Objects” (page 47). + (id)rectangleOfColor:(NSColor *)color { id newInstance = [[self alloc] init].CHAPTER 2 Defining a Class Initializer methods have some additional constraints. the instance returned will be the same type as the subclass (for example. } See “Allocating and Initializing Objects” (page 47) for more information about object allocation. There’s a tendency to do just that in definitions of class methods. self and super both refer to the receiving object—the object that gets a message telling it to perform the method. if the class is subclassed. . // BAD [self setColor:color]. It’s also possible to concentrate core functionality in one method defined in a superclass. and have subclasses incorporate the method through messages to super. But that would be an error. many class methods combine allocation and initialization of an instance. For example. return [self autorelease]. Class methods are often concerned not with the class object. often setting up instance variable values at the same time. } To avoid confusion. self refers to the class object. it can still get the basic functionality by sending a message to super. the array method of NSArray is inherited by NSMutableArray). // GOOD [newInstance setColor:color]. Inside an instance method. 46 Messages to self and super 2010-07-13 | © 2010 Apple Inc. it’s often better to send alloc to self. This is an example of what not to do: + (Rectangle *)rectangleOfColor:(NSColor *) color { self = [[Rectangle alloc] init]. but with instances of the class. but inside a class method. it’s usually better to use a variable other than self to refer to an instance inside a class method: + (id)rectangleOfColor:(NSColor *)color { id newInstance = [[Rectangle alloc] init]. it might be tempting to send messages to the newly allocated instance and to call the instance self. even assigned a new value. return [newInstance autorelease]. every class method that creates an instance must allocate storage for the new object and initialize its isa variable to the class structure. But self is a variable name that can be used in any number of ways. In such a method. it’s used only as the receiver of a message. This way. and the rectangleOfColor: message is received by a subclass. For example. This is typically left to the alloc and allocWithZone: methods defined in the NSObject class. All Rights Reserved. Redefining self super is simply a flag to the compiler telling it where to begin searching for the method to perform. // EXCELLENT [newInstance setColor:color]. return [newInstance autorelease]. self refers to the instance. rather than sending the alloc message to the class in a class method. } In fact. just as in an instance method. If another class overrides these methods (a rare case).
You must: ■ ■ Dynamically allocate memory for the new object Initialize the newly allocated memory to appropriate values An object isn’t fully functional until both steps have been completed. NSObject declares the method mainly to establish the naming convention described earlier. All other instance variables are set to 0. The alloc and allocWithZone: methods initialize a newly allocated object’s isa instance variable so that it points to the object’s class (the class object). method to initialize them. They don’t need to be overridden and modified in subclasses. For example. labels for the arguments follow the “init” prefix. Usually. However. Every class that declares instance variables must provide an init.. the method name is just those four letters. init. NSObject defines two principal methods for this purpose. The NSObject class declares the isa variable and defines an init method.CHAPTER 3 Allocating and Initializing Objects Allocating and Initializing Objects It takes two steps to create an object using Objective-C. by convention. all NSObject’s init method does is return self.. an object needs to be more specifically initialized before it can be safely used. and discuss how they are controlled and modified. These methods allocate enough memory to hold all the instance variables for an object belonging to the receiving class. memory for new objects is allocated using class methods defined in the NSObject class. The Returned Object An init. takes arguments. 47 . alloc and allocWithZone:. begin with the abbreviation “init” If the method takes no arguments. Separating allocation from initialization gives you individual control over each step so that each can be modified independently of the other. method normally initializes the instance variables of the receiver. then returns it. The following sections look first at allocation and then at initialization. since isa is initialized when memory for an object is allocated.. All Rights Reserved. In Objective-C. Allocating and Initializing Objects 2010-07-13 | © 2010 Apple Inc.. It’s the responsibility of the method to return an object that can be used without error. If it . an NSView object can be initialized with an initWithFrame: method. This initialization is the responsibility of class-specific instance methods that. Each step is accomplished by a separate method but typically in a single line of code: id anObject = [[Rectangle alloc] init].
it won’t be able to complete the initialization.. in many others.. indicating that the requested object can’t be created. if ( anObject ) [anObject someOtherMessage]. In some situations. you need to write a custom initializer. For example. In these other cases. this responsibility can mean returning a different object than the receiver. all bits of memory (except for isa)—and hence the values for all its instance variables—are set to 0. an instance with the requested name. When asked to assign a new instance a name that’s already being used by another object. method to do what it’s asked to do. it might provide an initWithName: method to initialize new instances. the name of a custom initializer method begins with init. Implementing an Initializer When a new object is created.. method might return an object other than the newly allocated receiver. else . since it ignores the return of init. id anObject = [SomeClass alloc]. an initFromFile: method might get the data it needs from a file passed as an argument. id anObject = [[SomeClass alloc] init].. In a few cases.. the init. initWithName: might refuse to assign the same name to two objects. or you want to pass values as arguments to the initializer. In Objective-C... custom initializers are subject to more constraints and conventions than are most other methods. [anObject init]. The following code is very dangerous. All Rights Reserved. then you should check the return value before proceeding: id anObject = [[SomeClass alloc] init]. Because an init.. to safely initialize an object. you want to provide other default values for an object’s instance variables. if a class keeps a list of named objects. method could free the receiver and return nil.. For example. this may be all you require when an object is initialized. If the file name it’s passed doesn’t correspond to an actual file. it might free the newly allocated instance and return the other object—thus ensuring the uniqueness of the name while at the same time providing what was asked for. [anObject someOtherMessage]. it’s important that programs use the value returned by the initialization method. you should combine allocation and initialization messages in one line of code. it might be impossible for an init. 48 Implementing an Initializer 2010-07-13 | © 2010 Apple Inc. not just that returned by alloc or allocWithZone:. If there can be no more than one object per name. or even return nil. . in some cases. In such a case. If there’s a chance that the init. method might return nil (see “Handling Initialization Failure” (page 50)).. Instead. Constraints and Conventions There are several constraints and conventions that apply to initializer methods that do not apply to other methods: ■ By convention.CHAPTER 3 Allocating and Initializing Objects However. [anObject someOtherMessage].
NSString provides a method initWithFormat:. however. This avoids the possibility of triggering unwanted side-effects in the accessors. In brief. For example. a full explanation of this issue is given in “Coordinating Classes” (page 51).(id)init { // Assign self to value returned by super's designated initializer // Designated initializer for NSObject is init self = [super init]. the designated initializer is init. you typically do so using direct assignment rather than using an accessor method. } return self.CHAPTER 3 Allocating and Initializing Objects Examples from the Foundation framework include. ■ At the end of the initializer. if a class requires its instances to have a name and a data source. the message returns an instance of NSMutableString. you must return self. you must ultimately invoke a designated initializer. (See also. if (self) { creationDate = [[NSDate alloc] init]. though. initWithObjects:. Implementing an Initializer 2010-07-13 | © 2010 Apple Inc. and initWithObjectsAndKeys:. that represents the time when the object was created: . Failed initializers are discussed in more detail in “Handling Initialization Failure” (page 50). or another of its own initializers that ultimately invokes the designated initializer. When sent to an instance of NSMutableString (a subclass of NSString). initWithFormat:. The reason for this is that id gives an indication that the class is purposefully not considered—that the class is unspecified and subject to change. but set nonessential instance variables to arbitrary values or allow them to have the null values set by default. ■ The return type of an initializer method should be id. depending on context of invocation. 49 . By default (such as with NSObject). All Rights Reserved.) An initializer doesn’t need to provide an argument for each variable. If you are implementing any other initializer. it should invoke its own class’s designated initializer. Designated initializers are described in “The Designated Initializer” (page 53). if you are implementing a new designated initializer. it might provide an initWithName:fromURL: method.) ■ In the implementation of a custom initializer. the singleton example given in “Combining Allocation and Initialization” (page 55). It could then rely on methods like setEnabled:. it must invoke the superclass’ designated initializer. creationDate. For example. not NSString. ■ You should assign self to the value returned by the initializer. and setDimensions: to modify default values after the initialization phase had been completed. This is because the initializer could return a different object than the original receiver. The following example illustrates the implementation of a custom initializer for a class that inherits from NSObject and has an instance variable. unless the initializer fails in which case you return nil. ■ If you set the value of an instance variable. setFriend:. } (The reason for using the if (self) pattern is discussed in “Handling Initialization Failure” (page 50).
It shows that you can do work before invoking the super class’s designated initializer. ■ Note: You should only call [self release] at the point of failure. if (self) { creationDate = [[NSDate alloc] init]. you should not also call release. } This example doesn’t show what to do if there are any problems during initialization. } return self. size. the class inherits from NSView. or an external caller) that receives a nil from an initializer method should be able to deal with it. There are two main consequences of this policy: ■ Any object (whether your own class. You must make sure that dealloc methods are safe in presence of partially-initialized objects. } The following example builds on that shown in “Constraints and Conventions” (page 48) to show how to handle an inappropriate value passed as the parameter: .0. } return self. All Rights Reserved. you should call [self release] and return nil. if (self) { image = [anImage retain]. . In this case. NSRect frame = NSMakeRect(0.(id)initWithImage:(NSImage *)anImage { 50 Implementing an Initializer 2010-07-13 | © 2010 Apple Inc. 0. .width.size. If you get nil back from an invocation of the superclass’s initializer. This is typically handled by the pattern of performing initialization within a block dependent on a test of the return value of the superclass’s initializer—as seen in previous examples: . if there is a problem during an initialization method. this is discussed in the next section.height).(id)initWithImage:(NSImage *)anImage { // Find the size for the new instance from the image NSSize size = anImage. a subclass. In the unlikely case where the caller has established any external references to the object before the call.0. // Assign self to value returned by super's designated initializer // Designated initializer for NSView is initWithFrame: self = [super initWithFrame:frame]. this includes undoing any connections.(id)init { self = [super init]. You should simply clean up any references you set up that are not dealt with in dealloc and return nil.CHAPTER 3 Allocating and Initializing Objects The next example illustrates the implementation of a custom initializer that takes a single argument. Handling Initialization Failure In general. size.
height). see Error Handling Programming Guide. 51 . if (self) { NSData *data = [[NSData alloc] initWithContentsOfURL:aURL options:NSUncachedRead error:errorPtr]. Coordinating Classes The init. } // Find the size for the new instance from the image NSSize size = anImage... } Implementing an Initializer 2010-07-13 | © 2010 Apple Inc. } // implementation continues. All Rights Reserved.(id)initWithName:(NSString *)string { self = [super init]. methods a class defines typically initialize only those variables declared in that class. return nil.0. if (self) { image = [anImage retain].0. return nil. // Assign self to value returned by super's designated initializer // Designated initializer for NSView is initWithFrame: self = [super initWithFrame:frame]. } return self. You should typically not use exceptions to signify errors of this sort—for more information. in the case of a problem. NSRect frame = NSMakeRect(0.. if (self) { name = [string copy].CHAPTER 3 Allocating and Initializing Objects if (anImage == nil) { [self release]. 0. if (data == nil) { // In this case the error object is created in the NSData initializer [self release].. Inherited instance variables are initialized by sending a message to super to perform an initialization method defined somewhere farther up the inheritance hierarchy: .size.(id)initWithURL:(NSURL *)aURL error:(NSError **)errorPtr { self = [super init]. there is a possibility of returning meaningful information in the form of an NSError object returned by reference: . } return self. size. size. } The next example illustrates best practice where.width.
} The initWithName: method would. a Rectangle object must be initialized as an NSObject. For example. For example. and a Shape before it’s initialized as a Rectangle. it ensures that superclass variables are initialized before those declared in subclasses. B must also make sure that an init message successfully initializes B instances.CHAPTER 3 Allocating and Initializing Objects The message to super chains together initialization methods in all inherited classes. invoke the inherited method. a Graphic. as shown earlier. All Rights Reserved. Because it comes first. . Figure 3-2 includes B’s version of init: 52 Implementing an Initializer 2010-07-13 | © 2010 Apple Inc.init { return [self initWithName:"default"]. The easiest way to do that is to replace the inherited init method with a version that invokes initWithName:: . if class A defines an init method and its subclass B defines an initWithName: method.. in turn. as shown in Figure 3-1.
but not always). we have to make sure that the inherited init and initWithName: methods also work for instances of C. } For an instance of the C class. someone else may use it to produce incorrectly initialized instances of your class. It’s also the method that does most of the work. This can be done just by covering B’s initWithName: with a version that invokes initWithName:fromFile:. All Rights Reserved. If you leave an inherited method uncovered. It’s important to know the designated initializer when defining a subclass.CHAPTER 3 Allocating and Initializing Objects Figure 3-2 Covering an Inherited Initialization Model – init Class A – init Class B – initWithName: Covering inherited initialization methods makes the class you define more portable to other applications. the inherited init method invokes this new version of initWithName: which invokes initWithName:fromFile:. In addition to this method. The designated initializer is the method in each class that guarantees inherited instance variables are initialized (by sending a message to super to perform an inherited method). The Designated Initializer In the example given in “Coordinating Classes” (page 51). initWithName: would be the designated initializer for its class (class B). a subclass of B. and implement an initWithName:fromFile: method. It’s a Cocoa convention that the designated initializer is always the method that allows the most freedom to determine the character of a new instance (usually this is the one with the most arguments. For example. suppose we define class C.initWithName:(char *)string { return [self initWithName:string fromFile:NULL]. and the one that other initialization methods in the same class invoke. . The relationship between these methods is shown in Figure 3-3: The Designated Initializer 2010-07-13 | © 2010 Apple Inc. 53 .
through a message to super. B. and C are linked. .. 54 The Designated Initializer 2010-07-13 | © 2010 Apple. if (self) { . init or initWithName:? It can’t invoke init. being the designated initializer for the C class. Figure 3-4 shows how all the initialization methods in classes A. for two reasons: ■ Circularity would result (init invokes C’s initWithName:. Messages to self are shown on the left and messages to super are shown on the right. But which of B’s methods should it invoke. ■ Therefore. } General Principle: The designated initializer in a class must. It won’t be able to take advantage of the initialization code in B’s version of initWithName:. All Rights Reserved.initWithName:(char *)string fromFile:(char *)pathname { self = [super initWithName:string]. which invokes init again). initWithName:fromFile: must invoke initWithName:: . invoke the designated initializer in a superclass. The initWithName:fromFile: method. while other initialization methods are chained to designated initializers through messages to self. which invokes initWithName:fromFile:. Designated initializers are chained to each other through messages to super..
.. All Rights Reserved. NSString has the following methods (among others): + (id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc.. . it invokes B’s version of initWithName:. 55 . Therefore. Combining Allocation and Initialization In Cocoa. For example. when the receiver is an instance of the B class.. it invokes C’s version.. initialized instances of the class. some classes define creation methods that combine the two steps of allocating and initializing to return new. Similarly. Combining Allocation and Initialization 2010-07-13 | © 2010 Apple Inc. These methods are often referred to as convenience constructors and typically take the form + className. and when the receiver is an instance of the C class. + (id)stringWithFormat:(NSString *)format. NSArray defines the following class methods that combine allocation and initialization: + (id)array. where className is the name of the class.
as discussed in “Constraints and Conventions” (page 48). You must read Memory Management Programming Guide to understand the policy that applies to these convenience constructors. As mentioned in “The Returned Object” (page 47). In the following example. Methods that combine allocation and initialization are particularly valuable if the allocation must somehow be informed by the initialization. if the data for the initialization is taken from a file.. and the file might contain enough data to initialize more than one object.. see how many objects to allocate. It also makes sense to combine allocation and initialization in a single method if you want to avoid the step of blindly allocating memory for a new object that you might not use.CHAPTER 3 Allocating and Initializing Objects + (id)arrayWithObject:(id)anObject. the soloist method ensures that there’s no more than one instance of the Soloist class. it would be impossible to know how many objects to allocate until the file is opened. Notice that the return type of these methods is id.. put them in the List. and create a List object large enough to hold all the new objects. For example. when initWithName: is passed a name that’s already taken. . .. it might free the receiver and in its place return the object that was previously assigned the name. If the code that determines whether the receiver should be initialized is placed inside the method that does the allocation instead of inside init... strong typing is appropriate—there is no expectation that this method will be overridden. It would open the file. method might sometimes substitute another object for the receiver. 56 Combining Allocation and Initialization 2010-07-13 | © 2010 Apple Inc. you can avoid the step of allocating a new instance when one isn’t needed. It allocates and initializes a single shared instance: + (Soloist *)soloist { static Soloist *instance = nil.. that an object is allocated and freed immediately without ever being used. This is for the same reason as for initializer methods. you might implement a listFromFile: method that takes the name of the file as an argument. of course. } return instance. and finally return the List. + (id)arrayWithObjects:(id)firstObj. In this case. All Rights Reserved. Important: It is important to understand the memory management implications of using these methods if you do not use garbage collection (see “Memory Management” (page 15)). } Notice that in this case the return type is Soloist *. This means. if ( instance == nil ) { instance = [[self alloc] init]. It would then allocate and initialize the objects from data in the file. For example.. an init. Since this method returns a singleton share instance.. but which any class. they’re optional. . and perhaps many classes. For example. 57 .(void)mouseUp:(NSEvent *)theEvent. A protocol is simply a list of method declarations. these methods that report user actions on the mouse could be gathered into a protocol: . . unattached to a class definition. but the identity of the class that implements them is not of interest. Protocols free method declarations from dependency on the class hierarchy. Classes in unrelated branches of the inheritance hierarchy might be typed alike because they conform to the same protocol.CHAPTER 4 Protocols Protocols declare methods that can be implemented by any class. so they can be used in ways that classes and categories cannot. Protocols can play a significant role in object-oriented design. All Rights Reserved. Unlike class definitions and message expressions. It all depends on the task at hand. What is of interest is whether or not a particular class conforms to the protocol—whether it has implementations of the methods the protocol declares. but also on the basis of their similarity in conforming to the same protocol. declare methods that are independent of any specific class.(void)mouseDown:(NSEvent *)theEvent. Informal and formal protocols. Some Cocoa frameworks use them. on the other hand. Thus objects can be grouped into types not just on the basis of similarities due to the fact that they inherit from the same class. Cocoa software uses protocols heavily to support interprocess communication through Objective-C messages. Declaring Interfaces for Others to Implement 2010-07-13 | © 2010 Apple Inc. especially where a project is divided among many implementors or it incorporates objects developed in other projects. Protocols list methods that are (or may be) implemented somewhere. However. Any class that wanted to respond to mouse events could adopt the protocol and implement its methods. might implement. some don’t.(void)mouseDragged:(NSEvent *)theEvent. an Objective-C program doesn’t need to use protocols.
These declarations advertise the messages it can receive. Protocols provide a way for it to also advertise the messages it sends. for example.. . } Then. } Since.. However. you can’t import the interface file of the class that implements it. You need another way to declare the methods you use in messages but don’t implement. return YES.setAssistant:anObject { assistant = anObject. at the time you write this code. objects send messages as well as receive them. that you develop an object that asks for the assistance of another object by sending it helpOut: and other messages. Suppose. The sender simply imports the interface file of the receiver. an object might delegate responsibility for a certain operation to another object. You provide an assistant instance variable to record the outlet for these messages and define a companion method to set the instance variable. this communication is easily coordinated. if ( [assistant respondsToSelector:@selector(helpOut:)] ) { [assistant helpOut:self]. or it may on occasion simply need to ask another object for information. All Rights Reserved. A protocol serves this purpose. if you develop an object that sends messages to objects that aren’t yet defined—objects that you’re leaving for others to implement—you won’t have the receiver’s interface file. This method lets other objects register themselves as potential recipients of your object’s messages: . Communication works both ways.(BOOL)doWork { . If you develop the class of the sender and the class of the receiver as part of the same project (or if someone else has supplied you with the receiver and its interface file). For example. an object might be willing to notify other objects of its actions so that they can take whatever collateral measures might be required. you can look at its interface declaration (and the interface declarations of the classes it inherits from) to find what messages it responds to.CHAPTER 4 Protocols Methods for Others to Implement If you know the class of an object. a check is made to be sure that the receiver implements a method that can respond: . In some cases. It informs the compiler about methods the class uses and also informs other implementors of the methods they need to define to have their objects work with yours. } return NO. you can only declare a protocol for the helpOut: method. you can’t know what kind of object might register itself as the assistant. whenever a message is to be sent to the assistant. The imported file declares the method selectors the sender uses in the messages it sends. 58 Methods for Others to Implement 2010-07-13 | © 2010 Apple Inc.
of course. Protocols make anonymous objects possible. Each subclass may re-implement the methods in its own way. Instead. For example. those classes are often grouped under an abstract class that declares the methods they have in common. the supplier must be willing to identify at least some of the messages that it can respond to. However. users have no way of creating instances of the class. classes. But you don’t need to know how another application works or what its components are to communicate with it. ■ You can send Objective-C messages to remote objects—objects in other applications. An anonymous object may represent a service or handle a limited set of functions. This is done by associating the object with a list of methods declared in a protocol. (Remote Messaging (page 105) in the Objective-C Runtime Programming Guide.CHAPTER 4 Protocols Declaring Interfaces for Anonymous Objects A protocol can be used to declare the methods of an anonymous object. consider the following situations: ■ Someone who supplies a framework or a suite of objects for others to use can include objects that are not identified by a class name or an interface file. 59 . For it to be of any use at all. Declaring Interfaces for Anonymous Objects 2010-07-13 | © 2010 Apple Inc. Without a protocol. an object of unknown class.) Each application has its own structure. (Objects that play a fundamental role in defining an application’s architecture and objects that you must initialize before using are not good candidates for anonymity. It doesn’t have to disclose anything else about the object. and internal logic. but the inheritance hierarchy and the common declaration in the abstract class captures the essential similarity between the subclasses. As an outsider. especially where only one object of its kind is needed. there’s usually little point in discovering this extra information. the object itself reveals it at runtime. there would be no way to declare an interface to an object without identifying its class. The object returned by the method is an object without a class identity. the supplier must provide a ready-made instance. All Rights Reserved. discusses this possibility in more detail. Non-Hierarchical Similarities If more than one class implements a set of methods. but they are anonymous when the developer supplies them to someone else. Note: Even though the supplier of an anonymous object doesn’t reveal its class. The sending application doesn’t need to know the class of the object or use the class in its own design. at least not one the supplier is willing to reveal. A class message returns the anonymous object’s class.) Objects are not anonymous to their developers. All it needs is the protocol. all you need to know is what messages you can send (the protocol) and where to send them (the receiver). Lacking the name and class interface. An application that publishes one of its objects as a potential receiver of remote messages must also publish a protocol declaring the methods the object will use to respond to those messages. the information in the protocol is sufficient. Typically. a method in another class returns a usable object: id formatter = [receiver formattingService].
They live in their own namespace.(NSXMLElement *)XMLRepresentation. In this case. the NSMatrix object wouldn’t care what class a cell object belonged to. Classes that are unrelated in most respects might nevertheless need to implement some similar methods. Corresponding to the @optional modal keyword.initFromXMLRepresentation:(NSXMLElement *)XMLElement. the default is @required. For example.CHAPTER 4 Protocols However. the compiler can check for types based on protocols. For example. you might want to add support for creating XML representations of objects in your application and for initializing objects from an XML representation: . there is a @required keyword to formally denote the semantics of the default behavior. and objects can introspect at runtime to report whether or not they conform to a protocol. protocol names don’t have global visibility. Formal protocols are supported by the language and the runtime system. the NSMatrix object could require objects representing cells to have methods that can respond to a particular set of messages (a type based on protocol). Optional Protocol Methods Protocol methods can be marked as optional using the @optional keyword. This limited similarity may not justify a hierarchical relationship. You can use @optional and @required to partition your protocol into sections as you see fit. rather than by their class. Declaring a Protocol You declare formal protocols with the @protocol directive: @protocol ProtocolName method declarations @end For example. These methods could be grouped into a protocol and the similarity between implementing classes accounted for by noting that they all conform to the same protocol. For example. . . you could declare an XML representation protocol like this: @protocol MyXMLSupport . The matrix could require each of these objects to be a kind of NSCell (a type based on class) and rely on the fact that all objects that inherit from the NSCell class have the methods needed to respond to NSMatrix messages. All Rights Reserved. Alternatively.initFromXMLRepresentation:(NSXMLElement *)xmlString. 60 Formal Protocols 2010-07-13 | © 2010 Apple Inc. sometimes it’s not possible to group common methods in an abstract class. an NSMatrix instance must communicate with the objects that represent its cells. If you do not specify any keyword. Objects can be typed by this similarity (the protocols they conform to). @end Unlike class names.(NSXMLElement *)XMLRepresentation. Formal Protocols The Objective-C language provides a way to formally declare a list of methods (including declared properties) as a protocol. . just that it implemented the methods.
such as for a delegate. @required . Informal Protocols In addition to formal protocols. but (on Mac OS X v10. To get these benefits.initFromXMLRepresentation:(NSXMLElement *)XMLElement.(void)anotherOptionalMethod.(void)anotherRequiredMethod. Because all classes inherit from the root class. Being informal.5. you can also define an informal protocol by grouping the methods in a category declaration: @interface NSObject ( MyXMLSupport ) . classes that implement the protocol declare the methods again in their own interface files and define them along with other methods in their implementation files. An informal protocol may be useful when all the methods are optional. but there is little reason to do so.(NSXMLElement *)XMLRepresentation. All Rights Reserved. An informal protocol bends the rules of category declarations to list a group of methods but not associate them with any particular class or implementation. .5 and later) it is typically better to use a formal protocol with optional methods. @end Note: In Mac OS X v10.6 and later. . protocols may not include optional declared properties. since that broadly associates the method names with any class that inherits from NSObject. 61 . a category interface doesn’t have a corresponding implementation. This constraint is removed in Mac OS X v10. you must use a formal protocol. (It would also be possible to declare an informal protocol as a category of another class to limit it to a certain branch of the inheritance hierarchy. protocols declared in categories don’t receive much language support.CHAPTER 4 Protocols @protocol MyProtocol . Informal Protocols 2010-07-13 | © 2010 Apple Inc. the methods aren’t restricted to any part of the inheritance hierarchy. Instead. There’s no type checking at compile time nor a check at runtime to see whether an object conforms to the protocol. @optional .(void)requiredMethod. @end Informal protocols are typically declared as categories of the NSObject class.(void)anOptionalMethod.) When used to declare a protocol.
62 Protocol Objects 2010-07-13 | © 2010 Apple Inc. except that here it has a set of trailing parentheses. Source code that deals with a protocol (other than to use it in a type specification) must refer to the Protocol object. formal protocols are represented by a special data type—instances of the Protocol class. The methods declared in the adopted protocol are not declared elsewhere in the class or category interface. otherwise the compiler issues a warning. The superclass declaration assigns it inherited methods. in addition to any it might have declared itself. Source code can refer to a Protocol object using the @protocol() directive—the same directive that declares a protocol. A class or category that adopts a protocol must import the header file where the protocol is declared. This is the only way that source code can conjure up a Protocol object. The parentheses enclose the protocol name: Protocol *myXMLSupportProtocol = @protocol(MyXMLSupport). @interface Formatter : NSObject < Formatting. They both declare methods. names in the protocol list are separated by commas. but only if the protocol is also: ■ ■ Adopted by a class. In many ways. the protocol assigns it methods declared in the protocol list. They’re not allocated and initialized in program source code. Adopting a Protocol Adopting a protocol is similar in some ways to declaring a superclass. The compiler creates a Protocol object for each protocol declaration it encounters. The Formatter class above would define all the required methods declared in the two protocols it adopts. Unlike a class name. protocols are similar to class definitions. Both assign methods to the class. or Referred to somewhere in source code (using @protocol()) Protocols that are declared but not used (except for type checking as described below) aren’t represented by Protocol objects at runtime. Protocol objects are created automatically from the definitions and declarations found in source code and are used by the runtime system.CHAPTER 4 Protocols Protocol Objects Just as classes are represented at runtime by class objects and methods by selector codes. . All Rights Reserved. Like class objects. a protocol name doesn’t designate the object—except inside @protocol(). and at runtime they’re both represented by objects—classes by class objects and protocols by Protocol objects. Prettifying > A class or category that adopts a protocol must implement all the required methods the protocol declares. conformsToProtocol: test is like the respondsToSelector: test for a single method. the following class declaration adopts the Formatting and Prettifying protocols. conformsToProtocol: can be more efficient than respondsToSelector:. except that it tests whether a protocol has been adopted (and presumably all the methods it declares implemented) rather than just whether one particular method has been implemented. except that it tests for a type based on a protocol rather than a type based on the inheritance hierarchy.CHAPTER 4 Protocols It’s possible for a class to simply adopt protocols and declare no other methods. saying that a class or an instance conforms to a protocol is equivalent to saying that it has in its repertoire all the methods the protocol declares. Protocols thus offer the possibility of another level of type checking by the compiler. if Formatter is an abstract class. id <MyXMLSupport> anObject. For example.(id <Formatting>)formattingService. but declares no instance variables or methods of its own: @interface Formatter : NSObject < Formatting. In a type declaration. 63 . All Rights Reserved. this syntax permits the compiler to test for a type based on conformance to a protocol. one that’s more abstract since it’s not tied to particular implementations. if ( ! [receiver conformsToProtocol:@protocol(MyXMLSupport)] ) { // Object does not conform to MyXMLSupport protocol // If you are expecting receiver to implement methods declared in the // MyXMLSupport protocol. It’s possible to check whether an object conforms to a protocol by sending it a conformsToProtocol: message. An instance of a class is said to conform to the same set of protocols its class conforms to. Type Checking Type declarations for objects can be extended to include formal protocols. Because it checks for all the methods in the protocol. Prettifying > @end Conforming to a Protocol A class is said to conform to a formal protocol if it adopts the protocol or inherits from another class that adopts it. protocol names are listed between angle brackets after the type name: . this is probably an error } (Note that there is also a class method with the same name—conformsToProtocol:. The conformsToProtocol: test is also like the isKindOfClass: test. For example. this declaration Conforming to a Protocol 2010-07-13 | © 2010 Apple Inc. Since a class must implement all the required methods declared in the protocols it adopts. Just as static typing permits the compiler to test for a type based on the class hierarchy.
as mentioned earlier. In each case. just as only instances can be statically typed to a class. If an incorporated protocol incorporates still other protocols.. All Rights Reserved. groups all objects that inherit from Formatter into a type and permits the compiler to check assignments against that type. the type groups similar objects—either because they share a common inheritance. In addition. Similarly. A class can conform to an incorporated protocol by either: ■ ■ Implementing the methods the protocol declares. and conformsToProtocol: messages if ( [anotherObject conformsToProtocol:@protocol(Paging)] ) . regardless of their positions in the class hierarchy. if the Paging protocol incorporates the Formatting protocol. at runtime. Protocols can’t be used to type class objects.) Protocols Within Protocols One protocol can incorporate other protocols using the same syntax that classes use to adopt a protocol: @protocol ProtocolName < protocol list > All the protocols listed between angle brackets are considered part of the ProtocolName protocol. the class must also conform to them. For example. 64 Protocols Within Protocols 2010-07-13 | © 2010 Apple Inc. need to mention only the Paging protocol to test for conformance to Formatting as well. this declaration. Only instances can be statically typed to a protocol.. id <Formatting> anObject. groups all objects that conform to the Formatting protocol into a type. The two types can be combined in a single declaration: Formatter <Formatting> *anObject. Type declarations id <Paging> someObject. . The compiler can make sure only objects that conform to the protocol are assigned to the type.CHAPTER 4 Protocols Formatter *anObject. (However. or because they converge on a common set of methods. both classes and instances will respond to a conformsToProtocol: message. it must conform to any protocols the adopted protocol incorporates. @protocol Paging < Formatting > any object that conforms to the Paging protocol also conforms to Formatting. When a class adopts a protocol. or Inheriting from a class that adopts the protocol and implements the methods. it must implement the required methods the protocol declares.
h" @protocol A . On the other hand. that the Pager class adopts the Paging protocol. 65 . All Rights Reserved. Referring to Other Protocols 2010-07-13 | © 2010 Apple Inc.foo:(id <B>)anObject. @end where protocol B is declared like this: #import "A. Note that a class can conform to a protocol without formally adopting it simply by implementing the methods declared in the protocol.bar:(id <A>)anObject. If Pager is a subclass of NSObject. you occasionally find yourself writing code that looks like this: #import "B. for example. circularity results and neither file will compile correctly. The following code excerpt illustrates how you would do this: @protocol B. @end In such a situation.h" @protocol B . It doesn’t import the interface file where protocol B is defined. but not those declared in Formatting. you must use the @protocol directive to make a forward reference to the needed protocol instead of importing the interface file where the protocol is defined. To break this recursive cycle. if Pager is a subclass of Formatter (a class that independently adopts the Formatting protocol). @end Note that using the @protocol directive in this manner simply informs the compiler that “B” is a protocol to be defined later.CHAPTER 4 Protocols Suppose. @protocol A . including those declared in the incorporated Formatting protocol.foo:(id <B>)anObject. Pager inherits conformance to the Formatting protocol from Formatter. Referring to Other Protocols When working on complex applications. @interface Pager : NSObject < Paging > it must implement all the Paging methods. @interface Pager : Formatter < Paging > it must implement all the methods declared in the Paging protocol proper. It adopts the Formatting protocol along with Paging.
CHAPTER 4 Protocols 66 Referring to Other Protocols 2010-07-13 | © 2010 Apple Inc. All Rights Reserved. .
By using accessor methods. 67 .CHAPTER 5 Declared Properties The Objective-C “declared properties” feature provides a simple way to declare and implement an object’s accessor methods. Overview There are two aspects to this language feature: the syntactic elements you use to specify and optionally synthesize declared properties. @property can also appear in the declaration of a protocol or category. Moreover. its declaration and its implementation. Overview 2010-07-13 | © 2010 Apple Inc. @property can appear anywhere in the method declaration list found in the @interface of a class. so the compiler can detect use of undeclared properties. explicit specification of how the accessor methods behave. All Rights Reserved.. you adhere to the principle of encapsulation (see “Mechanisms Of Abstraction” in Object-Oriented Programming with Objective-C > The Object Model). Although using accessor methods has significant advantages. Property Declaration A property declaration begins with the keyword @property. You typically access an object’s properties (in the sense of its attributes and relationships) through a pair of accessor (getter/setter) methods.). according to the specification you provide in the declaration. This means you have less code to write and maintain. Properties are represented syntactically as identifiers and are scoped. The compiler can synthesize accessor methods for you. ■ Property Declaration and Implementation There are two parts to a declared property.
properties are scoped to their enclosing interface declaration. The following attributes allow you to specify custom names instead.(void)setValue:(float)newValue.CHAPTER 5 Declared Properties @property(attributes) type name. each property has a type specification and a name. Property Declaration Attributes You can decorate a property with attributes by using the form @property(attribute [. If you implement the accessor method(s) yourself. if you specify copy you must make sure that you do copy the input value in the setter method). @end You can think of a property declaration as being equivalent to declaring two accessor methods. Thus @property float value. the property attributes apply to all of the named properties. . Listing 5-1 Declaring a simple property @interface MyClass : NSObject { float value. . . setFoo:.. @property declares a property. attribute2. For property declarations that use a comma delimited list of variable names.(float)value. Like methods. given a property “foo” the accessors would be foo and . An optional parenthesized set of attributes provides additional details about the storage semantics and other behaviors of the property—see “Property Declaration Attributes” (page 68) for possible values. All Rights Reserved. Like any other Objective-C type. is equivalent to: . you should ensure that it matches the specification (for example. } @property float value. Accessor Method Names The default names for the getter and setter methods associated with a property are propertyName and setPropertyName: respectively—for example.]). however. Listing 5-1 illustrates the declaration of a simple property. getter=getterName Specifies the name of the get accessor for the property. the code it generates matches the specification given by the keywords. The getter must return a type matching the property’s type and take no arguments. 68 Property Declaration and Implementation 2010-07-13 | © 2010 Apple Inc. If you use the @synthesize directive to tell the compiler to create the accessor method(s). provides additional information about how the accessor methods are implemented (as described in “Property Declaration Attributes” (page 68)).. A property declaration. They are both optional and may appear with any other attribute (except for readonly in the case of setter=).
the getter and setter methods are synthesized. For further discussion.6 and later. retain Specifies that retain should be invoked on the object upon assignment. assign Specifies that the setter uses simple assignment. This is the default.) The previous value is sent a release message. (The default is assign. They are mutually exclusive. readwrite Indicates that the property should be treated as read/write. only a getter method is required in the @implementation. If you specify that a property is readonly then also specify a setter with setter=. This attribute is valid only for object types. Property Declaration and Implementation 2010-07-13 | © 2010 Apple Inc. They are mutually exclusive. Both a getter and setter method will be required in the @implementation. this attribute is valid only for Objective-C object types (so you cannot specify retain for Core Foundation objects—see “Core Foundation” (page 74)). You typically use this attribute for scalar types such as NSInteger and CGRect. only the getter method is synthesized. 69 . The copy is made by invoking the copy method. Setter Semantics These attributes specify the semantics of a set accessor.) The previous value is sent a release message. (The default is assign. as illustrated in this example: @property(retain) __attribute__((NSObject)) CFDictionaryRef myDictionary.CHAPTER 5 Declared Properties setter=setterName Specifies the name of the set accessor for the property. readonly Indicates that the property is read-only. All Rights Reserved. see “Copy” (page 73). Typically you should specify accessor method names that are key-value coding compliant (see Key-Value Coding Programming Guide)—a common reason for using the getter decorator is to adhere to the isPropertyName convention for Boolean values. or (in a reference-counted environment) for objects you don’t own such as delegates. copy Specifies that a copy of the object should be used for assignment. you will get a compiler warning. Writability These attributes specify whether or not a property has an associated set accessor. This is the default. if you attempt to assign a value using the dot syntax. you can use the __attribute__ keyword to specify that a Core Foundation property should be treated like an Objective-C object for memory management. you get a compiler error. retain and assign are effectively the same in a garbage-collected environment. The setter method must take a single argument of a type matching the property’s type and must return void. Prior to Mac OS X v10. If you use @synthesize in the implementation block. If you specify readonly. If you use @synthesize in the implementation block. which must implement the NSCopying protocol. Moreover.6. On Mac OS X v10.
if you don’t specify any of assign.) nonatomic Specifies that accessors are non-atomic. to preserve encapsulation you often want to make a private copy of the object. accessors are atomic. if the property type can be copied. IBOutlet is not. retain or copy—otherwise you will get a compiler warning. (This encourages you to think about what memory management behavior you want and type it explicitly. @property CGFloat y __attribute__((. Atomicity This attribute specifies that accessor methods are not atomic. you don't get a warning if you use the default (that is.)). you can use the IBOutlet identifier: @property (nonatomic. however. Markup and Deprecation Properties support the full range of C style decorators. All Rights Reserved. you can use the storage modifiers __weak and __strong in a property’s declaration: 70 Property Declaration and Implementation 2010-07-13 | © 2010 Apple Inc. If you specify nonatomic. retain or copy) unless the property's type is a class that conforms to NSCopying. The default is usually what you want. By default. then in a reference counted environment a synthesized get accessor for an object property uses a lock and retains and autoreleases the returned value—the implementation will be similar to the following: [_internal lock].CHAPTER 5 Declared Properties Different constraints apply depending on whether or not you use garbage collection: ■ If you do not use garbage collection. If you use garbage collection. Properties can be deprecated and support __attribute__ style markup. If you want to specify that a property is an Interface Builder outlet. retain) IBOutlet NSButton *myButton. If you do not specify nonatomic. [_internal unlock]. as illustrated in the following example: @property CGFloat x AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4. a formal part of the list of attributes. // lock using an object-level lock id result = [[value retain] autorelease]. ■ If you use garbage collection. see “Performance and Threading” (page 77).. . for object properties you must explicitly specify one of assign. though. For more details.. then a synthesized accessor for an object property simply returns the value directly. the value returned from the getter or set via the setter is always fully retrieved or set regardless of what other threads are executing concurrently. Properties are atomic by default so that synthesized accessors provide robust access to properties in a multi-threaded environment—that is.) To decide which you should choose. you need to understand Cocoa’s memory management policy (see Memory Management Programming Guide). return result. (There is no keyword to denote atomic.
instance variables must already be declared in the @interface block of the current class. If you do not. @synthesize can only use an instance variable from the current class. @end You can use the form property=ivar to indicate that a particular instance variable should be used for the property. All Rights Reserved. the compiler will generate a warning. it is used—otherwise. Property Implementation Directives You can use the @synthesize and @dynamic directives in @implementation blocks to trigger specific compiler actions. @end @implementation MyClass @synthesize value. This specifies that the accessor methods for firstName. and age should be synthesized and that the property age is represented by the instance variable yearsOld. you get a compiler error. age = yearsOld. If an instance variable of the same name already exists. not a superclass.CHAPTER 5 Declared Properties @property (nonatomic. for example: @synthesize firstName. lastName. There are differences in the behavior that depend on the runtime (see also “Runtime Difference” (page 78)): ■ For the legacy runtimes. Important: If you do not specify either @synthesize or @dynamic for a particular property. you must provide a getter and setter (or just a getter in the case of a readonly property) method implementation for that property. 71 . instance variables are synthesized as needed. @synthesize You use the @synthesize keyword to tell the compiler that it should synthesize the setter and/or getter methods for the property if you do not supply them within the @implementation block. readwrite) NSString *value. } @property(copy. it is used. Note that neither is required for any given @property declaration. If an instance variable of the same name and compatible type as the property exists. retain) __weak Link *parent. Whether or not you specify the name of the instance variable. Listing 5-2 Using @synthesize @interface MyClass : NSObject { NSString *value. but again they are not a formal part of the list of attributes. lastName. ■ Property Declaration and Implementation 2010-07-13 | © 2010 Apple Inc. For the modern runtimes (see Runtime Versions and Platforms in Objective-C Runtime Programming Guide). Other aspects of the synthesized methods are determined by the optional attributes (see “Property Declaration Attributes” (page 68)).
you can redeclare it as readwrite in a class extension (see “Extensions” (page 81)). or a subclass—see “Subclassing with Properties” (page 76). at runtime. It suppresses the warnings that the compiler would otherwise generate if it can’t find suitable implementations.CHAPTER 5 Declared Properties @dynamic You use the @dynamic keyword to tell the compiler that you will fulfill the API contract implied by a property either by providing method implementations directly or at runtime using other mechanisms such as dynamic loading of code or dynamic method resolution. If you declare a property in one class as readonly. readwrite) you must repeat its attributes in whole in the subclasses. see “Core Foundation” (page 74). the property’s attributes must be repeated in whole. Property Re-declaration You can re-declare a property in a subclass. You should only use it if you know that the methods will be available at runtime. You therefore typically declare properties for the attributes and relationships. A managed object class has a corresponding schema that defines attributes and relationships for the class. The example shown in Listing 5-3 illustrates using @dynamic with a subclass of NSManagedObject. 72 Using Properties 2010-07-13 | © 2010 Apple Inc. @end NSManagedObject is provided by the Core Data framework. the compiler would generate a warning. The same holds true for a property declared in a category or protocol—while the property may be redeclared in a category or protocol. but you don’t have to implement the accessor methods yourself. The ability to redeclare a read-only property as read/write enables two common implementation patterns: a mutable subclass of an immutable class (NSString. however. but (with the exception of readonly vs. or “plain old data” (POD) type (see C++ Language Note: POD Types). In the case of a class extension redeclaration. Core Foundation data type. Using Properties Supported Types You can declare a property for any Objective-C class. All Rights Reserved. the fact that the property was redeclared prior to any @synthesize statement will cause the setter to be synthesized. retain) NSString *value. a protocol. @end @implementation MyClass @dynamic value. however. If you just declared the property without providing any implementation. and shouldn’t ask the compiler to do so. For constraints on using Core Foundation types. . Listing 5-3 Using @dynamic with NSManagedObject @interface MyClass : NSManagedObject { } @property(nonatomic. the Core Data framework generates accessor methods for these as necessary. Using @dynamic suppresses the warning.
@end Copy If you use the copy declaration attribute. @interface MyClass : NSObject { NSMutableArray *myArray. The following example shows using a class extension to provide a property that is declared as read-only in the public header but is redeclared privately as read/write. In this situation.(void)setMyArray:(NSMutableArray *)newArray { Using Properties 2010-07-13 | © 2010 Apple Inc. an instance of NSMutableString) and you want to ensure that your object has its own private immutable copy. All Rights Reserved. you specify that a value is copied during assignment. string = [newString copy]. @end // private implementation file @interface MyObject () @property (readwrite. and NSDictionary are all examples) and a property that has public API that is readonly but a private readwrite implementation internal to the class. } @property (readonly. copy) NSString *string. the synthesized method uses the copy method. copy) NSString *language. // public header file @interface MyObject : NSObject { NSString *language. 73 . as illustrated in the following example.CHAPTER 5 Declared Properties NSArray. This is useful for attributes such as string objects where there is a possibility that the new value passed in a setter may be mutable (for example. copy) NSString *language. If you synthesize the corresponding accessor. if you declare a property as follows: @property (nonatomic. you have to provide your own implementation of the setter method. For example. Typically you want such collections to be mutable. but the copy method returns an immutable version of the collection. @end @implementation MyClass @synthesize myArray. } } Although this works well for strings. it may present a problem if the attribute is a collection such as an array or a set. } @property (nonatomic. @end @implementation MyObject @synthesize language. . copy) NSMutableArray *myArray. then the synthesized setter method is similar to the following: -(void)setString:(NSString *)newString { if (string != newString) { [string release].
myArray = [newArray mutableCopy]. and those marked assign are not released. however. you declare a property whose type is a CFType and synthesize the accessors as illustrated in the following example: @interface MyClass : NSObject { CGImageRef myImage. you cannot access the instance variable directly. This is typically incorrect. } If you are using the modern runtime and synthesizing the instance variable. so you should not synthesize the methods. when you synthesize a property. the compiler only creates any absent accessor methods. There is no direct interaction with the dealloc method—properties are not automatically released for you. prior to Mac OS X v10. } } @end dealloc Declared properties fundamentally take the place of accessor method declarations. } @property(readwrite) CGImageRef myImage. provide a useful way to cross-check the implementation of your dealloc method: you can look for all the property declarations in your header file and make sure that object properties not marked assign are released.(void)dealloc { [property release]. Note: Typically in a dealloc method you should release object instance variables directly (rather than invoking a set accessor and passing nil as the parameter).CHAPTER 5 Declared Properties if (myArray != newArray) { [myArray release]. as illustrated in this example: .(void)dealloc { [self setProperty:nil]. however. you should implement them yourself. All Rights Reserved. [super dealloc]. If. 74 . @end then in a reference counted environment the generated set accessor will simply assign the new value to the instance variable (the new value is not retained and the old value is not released). so you must invoke the accessor method: . } Core Foundation As noted in “Property Declaration Attributes” (page 68). @end @implementation MyClass @synthesize myImage. [super dealloc]. Using Properties 2010-07-13 | © 2010 Apple Inc. therefore. Declared properties do.6 you cannot specify the retain attribute for non-object types.
CHAPTER 5 Declared Properties In a garbage collected environment. name is synthesized. CGFloat gratuitousFloat.. then the accessors are synthesized appropriately—the image will not be CFRetain’d. creationTimestamp and next are synthesized but use existing instance variables with different names. but the setter will trigger a write barrier. __strong CGImageRef myImage. nameAndAge does not have a dynamic directive. MyClass also declares several other properties. @property(readonly.. @property CGImageRef myImage. // Synthesizing 'name' is an error in legacy runtimes. it only requires a getter) with a specified name (nameAndAgeAsString). @property CGFloat gratuitousFloat.. @property(copy) NSString *name. ■ ■ gratuitousFloat has a dynamic directive—it is supported using direct method implementations. if the variable is declared __strong: . MyClass adopts the Link protocol so implicitly also declares the property next. Using Properties 2010-07-13 | © 2010 Apple Inc. @end @implementation MyClass @synthesize creationTimestamp = intervalSinceReferenceDate. name. it is supported using a direct method implementation (since it is read-only. Example The following example illustrates the use of properties in several different ways: ■ ■ The Link protocol declares a property. but this is the default value. next. All Rights Reserved. id <Link> nextLink. } @property(readonly) NSTimeInterval creationTimestamp. Listing 5-4 Declaring properties for a class @protocol Link @property id <Link> next. getter=nameAndAgeAsString) NSString *nameAndAge. @end @interface MyClass : NSObject <Link> { NSTimeInterval intervalSinceReferenceDate. .. 75 . and uses instance variable synthesis (recall that instance variable synthesis is not ■ ■ supported using the legacy runtime—see “Property Implementation Directives” (page 71) and “Runtime Difference” (page 78)).
@end @implementation MyInteger @synthesize value. [name release]. } @end Subclassing with Properties You can override a readonly property to make it writable.CHAPTER 5 Declared Properties // in modern runtimes. } . All Rights Reserved. value: @interface MyInteger : NSObject { NSInteger value. . } . [NSDate timeIntervalSinceReferenceDate] intervalSinceReferenceDate]. } return self.(NSString *)nameAndAgeAsString { return [NSString stringWithFormat:@"%@ (%fs)". } @property(readonly) NSInteger value.(void)dealloc { [nextLink release]. [super dealloc]. if (self) { intervalSinceReferenceDate = [NSDate timeIntervalSinceReferenceDate]. @synthesize next = nextLink. the instance variable is synthesized. .(CGFloat)gratuitousFloat { return gratuitousFloat.(void)setGratuitousFloat:(CGFloat)aValue { gratuitousFloat = aValue. you could define a class MyInteger with a readonly property. // This directive is not strictly necessary. @dynamic gratuitousFloat. For example. } . } . @end 76 Subclassing with Properties 2010-07-13 | © 2010 Apple Inc. [self name].(id)init { self = [super init]. // Uses instance variable "nextLink" for storage.
most synthesized methods are atomic without incurring this overhead. MyMutableInteger. as illustrated below (the implementation may not be exactly as shown): // assign property = newValue. and nonatomic. All Rights Reserved. assign. the method implementations generated by the compiler depend on the specification you supply. which redefines the property to make it writable: @interface MyMutableInteger : MyInteger @property(readwrite) NSInteger value. In a garbage collected environment. this may have a significant impact on performance. the fact that you declared a property has no effect on its efficiency or thread safety. By default. guaranteeing atomic behavior requires the use of a lock. as illustrated in “Atomicity” (page 70). In a reference counted environment. } // copy if (property != newValue) { [property release].CHAPTER 5 Declared Properties You could then implement a subclass. The declaration attributes that affect performance and threading are retain. copy. property = [newValue retain]. } @end Performance and Threading If you supply your own method implementation. // retain if (property != newValue) { [property release]. If such accessors are invoked frequently. property = [newValue copy]. the synthesized accessors are atomic. Although “atomic” means that access to the property is thread-safe. The first three of these affect only the implementation of the assignment part of the set method. It is important to understand that the goal of the atomic implementation is to provide robust accessors—it does not guarantee correctness of your code. 77 . simply making all the properties in your class atomic does not mean that your class or more generally your object graph is “thread safe”—thread safety cannot be expressed at the level of individual accessor methods. moreover a returned object is retained and autoreleased. Performance and Threading 2010-07-13 | © 2010 Apple Inc. If you use synthesized properties.(void)setValue:(NSInteger)newX { value = newX. see Threading Programming Guide. . For more about multi-threading. @end @implementation MyMutableInteger @dynamic value. } The effect of the nonatomic attribute depends on the environment.
@property float differentName. @end @implementation MyClass @synthesize sameName. if you do not provide an instance variable. } @property float sameName. float otherName. For example. There is one key difference: the modern runtime supports instance variable synthesis whereas the legacy runtime does not. @property float noDeclaredIvar. With the modern runtime. @end the compiler for the legacy runtime would generate an error at @synthesize noDeclaredIvar. All Rights Reserved.CHAPTER 5 Declared Properties Runtime Difference In general the behavior of properties is identical on all runtimes (see Runtime Versions and Platforms in Objective-C Runtime Programming Guide). you must either provide an instance variable with the same name and compatible type of the property or specify another existing instance variable in the @synthesize statement. the compiler adds one for you. . given the following class declaration and implementation: @interface MyClass : NSObject { float sameName. @synthesize differentName=otherName. For @synthesize to work in the legacy runtime. @synthesize noDeclaredIvar. whereas the compiler for the modern runtime would add an instance variable to represent noDeclaredIvar. 78 Runtime Difference 2010-07-13 | © 2010 Apple Inc.. nil.) To break all associations for an object.h> int main (int argc. Breaking Associations To break an association. // (2) overview invalid At point (1). the string overview is still valid because the OBJC_ASSOCIATION_RETAIN policy specifies that the array retains the associated object. however. the policy isn’t actually important. you could break the association between the array and the string overview using the following line of code: objc_setAssociatedObject(array.” Complete Example The following program combines the code samples from the preceding sections.h> #import <objc/runtime. you generate a runtime exception.CHAPTER 7 Associative References objc_setAssociatedObject(array. &overviewKey). however (at point 2). #import <Foundation/Foundation. In general. You only use this function if you need to restore an object to “pristine condition. Continuing the example shown in Listing 7-1 (page 83). passing nil as the value. OBJC_ASSOCIATION_ASSIGN). [overview release]. Retrieving Associated Objects You retrieve an associated object using the Objective-C runtime function objc_getAssociatedObject. overview is released and so in this case also deallocated. static char overviewKey. 84 Retrieving Associated Objects 2010-07-13 | © 2010 Apple Inc. const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]. OBJC_ASSOCIATION_RETAIN). If you try to. overview. (Given that the associated object is being set to nil. for example. When the array is deallocated. Continuing the example shown in Listing 7-1 (page 83). you are discouraged from using this since this breaks all associations for all clients. you typically use objc_setAssociatedObject. All Rights Reserved. you could retrieve the overview from the array using the following line of code: NSString *associatedObject = (NSString *)objc_getAssociatedObject(array. you can use objc_removeAssociatedObjects. &overviewKey. . log the value of overview. // (1) overview valid [array release].
objc_setAssociatedObject(array. use initWithFormat: to ensure we get a // deallocatable string NSString *overview = [[NSString alloc] initWithFormat:@"%@". [overview release]. associatedObject). } Complete Example 2010-07-13 | © 2010 Apple Inc. nil]. nil. @"Three". @"Two". OBJC_ASSOCIATION_RETAIN). [pool drain]. &overviewKey). NSLog(@"associatedObject: %@". [array release]. 85 . NSString *associatedObject = (NSString *)objc_getAssociatedObject(array. objc_setAssociatedObject(array. return 0.CHAPTER 7 Associative References NSArray *array = [[NSArray alloc] initWithObjects:@"One". @"First three numbers"]. OBJC_ASSOCIATION_ASSIGN). overview. &overviewKey. &overviewKey. All Rights Reserved. // For the purposes of illustration.
.CHAPTER 7 Associative References 86 Complete Example 2010-07-13 | © 2010 Apple Inc. All Rights Reserved.
The Cocoa collection classes—NSArray. you can perform multiple enumerations concurrently. For other classes. NSDictionary enumerates its keys. If the loop is terminated early. as does NSEnumerator. The for…in Feature Fast enumeration is a language feature that allows you to enumerate over the contents of a collection. and NSManagedObjectModel enumerates its entities. All Rights Reserved. The syntax is concise. NSDictionary. using NSEnumerator directly. the corresponding documentation should make clear what property is iterated over—for example. for example. The iterating variable is set to each item in the returned object in turn. There are several advantages to using fast enumeration: ■ ■ ■ The enumeration is considerably more efficient than. Since mutation of the object during iteration is forbidden. and the code defined by statements is executed. the iterating variable is left pointing to the last iteration item. and NSSet—adopt this protocol. expression yields an object that conforms to the NSFastEnumeration protocol (see “Adopting Fast Enumeration” (page 87)). 87 . The syntax is defined as follows: for ( Type newVariable in expression ) { statements } or Type existingItem. It should be obvious that in the cases of NSArray and NSSet the enumeration is over their contents. The iterating variable is set to nil when the loop ends by exhausting the source pool of objects. Enumeration is “safe”—the enumerator has a mutation guard so that if you attempt to modify the collection during enumeration.CHAPTER 8 Fast Enumeration Fast enumeration is a language feature that allows you to efficiently and safely enumerate over the contents of a collection using a concise syntax. The for…in Feature 2010-07-13 | © 2010 Apple Inc. Adopting Fast Enumeration Any class whose instances provide access to a collection of other objects can adopt the NSFastEnumeration protocol. NSDictionary and the Core Data class NSManagedObjectModel provide support for fast enumeration. an exception is raised. for ( existingItem in expression ) { statements } In both cases.
@"Two". NSArray *array = /* assume this exists */. for (key in dictionary) { NSLog(@"English: %@. nil]. . as illustrated in the following example: NSArray *array = [NSArray arrayWithObjects: @"One". NSString *key. NSUInteger index = 0. } In other respects. nil]. element). // next = "Two" For collections or enumerators that have a well-defined order—such as NSArray or NSEnumerator instance derived from an array—the enumeration proceeds in that order. @"four". } You can also use NSEnumerator objects with fast enumeration. NSArray *array = [NSArray arrayWithObjects: @"One". @"Three". @"quinque". @"Four". so simply counting iterations will give you the proper index into the collection if you need it. element). for (id element in array) { NSLog(@"Element at index %u is: %@". @"six". @"sex". for (NSString *element in array) { NSLog(@"element: %@".CHAPTER 8 Fast Enumeration Using Fast Enumeration The following code example illustrates using fast enumeration with NSArray and NSDictionary objects. } NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys: @"quattuor". @"Three". index++. You can use break to interrupt the iteration. for (NSString *element in enumerator) { if ([element isEqualToString:@"Three"]) { break. nil]. @"Four". NSEnumerator *enumerator = [array reverseObjectEnumerator]. for (id element in array) { if (/* some test for element */) { // statements that apply only to elements passing test } 88 Using Fast Enumeration 2010-07-13 | © 2010 Apple Inc. the feature behaves like a standard for loop. } } NSString *next = [enumerator nextObject]. Latin: %@". @"Two". and if you want to skip elements you can use a nested conditional statement as shown in the following example: NSArray *array = /* assume this exists */. key. All Rights Reserved. [dictionary objectForKey:key]). index. @"five".
All Rights Reserved. you could do so as shown in this example: NSArray *array = /* assume this exists */. index. } if (++index >= 6) { break. NSUInteger index = 0. } } Using Fast Enumeration 2010-07-13 | © 2010 Apple Inc.CHAPTER 8 Fast Enumeration } If you want to skip the first element then process no more than five further elements. element). for (id element in array) { if (index != 0) { NSLog(@"Element at index %u is: %@". 89 .
.CHAPTER 8 Fast Enumeration 90 Using Fast Enumeration 2010-07-13 | © 2010 Apple Inc. All Rights Reserved.
Objective-C allows objects to be statically typed with a class name rather than generically typed as id. any object variable can be of type id no matter what the object’s class is. Default Dynamic Behavior By design. but there’s a price to pay. Objective-C objects are dynamic entities. As many decisions about them as possible are pushed from compile time to runtime: ■ ■ The memory for objects is dynamically allocated at runtime by class methods that create new instances. The exceptionally rare case where bypassing Objective-C's dynamism might be warranted can be proven by use of analysis tools like Shark or Instruments. thisObject can only be a Rectangle of some kind. Static Typing If a pointer to a class name is used in place of id in an object declaration. Statically typed objects have the same internal data structures as objects declared to be ids. Rectangle *thisObject. It also lets you turn some of its object-oriented features off in order to shift operations from runtime back to compile time. typically incurring an insignificant amount of overhead compared to actual work performed. the compiler restricts the value of the declared variable to be either an instance of the class named in the declaration or an instance of a class that inherits from the named class. In the example above. Note: Messages are somewhat slower than function calls. In source code (at compile time).CHAPTER 9 Enabling Static Behavior This chapter explains how static typing works and discusses some other features of Objective-C. The type doesn’t affect the object. In particular. as described in “Dynamic Binding” (page 18). including ways to temporarily overcome its inherent dynamism. and to make code more self-documenting. A runtime procedure matches the method selector in the message to a method implementation that “belongs to” the receiver. the compiler can’t check the exact types (classes) of id variables. ■ These features give object-oriented programs a great deal of flexibility and power. The exact class of an id variable (and therefore its particular methods and data structure) isn’t determined until the program runs. Objects are dynamically typed. Messages and methods are dynamically bound. 91 . To permit better compile-time type checking. it affects only the amount of information given to the compiler about the object and the amount of information available to those reading the source code. Default Dynamic Behavior 2010-07-13 | © 2010 Apple Inc. All Rights Reserved.
When a statically typed object is assigned to a statically typed variable. the compiler generates a warning. or inherits from. ■ An assignment can be made without warning. It permits you to use the structure pointer operator to directly access an object’s instance variables. not every Shape is a Rectangle. it allows for compile-time type checking. not the one in its Rectangle superclass. the compiler can deliver better type-checking services in two situations: ■ When a message is sent to a statically typed receiver. not just those of a Rectangle: Rectangle *thisObject = [[Square alloc] init]. aShape = aRect. The third is covered in “Defining a Class” (page 35). The exact type of a statically typed receiver is still determined at runtime as part of the messaging process. A warning is issued if they’re not. . Type Checking With the additional information provided by static typing. performs the version of the method defined in the Square class. if the roles of the two variables are reversed and aShape is assigned to aRect. By giving the compiler more information about an object. (For reference. see Figure 1-2 (page 25). The following example illustrates this: Shape *aShape. the compiler makes sure the types are compatible. aRect = [[Rectangle alloc] init]. Messages sent to statically typed objects are dynamically bound. the class of the variable receiving the assignment. the compiler can make sure the receiver can respond. the following code would still produce an object with all the instance variables of a Square. It can free objects from the restriction that identically named methods must have identical return and argument types. Here aRect can be assigned to aShape because a Rectangle is a kind of Shape—the Rectangle class inherits from Shape. static typing opens up possibilities that are absent for objects typed id: ■ ■ In certain situations. Rectangle *aRect. Statically typed objects are dynamically allocated by the same class methods that create instances of type id.CHAPTER 9 Enabling Static Behavior Static typing also doesn’t affect how the object is treated at runtime. which shows the class hierarchy including Shape and Rectangle. just as objects typed id are. provided the class of the object being assigned is identical to. A warning is issued if the receiver doesn’t have access to the method named in the message. A display message sent to thisObject [thisObject display]. ■ The first two topics are discussed in the sections that follow. However. If Square is a subclass of Rectangle.) 92 Type Checking 2010-07-13 | © 2010 Apple Inc. All Rights Reserved.
Rectangle’s version of the method is performed. the compiler understands the class of a statically typed object only from the class name in the type designation. If you send the object a message to perform a Rectangle method. However. This constraint is imposed by the compiler to allow dynamic binding. [myRectangle display]. Return and Argument Types 2010-07-13 | © 2010 Apple Inc. can’t be known at compile time. even though Rectangle overrides the method. if you send it a message to perform a method that the Shape class knows about. can be statically typed as NSObject. The isFilled method is defined in the Rectangle class. the compiler must treat all methods with the same name alike. the compiler doesn’t ensure that a compatible object is returned to a statically typed variable. Therefore. the compiler will complain.CHAPTER 9 Enabling Static Behavior There’s no check when the expression on either side of the assignment operator is an id. For example. the compiler will treat it as a Shape. and it does its type checking accordingly. The compiler has access to class-specific information about the methods. . A statically typed object can be freely assigned to an id. Similarly. or an id to a statically typed object. when a message is sent to a statically typed object. Because methods like alloc and init return ids. suppose that the Upper class declares a worry method that returns a double. Because the class of a message receiver (and therefore class-specific details about the method it’s asked to perform). When it prepares information on method return and argument types for the runtime system. if you statically type a Rectangle instance as a Shape. Return and Argument Types In general. However. All Rights Reserved. for example. Typing an instance to an inherited class can therefore result in discrepancies between what the compiler thinks would happen at runtime and what actually happens.(double)worry. aRect = [[Shape alloc] init]. it creates just one method description for each method selector. but is allowed nonetheless: Rectangle *aRect. Shape *myRectangle = [[Rectangle alloc] init]. not in Shape. methods in different classes that have the same selector (the same name) must also share the same return and argument types. The following code is error-prone. the compiler won’t complain. BOOL solid = [myRectangle isFilled]. 93 . However. All instances. the class of the receiver is known by the compiler. Static Typing to an Inherited Class An instance can be statically typed to its own class or to any class that it inherits from. At runtime. the message is freed from the restrictions on its return and argument types.
.CHAPTER 9 Enabling Static Behavior and the Middle subclass of Upper overrides the method and declares a new return type: . the compiler will think that its worry method returns a double. but it can do so reliably only if the methods are declared in different branches of the class hierarchy. but at runtime it actually returns an int and generates an error. All Rights Reserved. 94 Static Typing to an Inherited Class 2010-07-13 | © 2010 Apple Inc. The compiler will inform the runtime system that a worry message sent to the object returns a double. Static typing can free identically named methods from the restriction that they must have identical return and argument types. it will think that worry returns an int. Errors will obviously result if a Middle instance is typed to the Upper class.(int)worry. If an instance is statically typed to the Upper class. and if an instance is typed to the Middle class.
All methods with the same name have the same selector. the selector for setWidth:height: is assigned to the setWidthHeight variable: SEL setWidthHeight. Methods and Selectors For efficiency. The @selector() directive lets you refer to the compiled selector. SEL and @selector Compiled selectors are assigned to a special type. You can use a selector to invoke a method on an object—this provides the basis for the implementation of the target-action design pattern in Cocoa. The NSStringFromSelector function returns a method name for a selector: NSString *method. method = NSStringFromSelector(setWidthHeight). refers to the unique identifier that replaces the name when the source code is compiled. However.CHAPTER 10 Selectors In Objective-C. in some cases. it’s futile to assign them arbitrarily. full ASCII names are not used as method selectors in compiled code. SEL. though. You can do this with the NSSelectorFromString function: setWidthHeight = NSSelectorFromString(aBuffer). you may need to convert a character string to a selector at runtime. to distinguish them from other data. You must let the system assign SEL identifiers to methods. then pairs the name with a unique identifier that represents the method at runtime. rather than to the full method name. Here. 95 . It can be used to refer simply to the name of a method when it’s used in a source-code message to an object. the compiler writes each method name into a table. It’s most efficient to assign values to SEL variables at compile time with the @selector() directive. and all methods with the same name have the same selector. The runtime system makes sure each identifier is unique: No two selectors are the same. Instead. Conversion in the opposite direction is also possible. Compiled selectors are of type SEL. Methods and Selectors 2010-07-13 | © 2010 Apple Inc. It also. Valid selectors are never 0. setWidthHeight = @selector(setWidth:height:). “selector” has two meanings. All Rights Reserved.
Varying the Message at Runtime The performSelector:. (Statically typed receivers are an exception to this rule. not method implementations. since the compiler can learn about the method implementation from the class type. SEL request = getTheSelector(). from the selector. These methods make it possible to vary a message at runtime. [helper performSelector:request]. except for messages sent to statically typed receivers. it lets you send the same message to receivers belonging to different classes. and the method the receiver is asked to perform (request) is also determined at runtime (by the equally fictitious getTheSelector function). there’s no confusion between the two. Method Return and Argument Types The messaging routine has access to method implementations only through selectors. and the data types of its arguments. All Rights Reserved. For example. for example.CHAPTER 10 Selectors Methods and Selectors Compiled selectors identify method names. the receiver (helper) is chosen at runtime (by the fictitious getTheReceiver function). All three methods map directly into the messaging function. take SEL identifiers as their initial arguments. A class method and an instance method with the same name are assigned the same selector. It discovers the return type of a method. However. and performSelector:withObject:withObject: methods. Therefore. The display method for one class. a message would be no different than a function call. so it treats all methods with the same selector alike. 96 Varying the Message at Runtime 2010-07-13 | © 2010 Apple Inc. This is essential for polymorphism and dynamic binding. In this example. is equivalent to: [friend gossipAbout:aNeighbor]. has the same selector as display methods defined in other classes. .) Although identically named class methods and instance methods are represented by the same selector. performSelector:withObject:. If there were one selector per method implementation. defined in the NSObject protocol. they can have different argument and return types. dynamic binding requires all implementations of identically named methods to have the same return type and the same argument types. [friend performSelector:@selector(gossipAbout:) withObject:aNeighbor]. because of their separate domains. Variable names can be used in both halves of a message expression: id helper = getTheReceiver(). just as it’s possible to vary the object that receives the message. A class could define a display class method in addition to a display instance method.
There would either have to be one target for each button. [myButtonCell setAction:@selector(reapTheWind:)]. menu items. it should be cast to the proper type. a label. the method selector it should use in the message it sends. To do this. an NSButtonCell object must be initialized not just with an image. you would also have to re-implement the method that responds to the action message. For example. text fields. the Application Kit makes good use of the ability to vary both the receiver and the message. a font. a picture. When the user clicks the button (or uses the keyboard alternative).) The Target-Action Design Pattern In its treatment of user-interface controls. a button labeled “Find” would translate a mouse click into an instruction for the application to start searching for something. all NSButtonCell objects would have to send the same message. All action messages take a single argument. Avoiding Messaging Errors If an object receives a message to perform a method that isn’t in its repertoire. and a target. and the like. switches. a size. casting doesn’t work for all types. the NSButtonCell class defines an object that you can assign to an NSMatrix instance and initialize with a size. The button cell sends the message using NSObject’s performSelector:withObject: method. or the target object would have to discover which button the message came from and act accordingly. [myButtonCell setTarget:anObject]. The Application Kit defines a template for creating control devices and defines a few “off-the-shelf” devices of its own. 97 . the error often isn’t evident until the program executes. Each time you rearranged the user interface.CHAPTER 10 Selectors Note: performSelector: and its companion methods return an id. but with directions on what message to send and who to send it to. Accordingly. If Objective-C didn’t allow the message to be varied. If the method that’s performed returns a different type. They interpret events coming from hardware devices like the keyboard and mouse and translate them into application-specific instructions. This would make it difficult for any object to respond to more than one button cell. In software. knobs. All Rights Reserved. the object that should receive the message. and a keyboard alternative. button cells and other controls would have to constrain the content of the message. an error results. For example. and a label. NSControl objects are graphical devices that can be used to give instructions to an application. This would be an unnecessary complication that Objective-C happily avoids. It’s the same sort of error as calling a nonexistent function. Most resemble real-world control devices such as buttons. the name of the method would be frozen in the NSButtonCell source code. Instead of simply implementing a mechanism for translating user actions into action messages. an NSButtonCell instance can be initialized for an action message. the id of the control device sending the message. dials. (However. The Target-Action Design Pattern 2010-07-13 | © 2010 Apple Inc. these devices stand between the application and the user. the method should return a pointer or a type compatible with a pointer. the NSButtonCell object sends a message instructing the application to do something. But because messaging occurs at runtime.
In that case.0 :0. See Message Forwarding in Objective-C Runtime Programming Guide for more information. if the message selector or the class of the receiver varies. determines whether a receiver can respond to a message. you can make sure that the receiver is able to respond. The respondsToSelector: test is especially important when sending messages to objects that you don’t have control over at compile time. even though the object responds to the message indirectly by assigning it to another object. it may be necessary to postpone this test until runtime. As you write your programs. .CHAPTER 10 Selectors It’s relatively easy to avoid this error when the message selector is constant and the class of the receiving object is known. Note: An object can also arrange to have the messages it receives forwarded to other objects if it can’t respond to them directly itself. it appears that the object can handle the message. If the receiver is statically typed. else fprintf(stderr. defined in the NSObject class. the compiler performs this test for you. However. 98 Avoiding Messaging Errors 2010-07-13 | © 2010 Apple Inc. It takes the method selector as an argument and returns whether the receiver has access to a method matching the selector: if ( [anObject respondsToSelector:@selector(setOrigin::)] ) [anObject setOrigin:0. All Rights Reserved. For example. you should make sure the receiver implements a method that can respond to the message. [NSStringFromClass([anObject class]) UTF8String]).0]. The respondsToSelector: method. if you write code that sends a message to an object represented by a variable that others can set. "%s can’t be placed\n".
You can have multiple @catch() blocks to catch different types of exception. A @catch() block contains exception-handling logic for exceptions thrown in a @try block. see Exception Programming Topics. calling undefined instructions (such as attempting to invoke an unimplemented method). Objective-C’s exception support revolves around four compiler directives: @try. use the -fobjc-exceptions switch of the GNU Compiler Collection (GCC) version 3. which is essentially an Objective-C object. for more details. NSError.) A @finally block contains code that must be executed whether an exception is thrown or not.) Exception Handling An exception is a special condition that interrupts the normal flow of program execution. Enabling Exception-Handling Using GNU Compiler Collection (GCC) version 3. underflow or overflow. Objective-C provides language-level support for exception handling. (This is illustrated in “Catching Different Types of Exception” (page 100). You typically use an NSException object. and attempting to access a collection element out of bounds. @throw. To turn on support for these features.3 and later because runtime support for exception handling and synchronization is not present in earlier versions of the software.3 and later. (Note that this renders the application runnable only in Mac OS X v10. Examples include arithmetical errors such as division by zero. @try { [cup fill]. You use the @throw directive to throw an exception. by hardware as well as software. @catch. Coupled with the use of the NSException.CHAPTER 11 Exception Handling The Objective-C language has an exception-handling syntax similar to that of Java and C++. There are a variety of reasons why an exception may be generated (exceptions are typically said to be raised or thrown). This article provides a summary of exception syntax and handling.3 and later. } Enabling Exception-Handling 2010-07-13 | © 2010 Apple Inc. you can add robust error-handling to your programs. and @finally: ■ ■ Code that can potentially throw an exception is enclosed in a @try block. ■ ■ The example below depicts a simple exception-handling algorithm: Cup *cup = [[Cup alloc] init]. 99 . but are not required to. All Rights Reserved. or custom classes.
use one or more @catch()blocks following the @try block. Catches a more general exception type. whether exceptions were thrown or not. Performs any clean-up processing that must always be performed. } @catch (NSException *ne) { // 2 // Perform processing necessary at this level.. 3. } @catch (id ue) { .. such as the exception name and the reason it was thrown. 2.. as shown in Listing 11-1.. } or not. } @catch (CustomException *ce) { // 1 . . } Catching Different Types of Exception To catch an exception thrown in a @try block. } @finally { // 3 // Perform processing necessary whether an exception occurred . [exception name]. The following list describes the numbered code-lines: 1.. } @finally { [cup release]. That way you can tailor the processing of exceptions as groups... [exception reason]). The @catch() blocks should be ordered from most-specific to the least-specific. All Rights Reserved... Catches the most specific exception type. Listing 11-1 An exception handler @try { . NSException *exception = [NSException exceptionWithName:@"HotTeaException" reason:@"The tea is too hot" userInfo:nil]. 100 Catching Different Types of Exception 2010-07-13 | © 2010 Apple Inc.CHAPTER 11 Exception Handling @catch (NSException *exception) { NSLog(@"main: Caught %@: %@". . Throwing Exceptions To throw an exception you must instantiate an object with the appropriate information..
but you can implement your own if you so desire. or simply to signify errors. Important: In many environments. You should not use exceptions for general flow-control. Instead you should use the return value of a method or function to indicate that an error has occurred.CHAPTER 11 Exception Handling @throw exception. You can throw any Objective-C object as an exception object. 101 . Exceptions are resource-intensive in Objective-C. For example. use of exceptions is fairly commonplace. Inside a @catch() block. you might throw an exception to signal that a routine could not execute normally—such as when a file is missing or data could not be parsed correctly. This can help make your code more readable. You can also subclass NSException to implement specialized types of exceptions. such as file-system exceptions or communications exceptions. see Error Handling Programming Guide. You are not limited to throwing NSException objects. and provide information about the problem in an error object. For more information. All Rights Reserved. The NSException class provides methods that help in exception processing. you can re-throw the caught exception using the @throw directive without an argument. Throwing Exceptions 2010-07-13 | © 2010 Apple Inc.
All Rights Reserved. .CHAPTER 11 Exception Handling 102 Throwing Exceptions 2010-07-13 | © 2010 Apple Inc.
This object is known as a mutual exclusion semaphore or mutex. You should use separate semaphores to protect different critical sections of a program. This means that two threads can try to modify the same object at the same time. 103 . Before executing a critical process. only one thread at a time is allowed to execute a class method because there is only one class object that is shared by all callers. Note: Using either of these features in a program. including self. Listing 12-1 Locking a method using self .. The Account class could create the semaphore in its initialize method. of course.(void)criticalMethod { @synchronized(self) { // Critical code. a situation that can cause serious problems in a program. The @synchronized() directive takes as its only argument any Objective-C object. It allows a thread to lock a section of code to prevent its use by other threads. Objective-C provides the @synchronized() directive. that is. Synchronizing Thread Execution Objective-C supports multithreading in applications. use the -fobjc-exceptions switch of the GNU Compiler Collection (GCC) version 3.. You can take a similar approach to synchronize the class methods of the associated class.CHAPTER 12 Threading Objective-C provides support for thread synchronization and exception handling.3 and later because runtime support for exception handling and synchronization is not present in earlier versions of the software. when execution continues past the last statement in the @synchronized() block. the code obtains a semaphore from the Account class and uses it to lock the critical section. which are explained in this article and “Exception Handling” (page 99). To protect sections of code from being executed by more than one thread at a time. } } Listing 12-2 shows a general approach. All Rights Reserved. renders the application runnable only in Mac OS X v10. Other threads are blocked until the thread exits the protected code. In the latter case. It’s safest to create all the mutual exclusion objects before the application becomes multithreaded to avoid race conditions. To turn on support for these features. Synchronizing Thread Execution 2010-07-13 | © 2010 Apple Inc. Listing 12-1 shows an example of code that uses self as the mutex to synchronize access to the instance methods of the current object. The @synchronized()directive locks a section of code for use by a single thread. . using the Class object instead of self.3 and later.
other threads are blocked from using it until the thread releases all the locks obtained with it. the Objective-C runtime catches the exception. } The Objective-C synchronization feature supports recursive and reentrant code. . id accountSemaphore = [Account semaphore]. that is. 104 Synchronizing Thread Execution 2010-07-13 | © 2010 Apple Inc. A thread can use a single semaphore several times in a recursive manner. and re-throws the exception to the next exception handler.CHAPTER 12 Threading Listing 12-2 Locking a method using a custom semaphore Account *account = [Account accountFromString:[accountField stringValue]]. every @synchronized() block is exited normally or through an exception.. All Rights Reserved. . // Get the semaphore. releases the semaphore (so that the protected code can be executed by other threads). @synchronized(accountSemaphore) { // Critical code. When code in an @synchronized() block throws an exception..
it has no identity of its own. The proxy assumes the identity of the remote object. It could simply display a dialog telling the user to wait while it was busy. and transfer data from one address space to another. would seem well suited for interprocess communication as well. Objective-C was initially designed for programs that are executed as a single process in a single address space. Using distributed objects. the threads are treated exactly like threads in different tasks. Or imagine an interactive application that needs to do a good deal of computation to carry out a user command. you can send Objective-C messages to objects in other tasks or have messages executed in other threads of the same task. recognize when a message is intended for an object in a remote address space. It must also mediate between the separate schedules of the two tasks.) Note that Cocoa’s distributed objects system is built on top of the runtime system. and the server might target specific client objects for the notifications and other information it sends. it has to hold messages until their remote receivers are free to respond to them. in a typical server-client interaction. Remote messaging is illustrated in Figure 13-1 (page 106). (When remote messages are sent between two threads of the same task. for most purposes. the client task might send its requests to a designated object in the server. in different tasks) or in different threads of execution of the same task. where object A communicates with object B through a proxy. where communication takes place between relatively self-contained units through messages that are resolved at runtime. Nevertheless. For example. Cocoa includes a distributed objects architecture that is essentially this kind of extension to the runtime system. it is the remote object. or it could isolate the processing work in a subordinate task. It’s not hard to imagine Objective-C messages between objects that reside in different address spaces (that is. The application is able to regard the proxy as if it were the remote object. It then communicates with the remote object through the proxy. 105 . it doesn’t alter the fundamental behavior of your Cocoa objects. the object-oriented model. Objects in the two tasks would communicate through Objective-C messages. and messages for B wait in a queue until B is ready to respond to them: Distributed Objects 2010-07-13 | © 2010 Apple Inc. leaving the main part of the application free to accept user input. To send a remote message. Establishing the connection gives the application a proxy for the remote object in its own address space. All Rights Reserved.CHAPTER 13 Remote Messaging Like most other programming languages. Distributed Objects Remote messaging in Objective-C requires a runtime system that can establish connections between objects in different address spaces. an application must first establish a connection with the remote receiver.
but a lightweight substitute for it. The distributed objects architecture. In a sense. Both the sending and the receiving application declare the protocol—they both import the same protocol declaration. The sending application doesn’t have to implement any of the methods in the protocol. Its class is hidden inside the remote application. Because of this. All Rights Reserved. For instance. Most of the issues are related to the efficiency of remote messaging and the degree of separation that the two tasks should maintain while they’re communicating with each other. It doesn’t need to use the same classes itself. A remote receiver is typically anonymous. it’s transparent. however. The sending application doesn’t need to know how that application is designed or what classes it uses. it declares the protocol only because it initiates messages to the remote receiver. is documented in the Foundation framework reference and Distributed Objects Programming Topics. Therefore. Objective-C defines six type qualifiers that can be used when declaring methods inside a formal protocol: oneway in out inout bycopy 106 Language Support 2010-07-13 | © 2010 Apple Inc. including the NSProxy and NSConnection classes. So there’s no guarantee that the receiver is free to accept a message when the sender is ready to send it. It isn’t a copy of the object. Language Support Remote messaging raises not only a number of intriguing possibilities for program design. All it needs to know is what messages the remote object responds to. it simply passes the messages it receives on to the remote receiver and manages the interprocess communication. So that programmers can give explicit instructions about the intent of a remote message. A proxy isn’t fully transparent. an object that’s designated to receive remote messages advertises its interface in a formal protocol.CHAPTER 13 Remote Messaging Figure 13-1 Remote Messages A Proxy for B B The sender and receiver are in different tasks and are scheduled independently of each other. A proxy doesn’t act on behalf of the remote object or need access to its class. arriving messages are placed in a queue and retrieved at the convenience of the receiving application. The sending application declares it to inform the compiler about the messages it sends and because it may use the conformsToProtocol: method and the @protocol() directive to test the remote receiver. it also raises some interesting issues for the Objective-C language. Its main function is to provide a local address for an object that wouldn’t otherwise have one. The receiving application declares it because the remote object must conform to the protocol. a proxy doesn’t allow you to directly set and get an object’s instance variables. .
The following sections explain how these modifiers are used. Pointer Arguments Next. The sending application waits for the receiving application to invoke the method. In the meantime. consider methods that take pointer arguments. However. the method is invoked and the return value provided directly to the sender. complete its processing. An asynchronous message can’t have a valid return value. the sender can go on to other things. However. even if no information is returned. Although oneway is a type qualifier (like const) and can be used in combination with a specific type name. the method looks at what’s stored in the address it’s passed.” For this reason. oneway. But when the receiver is in a remote application. and send back an indication that it has finished. has the advantage of coordinating the two communicating applications. When a canDance message is sent to a receiver in the same application. round-trip messages are often called synchronous.CHAPTER 13 Remote Messaging byref These modifiers are restricted to formal protocols. to indicate that a method is used only for asynchronous messages: . such as oneway float or oneway id. two underlying messages are required—one message to get the remote object to invoke the method. A pointer can be used to pass information to the receiver by reference. at bottom. This is illustrated in the figure below: Figure 13-2 Round-Trip Message A Proxy for B initial message B return information Most remote messages are. and the other message to send back the result of the remote calculation. its implementation of the protocol methods can use the same modifiers that are used to declare the methods. When invoked. Synchronous and Asynchronous Messages Consider first a method with just a simple return value: . if a class or category adopts a protocol.(oneway void)waltzAtWill. the only such combination that makes any sense is oneway void. it’s not always necessary or a good idea to wait for a reply. Waiting for the receiver to finish. Synchronous messages are the default. they can’t be used inside class and category declarations. Sometimes it’s sufficient simply to dispatch the remote message and return. Language Support 2010-07-13 | © 2010 Apple Inc. All Rights Reserved. 107 . two-way (or “round trip”) remote procedure calls (RPCs) like this one. allowing the receiver to get to the task when it can. along with any return information requested. Objective-C provides a return type modifier.(BOOL)canDance. of keeping them both “in sync.
In the second case. } The same sort of argument can also be used to return information by reference. inout is the safest assumption but also the most time-consuming since it requires passing information in both directions. a string is represented as a character pointer (char *). In neither case can the pointer simply be passed to the remote object unchanged. a string is an entity in and of itself. ■ A third modifier. the value it points to doesn’t have to be sent to the other application. 108 Language Support 2010-07-13 | © 2010 Apple Inc. } The way the pointer is used makes a difference in how the remote message is carried out. All Rights Reserved. ship the value it points to over to the remote application. information is returned on the second leg of the round trip. Although in notation and implementation there’s a level of indirection here. store the value in an address local to that application. not a pointer to something else. While in can be used with any kind of argument.getTune:(out struct tune *)theSong. The method uses the pointer to find where it should place information requested in the message..setTune:(in struct tune *)aSong.. a value from the other application must be sent back and written into the location indicated by the pointer. pointers are sometimes used to represent composite values. the runtime system must dereference the pointer. For example. it points to a memory location in the sender’s address space and would not be meaningful in the address space of the remote receiver. Objective-C provides type modifiers that can clarify the programmer’s intention: ■ The type modifier in indicates that information is being passed in a message: . information is passed on the first leg of the round trip.CHAPTER 13 Remote Messaging . *theSong = tune.getTune:(struct tune *)theSong { . . ■ The modifier out indicates that an argument is being used to return information by reference: . the pointer is used to return information by reference. . inout. and pass that address to the remote receiver. on the other hand..setTune:(struct tune *)aSong { tune = *aSong. If the argument is used to pass information by reference. Conceptually.. The Cocoa distributed objects system takes inout to be the default modifier for all pointer arguments except those declared const. Because these cases result in very different actions on the part of the runtime system for remote messaging. If. for which in is the default. In C. The only modifier that makes sense for arguments passed by value (non-pointers) is in. in concept there’s not. In the first case. Instead. out and inout make sense only for pointers. The runtime system for remote messaging must make some adjustments behind the scenes. . indicates that an argument is used both to provide information and to get information back: .adjustTune:(inout struct tune *)aSong.
This is true even if the receiver is in a remote application. except that the receiver needs to refer to the object through a proxy (since the object isn’t in its address space). Proxies and Copies Finally. consider a method that takes an object as an argument: .CHAPTER 13 Remote Messaging In cases like this. bycopy can also be used for return values: .danceWith:(id)aPartner. Objective-C provides a bycopy type modifier: .(bycopy)dancer. 109 . The only type that it makes sense for bycopy or byref to modify is an object. The pointer that danceWith: delivers to a remote receiver is actually a pointer to the proxy. These conventions are enforced at runtime. Messages sent to the proxy would be passed across the connection to the real object and any return information would be passed back to the remote application. the out and inout modifiers make no sense with simple character pointers. however. if ever. If the sender and the receiver are in the same application. thereby specifying that objects passed to a method or objects returned from a method should be passed or returned by reference. make use of the byref keyword. It can similarly be used with out to indicate that an object returned by reference should be copied rather than delivered in the form of a proxy: . whether dynamically typed id or statically typed by a class name.getTuneTitle:(out char **)theTitle. To give programmers a way to indicate that this is intended. You can override this behavior with byref. bycopy makes so much sense for certain classes—classes that are intended to contain a collection of other objects.danceWith:(bycopy id)aClone.getDancer:(bycopy out id *)theDancer. A danceWith: message passes an object id to the receiver. Note: When a copy of an object is passed to another application. it cannot be anonymous. There are times when proxies may be unnecessarily inefficient. instead of the usual reference. All Rights Reserved. The same is true of objects: . Therefore.adjustRectangle:(inout Rectangle **)theRect. Language Support 2010-07-13 | © 2010 Apple Inc. Since passing by reference is the default behavior for the vast majority of Objective-C objects. they would both be able to refer to the same aPartner object. for instance—that often these classes are written so that a copy is sent to a remote receiver. when it’s better to send a copy of the object to the remote process so that it can interact with it directly in its own address space. The application that receives the object must have the class of the object loaded in its address space. It takes an additional level of indirection in a remote message to pass or return a string by reference: . you will rarely. the distributed objects system automatically dereferences the pointer and passes whatever it points to as if by value. not by the compiler.
you could write a formal protocol foo as follows: @Protocol foo .(bycopy)array. @end A class or category can then adopt your protocol foo.. All Rights Reserved. 110 Language Support 2010-07-13 | © 2010 Apple Inc.
(id)init. Pointers to objects in either language are just pointers. .mm */ #import <Foundation/Foundation. } . @interface Greeting : NSObject { @private Hello *hello. This Objective-C/C++ language hybrid is called Objective-C++. Listing 14-1 illustrates this. and you can include pointers to C++ objects as instance variables of Objective-C classes. } }. and as such can be used anywhere. Mixing Objective-C and C++ Language Features 2010-07-13 | © 2010 Apple Inc.(void)sayGreeting. For example. world!". you can include pointers to Objective-C objects as data members of C++ classes. With it you can make use of existing C++ libraries from your Objective-C applications. Listing 14-1 Using C++ and Objective-C instances as instance variables -o hello /* Hello. } Hello(const char* initial_greeting_text) { greeting_text = [[NSString alloc] initWithUTF8String:initial_greeting_text]. Mixing Objective-C and C++ Language Features In Objective-C++.(void)sayGreeting:(Hello*)greeting. // holds an NSString public: Hello() { greeting_text = @"Hello.(void)dealloc.mm” extension for the Objective-C++ extensions to be enabled by the compiler. } void say_hello() { printf("%s\n". [greeting_text UTF8String]). .CHAPTER 14 Using C++ With Objective-C Apple’s Objective-C compiler allows you to freely mix C++ and Objective-C code in the same source file. All Rights Reserved. 111 .h> class Hello { private: id greeting_text. you can call methods from either language in C++ code and in Objective-C methods.mm * Compile with: g++ -x objective-c++ -framework Foundation Hello. Note: Xcode requires that file names have a “. .
not nested within the Objective-C class. As previously noted. as specified by (respectively) the C++ and Objective-C language standards.(id)init { self = [super init]. (This is consistent with the way in which standard C—though not C++—promotes nested struct definitions to file scope. Objective-C++ does not allow you to inherit C++ classes from Objective-C objects. [greeting sayGreeting:hello].. the Objective-C++ compiler defines both the __cplusplus and the __OBJC__ preprocessor constants. All Rights Reserved. @interface ObjCClass: Base . monde! As you can declare C structs in Objective-C interfaces. Hello *hello = new Hello("Bonjour. return 0. */ }.. @end // ERROR! class Derived: public ObjCClass . class Base { /* . monde!"). [greeting release].. world! // > Bonjour. nor does it allow you to inherit Objective-C classes from C++ objects.(void)sayGreeting { hello->say_hello(). } // > Hello. Greeting *greeting = [[Greeting alloc] init]. delete hello. } .(void)sayGreeting:(Hello*)greeting { greeting->say_hello(). } . // ERROR! 112 Mixing Objective-C and C++ Language Features 2010-07-13 | © 2010 Apple Inc. . } @end int main() { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init].. } . you can also declare C++ classes in Objective-C interfaces. [pool release].. [greeting sayGreeting].CHAPTER 14 Using C++ With Objective-C @end @implementation Greeting .. } return self. C++ classes defined within an Objective-C interface are globally-scoped.(void)dealloc { delete hello.) To allow you to conditionalize your code based on the language variant. [super dealloc]. As with C structs. if (self) { hello = new Hello().
objects in C++ are statically typed. }. in reverse declaration order immediately before the Objective-C object of which they are a member is deallocated.2. you can use instances of C++ classes containing virtual functions and nontrivial user-defined zero-argument constructors and destructors as instance variables. if you set the fobjc-call-cxx-cdtors compiler flag. @interface Foo { struct CStruct { . @end On Mac OS X 10.4 and later.CHAPTER 14 Using C++ With Objective-C Unlike Objective-C. You can declare a C++ class within an Objective-C class declaration.. inside object_dispose). in declaration order immediately after the Objective-C object of which they are a member is allocated. the layout of Objective-C and C++ objects in memory is mutually incompatible. meaning that it is generally impossible to create an object instance that would be valid from the perspective of both languages. The constructor used is the “public no-argument in-place constructor. // OK } . struct CStruct bigIvar. // OK Objective-C allows C structures (whether declared inside of an Objective-C declaration or not) to be used as instance variables.. Hence. More fundamentally. (The fobjc-call-cxx-cdtors compiler flag is set by default in gcc-4. inside class_createInstance). The object models of the two languages are thus not directly compatible. as follows: @interface Foo { class Bar { .... with runtime polymorphism available as an exceptional case. Mixing Objective-C and C++ Language Features 2010-07-13 | © 2010 Apple Inc. } // OK } @end Bar *barPtr. the two type hierarchies cannot be intermixed. The compiler treats such classes as having been declared in the global namespace.) Constructors are invoked in the alloc method (specifically.” Destructors are invoked in the dealloc method (specifically.. 113 . All Rights Reserved.
Objective-C does not have a notion of nested namespaces. protocols. These are not keywords in any other contexts. int j). even though class is a C++ keyword. // OK class1. the Objective-C runtime cannot dispatch calls to C++ constructors or destructors for those objects.constructor not called! .. in. }.3 and earlier: The following cautions apply only to Mac OS X v10. IMP. unlike the C++ this keyword. SEL. All Rights Reserved. nor can you declare namespaces within Objective-C classes. nor can a C++ template be declared inside the scope of an Objective-C interface.h> struct Class0 { void foo(). You cannot declare Objective-C classes within C++ namespaces. // ERROR! *ptr. @end C++ requires each instance of a class containing virtual functions to contain a suitable virtual function table pointer.. }. so the impact isn’t too severe. If a C++ class has any user-defined constructors or destructors. Objective-C++ similarly strives to allow C++ class instances to serve as instance variables. and BOOL. However. C++ adds quite a few new keywords. This is possible as long as the C++ class in question (along with all of its superclasses) does not have any virtual member functions defined. the compiler pre-declares the identifiers self and super. similarly to the keyword this in C++. because it is not familiar with the C++ object model. // OK—call 'ptr = new Class1()' from Foo's init. From an Objective-C programmer's point of view. the Objective-C runtime cannot initialize the virtual function table pointer. out. However. inout. C++ template parameters can also be used as receivers or parameters (though not as selectors) in Objective-C message expressions. // WARNING . self and super are context-sensitive. #import <Cocoa/Cocoa. The compiler emits a warning in such cases. you can still use the NSObject method class: 114 C++ Lexical Ambiguities and Conflicts 2010-07-13 | © 2010 Apple Inc. These identifiers are id. and bycopy). Similarly. For example. but you cannot use them for naming Objective-C classes or instance variables. You can still use C++ keywords as a part of an Objective-C selector. C++ Lexical Ambiguities and Conflicts There are a few identifiers that are defined in the Objective-C header files that every Objective-C program must include. Objective-C classes. or category. Class. they may be used as ordinary identifiers outside of Objective-C methods. there are five more context-sensitive keywords (oneway. Inside an Objective-C method. @interface Class0 Class1 Class1 Foo : NSObject { class0. protocol. struct Class2 { Class2(int i. the C++ class may not serve as an Objective-C instance variable. and categories cannot be declared inside a C++ template.3 and earlier. Objective-C classes may serve as C++ template parameters. . }. In the parameter list of methods within a protocol.CHAPTER 14 Using C++ With Objective-C Mac OS X v10. struct Class1 { virtual void foo(). However. they are not called. // 'delete ptr' from Foo's dealloc Class2 class2. If any virtual member functions are present.
Limitations 2010-07-13 | © 2010 Apple Inc. conversely. Objective-C++ adds a similar case. Protocol and template specifiers use the same syntax for different purposes: id<someProtocolName> foo. // OK However. multi-language exception handling is not supported. see “Exception Handling” (page 99). you cannot use class as the name of a variable: NSObject *class. there is a lexical ambiguity in C++ when a label is followed by an expression that mentions a global name. as in: label: ::global_name = 3. you can also have a category whose name matches that of a C++ class or structure. and an Objective-C class cannot inherit from a C++ class. All Rights Reserved. TemplateType<SomeTypeName> bar. both @interface foo and @interface(foo) can exist in the same source code. nor does it add Objective-C features to C++ classes. and you cannot use the keywords this and self interchangeably. the compiler doesn’t permit id to be used as a template name.CHAPTER 14 Using C++ With Objective-C [foo class]. The class hierarchies are separate. Limitations Objective-C++ does not add C++ features to Objective-C classes. you cannot use Objective-C syntax to call a C++ object. the names for classes and categories live in separate namespaces. because it is a keyword. an exception thrown in C++ code cannot be caught in Objective-C code. In addition. That is. That is. For more information on exceptions in Objective-C. you cannot add constructors or destructors to an Objective-C object. The space after the first colon is required. In Objective-C++. For example. an exception thrown in Objective-C code cannot be caught in C++ code and. // Error In Objective-C. a C++ class cannot inherit from an Objective-C class. Finally. To avoid this ambiguity. 115 . which also requires a space: receiver selector: ::global_c++_name.
All Rights Reserved.CHAPTER 14 Using C++ With Objective-C 116 Limitations 2010-07-13 | © 2010 Apple Inc. .
id can be used to type any kind of object. . For more information. A pointer to a method implementation that returns an id. 117 . Messages 2010-07-13 | © 2010 Apple Inc. Note that the type of BOOL is char. class. a compiler-assigned code that identifies a method name. class names can be used as type names to statically type instances of a class.APPENDIX A Language Summary Objective-C adds a small number of constructs to the C language and defines a handful of conventions for effectively interacting with the runtime system. or instance. A statically typed instance is declared to be a pointer to its class or to any class it inherits from.h. Class A class object (a pointer to the class data structure). see the other chapters in this document. Defined Types The principal types used in Objective-C are defined in objc/objc. All Rights Reserved.. In addition. This appendix lists all the additions to the language but doesn’t go into great detail. either YES or NO. A Boolean value. They are: Type id Definition An object (a pointer to its data structure).
(BOOL)0. categories. A boolean false value. and protocols: Directive @interface Definition Begins the declaration of a class or category interface. @protected Limits instance variable scope to declaring and inheriting classes. Preprocessor Directives The preprocessor understands these special notations: Notation Definition #import Imports a header file. 118 Preprocessor Directives 2010-07-13 | © 2010 Apple Inc. This directive is identical to #include. or protocol. @implementation Begins the definition of a class or category. Compiler Directives Directives to the compiler begin with “@” The following directives are used to declare and define classes. (BOOL)1. (id)0.h header file also defines these useful terms: Type Definition nil Nil NO YES A null object pointer. @public Removes restrictions on the scope of instance variables. A boolean true value. Ends the declaration/definition of a class. (Class)0. . except that it doesn’t include the same file more than once.APPENDIX A Language Summary The objc. // Begins a comment that continues to the end of the line. A null class pointer. @protocol @end Begins the declaration of a formal protocol. All Rights Reserved. The following mutually exclusive directives specify the visibility of instance variables: Directive @private Definition Limits the scope of an instance variable to the class that declares it. category. .
you can use UTF-16 encoded strings. (@protocol is also valid without (protocol_name) for forward declarations. All Rights Reserved. Defines a constant NSString object in the current module and initializes the object with the specified string. @dynamic Instructs the compiler not to generate a warning if it cannot find implementations of accessor methods associated with the properties whose names follow. @synthesize Requests that. In addition. On Mac OS X v10.2 and later supports UTF-16 encoded strings.4 and earlier. The following directives support the declared properties feature (see “Declared Properties” (page 67)): Directive @property Definition Begins the declaration of a declared property. (The runtime from Mac OS X v10.5 and later (with Xcode 3. Throws an exception object. @finally Defines a block of code that is executed whether exceptions were thrown or not in a preceding @try block. @catch() Catches an exception thrown within the preceding @try block. 119 . These directives support exception handling: Directive @try @throw Definition Defines a block within which exceptions can be thrown.5 to compile an application for Mac OS X v10. @protocol(protocol_name) Returns the protocol_name protocol (an instance of the Protocol class).APPENDIX A Language Summary The default is @protected. for the properties whose names follow. there are directives for these particular purposes: Directive @class @selector(method_name) Definition Declares the names of classes defined elsewhere.) @encode(type_spec) @"string" Yields a character string that encodes the type structure of type_spec. Returns the compiled selector that identifies method_name. the compiler generate accessor methods for which there are no custom implementations.2 and later.0 and later). you can also use UTF-16 encoded strings. On Mac OS X v10. so if you use Mac OS X v10.) Compiler Directives 2010-07-13 | © 2010 Apple Inc. the string must be 7-bit ASCII-encoded.
A file containing a class definition imports its own interface: #import "ClassName. The interface file for its superclass must be imported: #import "ItsSuperclass. Like a class definition. @synchronized() Defines a block of code that must be executed only by one thread at a time. the header files where they’re declared must also be imported. the class is declared to be a new root class..APPENDIX A Language Summary Directive Definition @"string1" @"string2" .h" @implementation ClassName method definitions @end Categories A category is declared in much the same way as a class.h" @interface ClassName ( CategoryName ) < protocol list > method declarations @end The protocol list and method declarations are optional. All Rights Reserved.h" @interface ClassName : ItsSuperclass < protocol_list > { instance variable declarations } method declarations @end Everything but the compiler directives and class name is optional.. If the colon and superclass name are omitted. the header files where they’re declared must also be imported. . If any protocols are listed. Defines a constant NSString object in the current module. If any protocols are listed. The string @"stringN" created is the result of concatenating the strings specified in the two directives. a file containing a category definition imports its own interface: 120 Classes 2010-07-13 | © 2010 Apple Inc. The interface file that declares the class must be imported: #import "ClassName. Classes A new class is declared with the @interface directive.
to adopt the protocol (as shown in “Classes” (page 120) and “Categories” (page 120)) In a type specification. The protocol must import the header files that declare any protocols it incorporates. should be passed or returned. The @optional directive specifies that following methods are optional. protocols are referred to using the similar @protocol() directive. Formal Protocols 2010-07-13 | © 2010 Apple Inc. The argument passes information to the remote receiver. 121 . A copy of the object. Within source code. The argument gets information returned by reference. All Rights Reserved. the @required directive directive specifies that following methods must be implemented by a class that adopts the protocol. these type qualifiers support remote messaging: Type Qualifier Definition oneway in out inout bycopy The method is for asynchronous messages and has no valid return type. Protocol names listed within angle brackets (<.>) are used to do three different things: ■ ■ In a protocol declaration. to incorporate other protocols (as shown earlier) In a class or category declaration.APPENDIX A Language Summary #import "CategoryName. to limit the type to objects that conform to the protocol ■ Within protocol declarations.. not a proxy. The argument both passes information and gets information default is @required. where the parentheses enclose the protocol name.. You can create a forward reference to a protocol using the @protocol directive in the following manner: @protocol ProtocolName.
(void)setWidth:(int)newWidth height:(int)newHeight Typically. Deprecation Syntax Syntax is provided to mark methods as deprecated: @interface SomeClass -method __attribute__((deprecated)). 122 Method Declarations 2010-07-13 | © 2010 Apple Inc. for example: . Within the implementation.) Method Implementations Each method implementation is passed two hidden arguments: ■ ■ The receiving object (self). The selector for the method (_cmd).(void)setWidthAndHeight:(int)newWidth :(int)newHeight Both labels and colons are considered part of the method name. a label describing the argument precedes the colon—the following example is valid but is considered bad style: . super replaces self as the receiver of a message to indicate that only methods inherited by the implementation should be performed in response to the message.APPENDIX A Language Summary Type Qualifier Definition byref A reference to the object. A “-” precedes declarations of instance methods. . Argument and return types are declared using the C syntax for type casting. the modifier unsigned when used without a following type always means unsigned int. (However. Method Declarations The following conventions are used in method declarations: ■ ■ ■ ■ A “+” precedes declarations of class methods. Methods with no other valid return typically return void. Arguments are declared after colons (:). All Rights Reserved. both self and super refer to the receiving object. should be passed or returned. not int as it is for functions. ■ The default return and argument type for methods is id. not a copy.
h extension typical of header files. A class can declare instance variables with the same names as variables in other classes. All Rights Reserved. A category of one class can have the same name as a category of another class. Likewise. identical names that serve different purposes don’t clash. An instance method can have the same name as a class method. a category.h> @interface SomeClass -method DEPRECATED_ATTRIBUTE. and protocol names generally begin with an uppercase letter. A method can have the same name as an instance variable.m extension. Files that declare class and category interfaces or that declare protocols have the . are reserved for use by Apple. // or some other deployment-target-specific macro @end This syntax is available only in Objective-C 2. names can be freely assigned: ■ ■ ■ ■ ■ A class can declare methods with the same names as methods in other classes. Within a class.APPENDIX A Language Summary @end or: #include <AvailabilityMacros. .0 and later. Method names beginning with “_” a single underscore character. class names are in the same name space as global variables and defined types. 123 . Naming Conventions The names of files that contain Objective-C source code have the . protocols and categories of the same class have protected name spaces: ■ ■ A protocol can have the same name as a class. category. In Objective-C. or anything else. However. the names of methods and instance variables typically begin with a lowercase letter. A program can’t have a global variable with the same name as a class. Class. Naming Conventions 2010-07-13 | © 2010 Apple Inc. The names of variables that hold instances usually also begin with lowercase letters.
. All Rights Reserved.APPENDIX A Language Summary 124 Naming Conventions 2010-07-13 | © 2010 Apple Inc.
Corrected typographical errors. 2008-02-08 2007-12-11 2007-10-31 2007-07-22 2007-03-26 2007-02-08 2006-12-05 2006-05-23 2006-04-04 2006-02-07 2006-01-10 125 2010-07-13 | © 2010 Apple Inc." Corrected minor typographical errors. Date 2010-07-13 2009-10-19 2009-08-12 2009-05-06 2009-02-04 2008-11-19 2008-10-15 2008-07-08 2008-06-09 Notes Updated to show the revised initialization pattern.REVISION HISTORY Document Revision History This table describes the changes to The Objective-C Programming Language. Corrected minor typographical errors. Provided an example of fast enumeration for dictionaries and enhanced the description of properties. Significant reorganization. Updated article on Mixing Objective-C and C++. All Rights Reserved. Added discussion of associative references. Extended the discussion of properties to include mutable objects. Updated description of categories. Corrected minor errors. Clarified the description of Code Listing 3-3. Clarified the discussion of sending messages to nil. Moved the discussion of memory management to "Memory Management Programming Guide for Cocoa. . Clarified use of the static specifier for global variables used by a class. Corrected typographical errors. Corrected minor errors. Corrected minor typographical errors. Added references to documents describing new features in Objective-C 2. with several sections moved to a new Runtime Guide. particularly in the "Properties" chapter. Made several minor bug fixes and clarifications.
Moved function and data structure reference to Objective-C Runtime Reference. Documented the Objective-C exception and synchronization support available in Mac OS X version 10. 2005-04-08 2004-08-31 Removed function and data structure reference.REVISION HISTORY Document Revision History Date 2005-10-04 Notes Clarified effect of sending messages to nil. Moved “Memory Management” before “Retaining Objects” . Corrected the descriptions for the Ivar structure and the objc_ivar_list structure. Clarified when the initialize method is called and provided a template for its implementation in “Initializing a Class Object” . 2004-02-02 2003-09-16 2003-08-14 Corrected typos in “An exception handler” .3 and later in “Exception Handling and Thread Synchronization” . Corrected typo in language grammar specification and modified a code example. Corrected definition of the term conform in the glossary. All Rights Reserved. Added exception and synchronization grammar to “Grammar” . Clarified example in Listing 14-1 (page 111).mm" extension to signal Objective-C++ to compiler. Corrected the grammar for the protocol-declaration-list declaration in “External Declarations” . 126 2010-07-13 | © 2010 Apple Inc. Changed the font of function result in class_getInstanceMethod and class_getClassMethod. Added examples of thread synchronization approaches to “Synchronizing Thread Execution” . Made technical corrections and minor editorial changes. . Documented the language support for concatenating constant strings in “Compiler Directives” (page 118). noted use of ". Corrected definition of id. Added exception and synchronization grammar. Corrected definition of method_getArgumentInfo. Renamed from Inside Mac OS X: The Objective-C Programming Language to The Objective-C Programming Language. Replaced conformsTo: with conformsToProtocol: throughout document.
Added an index. and archaic tone. Renamed from Object Oriented Programming and the Objective-C Language to Inside Mac OS X: The Objective-C Programming Language. Fixed several typographical errors. All Rights Reserved. Updated grammar and section names throughout the book to reduce ambiguities. which allows C++ constructs to be called from Objective-C classes. . and vice versa.1 introduces a compiler for Objective-C++.REVISION HISTORY Document Revision History Date 2003-01-01 Notes Documented the language support for declaring constant strings. Mac OS X 10. Restructured some sections to improve cohesiveness. Fixed a bug in the Objective-C language grammar’s description of instance variable declarations. 2002-05-01 127 2010-07-13 | © 2010 Apple Inc. Added runtime library reference material. passive voice.
All Rights Reserved.REVISION HISTORY Document Revision History 128 2010-07-13 | © 2010 Apple Inc. .
and are therefore not “in sync. a method that can operate on class objects rather than instances of the class. Thus. archiving involves writing data to an NSData object. Application Kit A Cocoa framework that implements an application's user interface. The sending application and the receiving application act independently. copied to the pasteboard. class method In the Objective-C language. especially an object. and can’t be statically typed. a prototype for a particular kind of object. asynchronous message A remote message that returns immediately. A class definition declares instance variables and defines methods for all members of the class. category In the Objective-C language. a class object is represented by the class name. In Cocoa. Objects that have the same types of instance variables and have access to the same methods belong to the same class. conform In the Objective-C language. a set of method definitions that is segregated from the rest of the class definition. An archived data structure is usually stored in a file. Cocoa is a set of frameworks with its primary programming interfaces in Objective-C. 129 2010-07-13 | © 2010 Apple Inc. only of its subclasses. The interface to an anonymous object is published through a protocol declaration. As the receiver in a message expression.Glossary abstract class A class that’s defined solely so that other classes can inherit from it.” See also synchronous message. a class is said to conform to a protocol if it (or a superclass) implements the methods declared in the protocol. Categories can be used to split a class definition into parts or to add methods to an existing class. or sent to another application. class In the Objective-C language. Programs don’t use instances of an abstract class. without waiting for the application that receives the message to respond. anonymous object An object of unknown class. An instance conforms to a protocol if its class does. See also class object. Decisions made at compile time are constrained by the amount and kind of information encoded in source files. an instance that conforms to a protocol can perform any of the instance methods declared in the protocol. abstract superclass Same as abstract class. compile time The time when source code is compiled. for later use. Class objects are created by the compiler. All Rights Reserved. The Application Kit provides a basic program structure for applications that draw on the screen and respond to events. lack instance variables. class object In the Objective-C language. but it can also be written to memory. Protocols are adopted by listing their names between angle brackets in a class or category declaration. adopt In the Objective-C language. Cocoa An advanced object-oriented development platform on Mac OS X. but otherwise behave like all other objects. archiving The process of preserving a data structure. a class is said to adopt a protocol if it declares that it implements all the methods in the protocol. an object that represents a class and knows how to create new instances of the class. .
encapsulation Programming technique that hides the implementation of an operation from its users behind an abstract interface. Cocoa provides the Foundation framework and the Application Kit framework. id is defined as a pointer to an object data structure. The language gives explicit support to formal protocols. and any class may have an unlimited number of subclasses. factory method Same as class method. inheritance In object-oriented programming. Frameworks are sometimes referred to as “kits.” gdb The standard Mac OS X debugging tool. dynamic binding Binding a method to a message—that is. through a message to super. inheritance hierarchy In object-oriented programming. the hierarchy of classes that’s defined by the arrangement of superclasses and subclasses.. dynamic allocation Technique used in C-based languages where the operating system provides memory to a running application as it needs it.GLOSSARY content view In the Application Kit. finding the method implementation to invoke in response to the message—at runtime. factory Same as class object. each class inherits from those above it in the hierarchy. rather than at compile time. method that has primary responsibility for initializing new instances of a class. All Rights Reserved. the NSView object that’s associated with the content area of a window—all the area in the window excluding the title bar and border. framework A way to package a logically-related set of classes. event The direct or indirect report of external activity. designated initializer The init. 130 2010-07-13 | © 2010 Apple Inc. other init. Each class defines or inherits its own designated initializer. Classes can adopt formal protocols. informal protocol In the Objective-C language. an object that belongs to (is a member of ) a particular class. the ability of a superclass to pass its characteristics (methods and instance variables) on to its subclasses. on-line documentation. factory object Same as class object. . delegate An object that acts on behalf of another object. objects can respond at runtime when asked if they conform to a formal protocol. and other pertinent files. especially user activity on the keyboard and mouse. instead of when it launches. invokes the designated initializer of its superclass. Every class (except root classes such as NSObject) has a superclass. dynamic typing Discovering the class of an object at runtime rather than at compile time. methods in the same class directly or indirectly invoke the designated initializer. All other views in the window are arranged in a hierarchy beneath the content view.. distributed objects Architecture that facilitates communication between objects in different address spaces. Through its superclass. dispatch table Objective-C runtime table that contains entries that associate method selectors with the class-specific addresses of the methods they identify. a protocol declared as a category. Instances are created at runtime according to the specification in the class definition. formal protocol In the Objective-C language.. This allows the implementation to be updated or changed without impacting the users of the interface. instance In the Objective-C language. id In the Objective-C language. This section defines both public methods as well as private methods—methods that are not declared in the class’s interface. but not to informal ones. and the designated initializer. Through messages to self. protocols and functions together with localized strings. among others. implementation Part of an Objective-C class specification that defines its implementation. the general type for any kind of object regardless of class. It can be used for both class objects and instances of a class. usually as a category of the NSObject class. a protocol that’s declared with the @protocol directive.. and instances can be typed by the formal protocols they conform to.
instance variable In the Objective-C language. key window The window in the active application that receives keyboard events and is the focus of user activity. Only menus for the active application are visible on-screen. an application localized in Spanish would display “Salir” in the application menu. Instance variables are declared in a class definition and become part of all objects that are members of or inherit from the class. images. instances variables. link time The time when files compiled from different source modules are linked into a single program. any method that can be used by an instance of a class rather than by the class object. object A programming unit that groups together a data structure (instance variables) and the operations (methods) that can use or affect that data.GLOSSARY instance method In the Objective-C language. in Objective-C. and the protocols it conforms to. message In object-oriented programming. Decisions made by the linker are constrained by the compiled code and ultimately by the information contained in source code. All Rights Reserved. and public-method prototypes. multiple inheritance In object-oriented programming. In the Objective-C language. Used to synchronize thread execution. it would be “Esci. message expression In object-oriented programming. Objective-C doesn’t support multiple inheritance. 131 2010-07-13 | © 2010 Apple Inc. Localization entails freeing application code from language-specific and culture-specific references and making it able to import localized resources (such as character strings. It sets up the corresponding objects for you and makes it easy for you to establish connections between these objects and your own code where needed. In the Application Kit.” main event loop The principal control loop for applications that are driven by events. In Italian. a procedure that can be executed by an object.” in German “Verlassen. localize To adapt an application to work under various local conditions—especially to have it use a language selected by the user. interface Part of an Objective-C class specification that declares its public interface. method In object-oriented programming. . the messages it can respond to. the NSApplication object runs the main event loop. an expression that sends a message to an object. mutex Also known as mutual exclusion semaphore. Symbols in one name space won’t conflict with identically named symbols in another name space. waiting between events if the next event isn’t ready. Interface Builder A tool that lets you graphically specify your application’s user interface. which include its superclass name. name space A logical subdivision of a program within which all names must be unique. and sounds).” and in English “Quit. menu A small window that displays a list of commands. the ability of a class to have more than one superclass—to inherit from different sources and thus combine separately-defined behaviors in a single class. any variable that’s part of the internal data structure of an instance. For example. message expressions are enclosed within square brackets and consist of a receiver followed by a message (method selector and arguments). From the time it’s launched until the moment it’s terminated. For example. Objects are the principal building blocks of object-oriented programs. the method selector (name) and accompanying arguments that tell the receiving object in a message expression what to do. an application gets one keyboard or mouse event after another from the Window Manager and responds to them. an object id with a value of 0. the instance methods of each class are in a separate name space. as are the class methods and instance variables. introspection The ability of an object to reveal information about itself as an object—such as its class and superclass. nil In the Objective-C language.
remote object An object in another application. the name of a method when it’s used in a source-code message to an object. When the object’s reference count reaches zero. subclass In the Objective-C language. a class that’s one step above another class in the inheritance hierarchy. the declaration of a group of methods not associated with any particular class. All Rights Reserved. like C. This technique allows one instance of an object to be safely shared among several other objects. polymorphism In object-oriented programming. selector In the Objective-C language. by typing it as a pointer to a class. the two applications are kept “in sync. reference counting Memory-management technique in which each entity that claims ownership of an object increments the object’s reference count and later decrements it. giving the compiler information about what kind of object an instance is.” See also asynchronous message. 132 2010-07-13 | © 2010 Apple Inc. or the unique identifier that replaces the name when the source code is compiled. procedural programming language A language. that organizes a program as a set of procedures that have definite beginnings and ends. protocol In the Objective-C language. the object that is sent a message. static typing In the Objective-C language. the object is deallocated. each in its own way. Decisions made at runtime can be influenced by choices the user makes. . Outlet instance variables are a way for an object to keep track of the other objects to which it may need to send messages. runtime The time after a program is launched and while it’s running. remote message A message sent from one application to an object in another application. superclass In the Objective-C language. any class that’s one step below another class in the inheritance hierarchy. the ability of different objects to respond. synchronous message A remote message that doesn’t return until the receiving application finishes responding to the message. to the same message. surrogate An object that stands in for and forwards messages to another object. Occasionally used more generally to mean any class that inherits from another class. and sometimes also used as a verb to mean the process of defining a subclass of another class.GLOSSARY outlet An instance variable that points to another object. one that’s a potential receiver for a remote message. the class through which a subclass inherits methods and instance variables. Because the application that sends the message waits for an acknowledgment or return information from the receiving application. receiver In object-oriented programming. Compiled selectors are of type SEL. See also formal protocol and informal protocol.
All Rights Reserved. 119 class methods and selectors 96 and static variables 30 declaration of 36. 59 action messages 97 adaptation 24 adopting a protocol 62.(minus sign) before method names 36 // marker comment 118 @"" directive (string declaration) 119. 120 [“Dynamic Method Resolution”] 19 _cmd 122 __cplusplus preprocessor constant 112 __OBJC__ preprocessor constant 112 BOOL data type 117 bycopy type qualifier 121 byref type qualifier 122 C . 80 Class data type 28. .c extension 10 A abstract classes 26.Index Symbols + (plus sign) before method names 36 . 117 @class directive 37. 121 alloc method 28. 100. 119 categories 79–81 See also subclasses and informal protocols 61 declaration of 79–80 declaring 120 defining 120 implementation of 79–80 naming conventions 123 of root classes 81 scope of variables 80 uses of 61. See root classes 133 2010-07-13 | © 2010 Apple Inc.. 81 and static typing 32 as receivers of messages 32 variables and 30 classes 23–32 root. 122 defined 28 of root class 32 using self 46 class object defined 23 initializing 31 class objects 27–32 and root class 32 and root instance methods 32.
summary of 118–119 distributed objects 105 dynamic binding 18 dynamic typing 14 E @encode() directive 119 @end directive 35. 123 defining 35–42. 25 and instances 23 and namespaces 123 declaring 35–38. 118 in type qualifier 121 #include directive 37 #include directive See #import directive informal protocols 61 See also protocols inheritance 23–26 of instance variables 51 of interface files 37 init method 28. All Rights Reserved. See instance variables data structures. 122 #import directive 37. 120 designated initializer of 53 identifying 14 implementation of 35.h extension 35. See instance variables data types defined by Objective-C 117 designated initializer 53–55 development environment 9 directives. 103 throwing 100 and method declarations 122 and static typing 26. 119 formal protocols 60. 38 instance methods 28 interfaces 35 introspection 14. 121 See also protocols G GNU Compiler Collection 10 H .INDEX abstract 26 and inheritance 23. 27 naming conventions 123 subclasses 23 superclass 23 uses of 32 comment marker (//) 118 compiler directives. 47 initialize method 31 initializing objects 45. 38. summary of 118 conforming to protocols 57 conformsToProtocol: method 106 conventions of this book 10–11 customization with class objects 29–30 F @finally directive 99. 101 synchronization 104 system requirements 99. 120. 103 exception handler 100 NSException 99. 91 as default method return type 36 of class objects 28 overview 14 IMP data type 117 @implementation directive 38. 123 hidden arguments 122 I id data type 117 D data members. 118 implementation files 35. 120 of methods 39. 55 inout type qualifier 121 instance methods 28 and selectors 96 declaration of 122 declaring 36 naming conventions 123 syntax 36 134 2010-07-13 | © 2010 Apple Inc. 38 implementation of classes 38–42. 118 exceptions 99–100 catching 100 clean-up processing 100 compiler switch 99. 100. .
91 initializing 28. 40–42. 118 NO constant 118 NSClassFromString function 32 NSException 99. 47–56 instances of the class See also objects @interface directive 35. 101 NSObject 23. 47. 118. 122 hidden arguments 122 implementing 39. 118 instances of a class allocating 47 creating 28 defined 23 initializing 28. 120 introspection 14. 17 synchronous 107 syntax 117 varying at runtime 19.mm extension 10 N name spaces 123 naming conventions 123 Nil constant 118 nil constant 14. 122 inheriting 25 instance methods 28 naming conventions 123 overriding 25 return types 93. 120 interface files 37. 55 initializing a class object 31 instance variables 17 introspection 27 135 2010-07-13 | © 2010 Apple Inc. 118 defined 13 encapsulation 40 inheriting 24–25.m extension 10.INDEX instance variables declaring 25. 42 naming conventions 123 of the receiver 17 public access to 118 referring to 39 scope of 13. 123 memory allocating 47. 27 isa instance variable 14. 28 isKindOfClass: method 27. 35. 24 NSSelectorFromString function 95 NSStringFromSelector function 95 M . . 45. 96 returning values 14. 55 message expressions 15. 18 and static typing 92 asynchronous 107 binding 92 defined 15. 16 selecting 18 specifying arguments 15 using instance variables 39 minus sign (-) before method names 36 . 96 messaging avoiding errors 97 to remote objects 105–110 metaclass object 28 method implementations 39. 122 methods 13 See also behaviors See also messages adding with categories 79 and selectors 15. 93 calling super 51 class methods 28 declaring 36. 117 sending 15. 117 message receivers 117 messages See also methods and selectors 15. All Rights Reserved. 36. 96 O object 14 object identifiers 14 Objective-C 9 Objective-C++ 111 objects 23 allocating memory for 47 anonymous 59 creating 28 customizing 29 designated initializer 53 dynamic typing 14. 32 isMemberOfClass: method 27 and variable arguments 36 argument types 96 arguments 48.
121 Protocol objects 62 protocols 57–65 adopting 64.. summary of 118 @private directive 40. 119 @try directive 99. 118. 121 informal 61 naming conventions 123 type checking 63 uses of 57–65 proxy objects 105 @public directive 41. 45. All Rights Reserved. 103 @synchronized() directive 103. 122 Smalltalk 9 specialization 24 static type checking 92 static typing 91–94 and instance variables 40 in interface files 38 introduced 26 to inherited classes 93 strings. 46. 92 protocol types 63 136 2010-07-13 | © 2010 Apple Inc. 118 procedures. 118 @protocol directive 65. 119 96 plus sign (+) before method names 36 polymorphism defined 18 precompiled headers 37 preprocessor directives. 122 superclasses See also abstract classes and inheritance 23 importing 37 synchronization 103–104 compiler switch 99. 121 incorporating other protocols 64–65. 64 declaring 57. See methods @protected directive 41. 118 selectors 95 and messaging errors 98 defined 15 self 43. 117 @selector() directive 95. 63. 106. 119 type checking class types 91. 121 formal 60 forward references to 65. 100. declaring 119. 120 subclasses 23 super variable 43. 103 exceptions 104 mutexes 103 system requirements 99. 121 conforming to 57. . 119.
All Rights Reserved.INDEX type introspection 27 types defined by Objective-C 117 U unsigned int data type 122 V variable arguments 36 void data type 122 Y YES constant 118 137 2010-07-13 | © 2010 Apple Inc. . | https://www.scribd.com/doc/45626911/ObjC | CC-MAIN-2017-13 | refinedweb | 37,964 | 52.46 |
Rotate an Image in Java
In this tutorial, we will learn how to rotate an image using Java. First of all, we will download one image and will save it in any folder of our choice on our computer. Then using a java code we will create a new pdf file of any name of our choice and open our downloaded image rotated by some degrees in that pdf file. (we can set degrees in our code and change them according to our need).
Before starting to write our code we need a jar file ie. “itextpdf-5.1.0.jar”
Link to download jar file::
Where to write the code
We can generate this code using any IDE ie. Notepad, Notepad++, Netbeans, Eclipse, etc. But we will use Netbeans as we require jar file ie. itextpdf-5.1.0.jar and using Eclipse or Netbeans it becomes very easy for us to deal with jar-files as we can directly add them to Libraries by just right-clicking on Libraries and clicking Add Jar/Project. But this is not so in case of Notepad and Notepad++, we need to add jar-files to our classpath to use the required jar-files in case of Notepad and Notepad++.
And for writing java codes Netbeans and Eclipse are the best IDE’s. Because most of the code is generated automatically.
Source code to Rotate Image Using Java
package JavaApplication29; import java.io.FileOutputStream; import com.itextpdf.text.Document; import com.itextpdf.text.Image; import com.itextpdf.text.PageSize; import com.itextpdf.text.pdf.PdfWriter; public class JavaApplication29 { public static void main(String[] args) { try { Document documentobj = new Document(PageSize.A4, 20, 20, 20, 20); PdfWriter.getInstance(documentobj, new FileOutputStream("output.pdf")); documentobj.open(); Image imageobj = Image.getInstance("C:\\Users\\lenovo\\Desktop\\kamal\\cartoon.jpg"); imageobj.scaleToFit(200f, 200f); imageobj.setRotationDegrees(180); documentobj.add(imageobj); documentobj.close(); System.out.println("Task completed"); } catch (Exception e) { System.out.println("Exception occured"); } } }
In the above code, JavaApplication29 is the name of the package.
Further, we imported all the required packages required in our code.
We can only import these packages by adding itextpdf.5.1.0.jar file to Libraries of our project.
JavaApplication29 is the name of our class.
In the main method of our class, we are using a try-catch block to handle all the Exceptions. Exceptions may disturb the flow of the program.
Uses of itextpdf-5.1.0.jar
Document Class:: We use the Document class of the iText library to represent pdf documents. We created an instance of Document class ie.documentobj which we can use further to open and close pdf file. To use Document Class we need itextpdf-5.1.0.jar.
PdfWriter:: PdfWriter supports the generation of PDF, XML, RTF files. In this code, we are using PdfWriter for the generation of PDF. fileOutputStream() is used for file handling in java. Output.pdf is the name of the pdf file in which we want to display our result.
“C:\\Users\\lenovo\\Desktop\\kamal\\cartoon.jpg” is the path of our image that we downloaded. Figure on which we want to perform rotation.
Functions
imageobj is the object of Image class.imageobj.scaleToFit() helps us to set the size of the image in the output file.
We use imageobj.setRotationDegrees() to rotate the image. We can use the degree of rotation as the parameter of our method.
The documentobj.open() and documentobj.close() helps us to open and close our pdf files.
Original image::
Output::(180 degree rotation)
Also read: | https://www.codespeedy.com/rotate-an-image-in-java/ | CC-MAIN-2021-10 | refinedweb | 594 | 60.92 |
Develop a Custom Page Tool Tutorial
A page tool is an external web application rendered aside of a page shown in the Channel Manager. It extends the base functionality of BloomReach Experience Manager with third-party functionality.
In this tutorial we are going to add a page tool that renders the JSON data provided by the Channel Manager. The page tool will be named "Show JSON". In the end it will look like this:
Page tool
The show-json page tool will be a separate project based on Webpack. We'll assume NodeJS and NPM are already installed. First create a new project:
mkdir show-json && cd show-json npm init -y npm install --save-dev webpack webpack-cli webpack-dev-server
Add a file called index.html in the root folder:
<!doctype html> <html> <head> <title>Show JSON</title> </head> <body> <script src="main.js"></script> </body> </html>
Create a source folder for JavaScript code:
mkdir src
Create the JavaScript source file src/index.js. It will generate some test output for now:
document.write('Hi!');
Next, edit the package.json file and change the "scripts" entry in there to:
"scripts": { "start": "webpack-dev-server --port 9000 --mode development --watch-content-base" },
Start the Webpack development server using the 'start' command we've just added:
npm start
The "show json" extension can now be viewed separately at.
BloomReach Experience Manager Project
Follow the Get Started steps to create a new archetype project. Install some Essentials features to get a working site. For example, install the "News" feature.
Next we're going to integrate the "show json" extension. Open and navigate to /hippo:configuration/hippo:frontend/cms/ui-extensions and add one node:
definitions: config: /hippo:configuration/hippo:frontend/cms/ui-extensions/showJson: jcr:primaryType: frontend:uiExtension frontend:displayName: Show JSON frontend:extensionPoint: channel.page.tools frontend:url:
Login to the CMS as admin or editor. Navigate to Channels > My Project > Page > Tools. The "show json" tab should now show "Hi!".
Show JSON data
Instead of "Hi" we want to see the JSON data provided by the Channel Manager. Let's go back to the code base of the "show JSON" extension. We'll create our extension using only plain HTML and JavaScript, but any framework may be used.
First install the BloomReach JavaScript client library:
npm install @bloomreach/ui-extension
Next, change the index.html file so it contains two <pre> tags that will show the data:
<!doctype html> <html> <body> UI properties: <pre id="ui"></pre> Page properties: <pre id="page"></pre> <button id="refreshChannel">Refresh Channel</button> <button id="refreshPage">Refresh Page</button> <script src="main.js"></script> </body> </html>
The Webpack dev server will pick up the changes automatically and reload the extension in the Channel Manager. Nice!
Change the src/index.js file to:
import UiExtension from "@bloomreach/ui-extension"; document.addEventListener('DOMContentLoaded', () => { UiExtension.register().then((ui) => { showUiProperties(ui); ui.channel.page.get().then(showPageProperties); ui.channel.page.on('navigate', showPageProperties); onClick('refreshChannel', () => ui.channel.refresh()); onClick('refreshPage', () => ui.channel.page.refresh()); }); }); function showUiProperties(ui) { const properties = pluck(ui, ['baseUrl', 'extension', 'locale', 'timeZone', 'user', 'version']); showJson(properties, 'ui'); } function showPageProperties(page) { showJson(page, 'page'); } function showJson(json, id) { document.getElementById(id).innerHTML = JSON.stringify(json, null, ' '); } function onClick(id, listener) { document.getElementById(id).addEventListener('click', listener); } function pluck(object, properties) { return Object.keys(object) .filter(key => properties.includes(key)) .reduce((result, key) => { result[key] = object[key]; return result; }, {}); }
The code waits for the DOMContentLoaded event to ensure the DOM is ready for changes. Next it calls UiExtension.register() to register the extension with the CMS. The register method returns a Promise that resolves with a ui object.
The ui object contains several properties, which are shown using the showUiProperties() method. It uses a custom pluck() to extract some properties, and displays those as JSON in one of the <pre> tags.
The extension.config property will be set to the string configured in the JCR property /hippo:configuration/hippo:frontend/cms/ui-extensions/showJson/frontend:config. When that JCR property is not set the JSON property will be null. It's up to the extension how to use/interpret the config property (e.g. parse it as JSON).
The timeZone property is only available when the time zone selector is enabled in the login screen.
The ui object also returns data about the current page via ui.channel.page.get() and shows it in the other <pre> tag.
Our page tool also registers a 'navigate' listener. To see this listener in action, navigate to another page by browsing the site in the Channel Manager. The 'navigate' listener will be called for every new page and make our page tool show the new page data.
Last, the extension shows two buttons that refresh the channel and page, respectively. Refreshing the page is probably noticeable. Refreshing the channel may not seem to do much at first, though. To see it in action, use an admin user that views the page tools and a concurrent editor user that changes the channel (e.g. adds a component). When the admin clicks Refresh Channel the yellow changes indicator will appear in the top-left corner. Also the site map in the left side panel will sync. | https://documentation.bloomreach.com/trails/open-ui/develop-a-custom-page-tool.html | CC-MAIN-2019-09 | refinedweb | 875 | 50.23 |
- while loop
- for loop
1.) while Loop:
- A while loop allows a part of code to be executed as long as the given condition is true.
- The while loop is used to repeatedly execute instructions as long as expression is true.
- A while loop is used in the case where the number of iterations is not know in advance.
The while loop has two syntax (forms):
a.) while condition:
statement 1
statement 2
statement 3
statement 1
statement 2
else:
statement 3
statement 4
Note:-else block of codes will be executed when condition fails.Program 1 : Write a python program to add the given numbers.
Output:-Output:-
sum=0 num=int(input("Enter the last number upto which you want to add:\n")) i=1 while(i<=num): sum =sum+i i=i+1 print("The sum of all numbers is= ",sum)
num=int(input("Enter the number:")) i=1 while(i<=num): print(i) i=i+1
Output:-
Infinite while loop:-
- When any while loop condition never become false then while while loop will never terminate.This is called infinite condition.
- Any non-zero values in while loop indicates always true condition and whereas zero indicates the always false condition.
Program 3 : While infinite loop:
num=int(input("Enter non zero number:")) while(num): print("welcome to MNT LAB")
Output:-
import time a=1 num=int(input("Enter a value:\n")) while(1): n=a+num a=a+1 time.sleep(2) print(n)
Output:-
Use the else statement in while loop:-
- The else block is executed when the condition given in while loop becomes false.
- If the while loop is terminated using break statement then else block of codes will not be executed and statement present after the else block will be executed.
Program 5 :Write a python program to print the list values.
list=[1,2,3,4,5,6,7,8,9,10] i=0 while(i<10): print(list[i]) i=i+1
Output:-
Program 6 : Write a python program to print the given numbers.
i=1 num=int(input("Enter the Number upto which you want to print: \n")) while(i<=num): print(i) i=i+1 else: print("While loop is terminated...")
Output:-
Program 7 : Write a python program to print the some numbers out of given numbers.
i=1 num=int(input("Enter the Number upto which you want to print: \n")) while(i<=num): print(i) if(i==8): break i=i+1 else: print("While loop is termineted...")
Output:-
- How to use search and replace functions in python with examples
- How to use split(),count(),partition and join functions in python
- Operators in python with real examples
- Print function complete knowledge in python with examples
- Literal in python with examples
- Learn Complete History of python with examples
- Algorithm concepts in python with examples
Watch Complete Lecture Video:- | https://www.msdotnet.co.in/2020/06/how-to-use-while-loop-repetition.html | CC-MAIN-2022-05 | refinedweb | 478 | 58.92 |
Wikiversity:Initial experiences
This place is for users to describe their experiences here at Wikiversity (WV). Please feel free to write your experience down, as users could scroll past this page and see how others have changed here using Wikiversity!
Recommended: Add your signature after posting about your Wikiversity experiences.
Contents
Atcovi[edit]
For starters, Wikiversity is an "exceptional" wiki... and when I mean "exceptional" wiki, I mean that this place isn't as "strict" as Wikipedia, and the other WMF wikis (you're more "loose"). Here, at Wikiversity, you're here to learn (learning by doing!)... so we all grow here at Wikiversity... one way or the other.
Honestly, with comforting users, and "let-loose" feeling here at Wikiversity, I've grown from a petty vandal that would create articles on Wikipedia about myself, to a "knowledgeable" (at least, better than how I was before). I've worked on several projects, ranging from History to Mathematics (Mathematics Properties). I have even brought on a friend here at Wikiversity: User:Atef1975, who I've invited so he (by a chance) can improve on his studies, by posting his notes online for daily review.
Although he isn't the most dedicated/active, he seems to have an interest... which was a surprise! And, since he is an ar-N (native arabic speaker), I've told him to help with the Arabic pages, so I could learn current day Arabic!
In summary: There is no better Wikimedia Wiki than Wikiversity, to be honest. I've learnt A LOT from this place, and I probably will continue using WV. ---Atcovi (Talk - Contribs) 02:04, 18 January 2016 (UTC)
- Planning on making Wikiversity:Initial experiences/In real life schoolmates joining WV; little essay on my views/points on bringing in schoolmates onto WV. ---Atcovi (Talk - Contribs) 02:46, 18 January 2016 (UTC)
Mu301[edit]
My first thoughts (from a long time ago) were about the possibilities of creating new kinds of lessons in a wiki environment and my frustration with the way content was organized. After a wiki break I now have some "new first impressions" which I will share when I get a chance. --mikeu talk 03:23, 27 January 2016 (UTC)
- I've been updating my User:Mu301/Learning_blog which now contains many of my recent impressions. --mikeu talk 07:22, 8 January 2018 (UTC)
Dave Braunschweig[edit]
My initial experience was one of frustration. There's too much introductory (how to get started) content, not well defined, and some of it contradictory. Examples on the tour are all outdated. Posting on a department talk page (Topic: namespace) goes unanswered, because no one is active. Many of the pages are nothing more than incomplete Wikipedia copies or long, rambling lectures. There's not enough pedagogical design in most of the content here, meaning that it can't be reused for lessons. The learning experience for those was in the creation rather than the sharing.
But, I was exited by the popularity and quality of Wikipedia in my field (IT), and the possibility of doing "mashups" linking Wikipedia readings with YouTube videos and hands-on activities that I could develop. It meant not having to create an entire course, but only needing to curate the resources of others and just adding the pedagogical experience to those materials. It's a very powerful model that has since proven to yield better learning than textbooks alone. The Wikipedia and YouTube content continues to be developed and improved by others, and I can focus on the learning experience.
Dave Braunschweig (discuss • contribs) 22:11, 1 February 2016 (UTC)
Guy vandegrift[edit]
My first impression was excitement, until I began to look at the quality, first of other people's work, then even my own as I reread my first projects. Then I decided to roll up my sleeves and do my best. What keeps me going now is a firm conviction that someday Wikiversity will become important. I base this optimism on two closely related limitations of Wikipedia: only one article per topic, and no POV. No sane person would advocate that Wikipedia should deviate from that mode of operation because it is so successful. That leaves an opening for a different kind of wiki -- one that has not actually been created yet. But I think we are evolving in the right direction--Guy vandegrift (discuss • contribs) 04:18, 2 February 2016 (UTC)
Sam Wilson[edit]
I can hardly remember my initial experience of Wikiversity, but I rather remember that I was more excited about it than I had been about discovering Wikisource (on which project I now spend most of my wiki-time). I was excited because it seemed to me to combine the best aspects of the web, being at a university, and the fun of learning — all in one place. I imagined it rather as Open University except completely open and free (as in libre and gratis). I imagined Wikiversity being a place to work on research, and develop methodologies, and explore any and every aspect of the things that one learns — all things, that is!
For example, at the moment I'm helping get some Nyunga lexicon into Wiktionary, and it seems that that is the sort of activity one could document on Wikiversity. Or an old idea I had (that perhaps I'll get back to one day) of developing some woodworking material here. Currently, I'm wondering what the possibilities are for enabling learning blogs on Wikiversity.
So all up I'd say that my initial experience was good, but that since then things have not developed as I'd thought they would. I have not at all lost hope though!
— Sam Wilson ( Talk • Contribs ) … 09:53, 2 February 2016 (UTC)
Marshallsumter[edit]
I hadn't initially considered Wikiversity because my original research ideas have often met with critical demands for conventionalism, e.g., uniformitarianism over astronomical events causing some extinction of the dinosaurs (this was before the discovery of the iridium layer).
Wikiversity was a safe haven. When I began editing and contributing to Wikipedia, I wrote some test articles, asked for review that I was writing them per Wikipedia instructions, but received nothing. My interest there was to bring some of their articles to the state of the art or science per US copyright law. I had contributed to, written and contributed original research for half a century and wanted to prepare PD-type articles so that I could continue to submit proposals for funding. The fighting I read about and watched first-hand in the beginning there suggested caution. Instead of using my real name I chose Marshallsumter. Looking back that was a wise choice. The resulting attacks, after creating ~ 270 some articles and contributing to a similar number of others, regarding copyright violations and original research appeared to be irrational. A user there and here was apparently spearheading that effort. When someone would point out a good article, he/she would try to find at least one apparent copyright mistake and emphasize it. The fact that I used hyperlinks and cited ≥ 95 % of all statements (I counted to be sure) that were not mine meant nothing. I began preparing to take the WMF (Wikipedia) to US Federal District court for potentially libelous comments and fiscal damage to my reputation. I'd potentially lost an enormous amount of effort and had lost some 3 years. But two things prevented fiscal damage: I'd used a pseudonym and colleagues found what was happening to me from users on Wikipedia to be laughable. Whew!
I was welcomed and helped here by user Abd. Something completely missing at Wikipedia. Dominant group was initially put up for deletion here. With some caution from Abd, I let the process take its course. I wasn't going to put anymore effort into WMF projects. The dominant group project survived. The user apparently spurring the attacks on Wikipedia who was also here has been apparently blocked on both for other activities. Sweet! It's been a win-win. I've been able to submit proposals for potential courses and original research even to the WMF. It's been both learning by doing and by writing. Hopefully some of what I've written has helped Wikiversity in return. I wouldn't recommend going through what I went through on Wikipedia to anyone. Cheers to Wikiversity! --Marshallsumter (discuss • contribs) 21:53, 8 February 2016 (UTC)
Leutha[edit]
At first I was excited about Wikiversity, and worked with a colleague at the University of Westminster on a course. However I soon found that not everyone at Wikiversity was as considerate as I would have liked. Indeed some people seemed to be smarting from unpleasant experiences on Wikipedia, but rather than learn how better to interact with other people preferred to use the relative lack of constraints on Wikiversity as an opportunity to disrupt other peoples work. I originally thought what an amazing potential Wikiversity has. Now I wonder how likely is it to realise even a fraction of those potentials. Leutha (discuss • contribs) 15:08, 10 February 2016 (UTC)
Dumbowski[edit]
Some difficulty in traversing W/U site. The reason I bailed out of site was because you asked me to enable cookies. I will not do that, as much as I might wish to participate. James Reilly, (Australia) 0418 996 548. jimreilly@bigpond.com —The preceding unsigned comment was added by Dumbowski (talk • contribs) 23:16, 13 February 2016 (UTC)
Eiffel[edit]
I had been thinking there should be a place such as Wikiversity, and was wondering how to go about proposing it to Wikimedia Foundation, when today I was astonished to discover that it already existed, and had existed for many years!
After looking around, my excitement gave way to surprise that the project had not advanced further over those years. Why was it still a big jumbly mess surrounding pockets of great content?
This page is for initial experiences, so please don't take this as anything other than my first impression. But my impression is that the project hasn't reached its potential because it is too ill-defined. Whereas Wikipedia has one article per topic, collaboratively polished by a diverse group of people, Wikiversity doesn't have the same tight focus. I guess I expected to find "one lesson per nugget", collaboratively polished. I use the term "nugget" to mean the smallest chunk of learning that can stand alone, such as "How to solve a quadratic equation", or "Introduction to covalent bonds" or "compound interest". Each nugget would have an associated lesson, and also an overview page listing its prerequisites and linking to relevant learning resources, quizzes, etc. Nuggets would of course be grouped into larger bundles - e.g. several nuggets to a module, and several modules to a course.
Now I need to look around Wikiversity further, to see what gems I can find; to try to learn why the project is structured as it is; and to work out whether (or how best) I can contribute within that structure. Thanks for all the work that people have already put into the project - it's a delight to wish for something and then discover that it already exists! Eiffel (discuss • contribs) 10:54, 21 February 2016 (UTC)
AgentCachet[edit]
There are dozens of courses with no content. Some have an outline of topics, but nothing in the outline topics either. Why not delete these, as they are confusing, take up space, and apparently are never going to be finished. (The preceding unsigned comment was added by AgentCachet (talk • contribs) 22 February 2016)
Leolauwhut[edit]
The reason I log in the Wikiversity is that I want to improve myself and learn more things.Hope to become a life-time learner. (The preceding unsigned comment was added by Leolauwhut (talk • contribs) 9 March 2016 at Help:The original tour for newcomers/1)
Jon michael swift[edit]
Hey all, I'm really grateful that folks are holding this project together; I had the instinct that this was how education should be and I'm glad I found a community that shares my passion for this kind of education. The trickiest part is just getting oriented to all that there is! At first I was really struggling to get the code for page editing correct and then I learned about the visual editor. That helped a lot. Still, I came with a plan and there's an obvious learning curve to getting into it. I can definitely handle it, but as I bring students in (especially younger ones) they may struggle more with the first editing and orientation. I think making the visual editor the default would help less web-savvy users get started. I also find it a little unwieldy to find the right discussions and the right people. The whole interface is very raw and text-based, making it a little less inviting to find other projects. I also understand that since things are community-built that not everything is at the same stage, but most of the places I looked first seemed to be at very undeveloped stages and that's a little disheartening. I think giving new users an even stronger set of examples of what the best projects look like in the tour would really help.
Nevertheless, I can tell that this is a robust community with a grand vision and I'm throwing my chips in with this team for sure. Look forward to meeting you, Wikiversity!
--Jon michael swift (discuss • contribs) 23:23, 16 April 2016 (UTC)
Patrik Näsfors[edit]
I just found this site a few hour ago, while searching for free online learning resources, specifically IT security and some certification, which I also found, so that was positive. Thanks to Dave Braunschweig for creating that project!
The reason for searching, is because I am attending a course, which is primarily based on a regular book and that is not free of course. Because there is so much information available (for free) on the Internet, I initially thought about creating my own website or blog with links to content covering the topics we will go through.
After a while I found a few free MOOC courses, but those did not fit my need, so I continued to look and ended up here. The course I found is not complete, but now I don't have to create something from scratch, but can append to the existing project. The chance that it will be found and used by others are also a lot greater, when it will reside here. So all these are positive things.
A big negative side, as I see it initially here at my first visit, is that there is no possibility to track my progress. Since the concept of this site is learning and "projects" consisting of (potentially) a lot of pages, I would consider it essentially to track progress and do some more interactive stuff. It's perfectly fine that you can access and edit all content without registering, but I think there should be some tracking/interactive options for registered users who would like that option. The above page says "None of this currently exists on Wikiversity", but it doesn't say why. Is it because of technical issues that it is difficult to implement, limited resources to get it implemented or "political" issues that you don't want to do it? I'm just wondering.
Despite that, I think I will start using it anyway. That was my first impressions :-)
Patrik Näsfors (discuss • contribs) 02:59, 26 April 2016 (UTC) | https://en.wikiversity.org/wiki/Wikiversity:Initial_experiences | CC-MAIN-2018-34 | refinedweb | 2,609 | 60.45 |
There is a bunch of cool stuff coming out of Microsoft right now. As I’ve previously blogged, WCF Web APIs is one of them. One of the cool things that was shown by Glenn Block at PDC a couple of weeks ago was Media Type Processors. Media Type Processors provide a way to allow the consumer of your service to be able to specify the format they want on their response simply by setting the Accept header on the request (and thereby allowing your service to conform to HTTP standards). Out of the box, WCF will support xml, json, and OData. However, at PDC, they also demonstrated building a PngProcessor which would return a png image from WCF by setting the Accept header to “image/png”. Yes, you heard that right – WCF returning an image!
In the PDC demo, a Contact Manager application was used to show that you could request the same URI for a given contact but get back different representations for that resource depending on the requested media type. The WCF code for the service knows nothing of formats – it is only concerned the logic for returning the appropriate resource. The concerns for the formatting is totally encapsulated in the media type processors. For example, (using Fiddler) and executing a GET request for “/contact/4”, a default request returns XML:
An Accept header of “application/json” results in json:
An Accept header of “image/png” results in an image (made possible by the PngProcessor):
All for the same URI.
Wouldn’t it also be nice to be able to return HTML if a consumer specified an Accept header of “text/html”? Wouldn’t it be nice to just hook this into the WCF pipeline? And wouldn’t it also be nice to be able to use the Razor view engine even though we’re using WCF and not MVC 3? Andrew Nurse recently had a blog post which gave details on how to host Razor outside of ASP.NET. This was also demonstrated at PDC. (If you don’t think that is cool, you might have to check to make sure you still have a pulse)
I want to be able to use a Razor template that looks something like this:
1: <html>
2: <body>
3: <p>Name: @Model.Name</p>
4: <p>Email: @Model.Email</p>
5: <p>Address: @Model.Address</p>
6: <p>City: @Model.City</p>
7: <p>State: @Model.State</p>
8: <p>Zip: @Model.Zip</p>
9: <p>Twitter: @Model.Twitter</p>
10: </body>
11: </html>
Now I need some way to invoke that Razor template. But I also need to be able to specify a model. In order to do that, I’ll make a slight change to the TemplateBase class that Andrew Nurse provided in his sample:
1: public abstract class TemplateBase
2: {
3: public StringBuilder Buffer { get; set; }
4: public StringWriter Writer { get; set; }
5:
6: public TemplateBase()
7: {
8: Buffer = new StringBuilder();
9: Writer = new StringWriter(Buffer);
10: }
11:
12: public abstract void Execute();
13:
14: public virtual void Write(object value)
15: {
16: WriteLiteral(value);
17: }
18:
19: public virtual void WriteLiteral(object value)
20: {
21: Buffer.Append(value);
22: }
23:
24: public dynamic Model { get; set; }
25: }
The only change I’ve made is that, on line #24, I added a property for the Model which I typed as dynamic. That is what makes it possible for me to simply refer to @Model in the razor template I showed above. So the final step is that I need a way to pass in that model to my template. Well, with the WCF bits available from CodePlex, this is now quite easy to do. Ultimately, I need to create my own HTML Processor to hook into the pipeline.
1: public class RazorHtmlProcessor : MediaTypeProcessor
3: public RazorHtmlProcessor(HttpOperationDescription operation, MediaTypeProcessorMode mode)
4: : base(operation, mode)
5: {
6: }
7:
8: public override IEnumerable<string> SupportedMediaTypes
9: {
10: get { yield return "text/html"; }
11: }
12:
13: public override void WriteToStream(object instance, System.IO.Stream stream, Microsoft.Http.HttpRequestMessage request)
14: {
15: var templateManager = new TemplateEngine();
16: var currentTemplate = templateManager.CreateTemplate(instance.GetType());
17:
18: // set the model for the template
19: currentTemplate.Model = instance;
20: currentTemplate.Execute();
21: using (var streamWriter = new StreamWriter(stream))
22: {
23: streamWriter.Write(currentTemplate.Buffer.ToString());
24: }
25: currentTemplate.Buffer.Clear();
26: }
27:
28: public override object ReadFromStream(System.IO.Stream stream, Microsoft.Http.HttpRequestMessage request)
29: {
30: throw new NotImplementedException();
31: }
32: }
Notice that all I need to do on line #10 is to specify which media types I can respond to. Then I simply have a stream I can write directly to in the WriteToStream() method. This allows me to now request “text/html” and you can see I now get HTML returned from WCF:
I’ve excluded the code of the TemplateEngine in this post in the interest of brevity. It closely matches the sample by Andrew Nurse – I just had to make a few tweaks to enable the ability to bind to dynamic types as well as to be able to read the Contact.cshtml file from disk. My complete code sample can be downloaded here (the contact manager parts are copy/paste from the sample available on the WCF CodePlex site). It is far from Production-ready (e.g., it’s currently hard-coded to read only the Contact.cshtml file but could easily be extended UPDATE: I’ve updated code so engine now dynamically loads template based on type; for example, for a Contact object, it will find Contact.cshtml, borrowing the concept from MVC EditorTemplates) but this gives you a glimpse of the types of things that are now possible when combining the WCF HTTP library with a custom-hosted Razor view engine! | http://geekswithblogs.net/michelotti/archive/2010/11/17/combine-wcf-mediatypeprocessors-with-a-custom-razor-host.aspx | CC-MAIN-2015-27 | refinedweb | 967 | 61.87 |
Items. Read the docs page for the respective binding to get more information about possible connections and examples.
There are two methods for defining items.
If the binding supports it, PaperUI can do this.
Otherwise items must be defined in one or more files in the
items folder.
Files here must have the extension
.items but you can make as many
.items files as you need/want however each item must be unique across them all.
Refer to the installation docs to determine your specific installations folder structure.
Groups are also defined in the
.items files.
Groups can be nested inside other groups, and items can be in none, one, or multiple groups.
Typically items are defined using the openHAB Designer by editing the items definition files. Doing so you will have full IDE support like syntax checking, context assist etc.
Item Syntax
Items are defined in the following syntax:
itemtype itemname ["labeltext"] [<iconname>] [(group1, group2, ...)] [["tag1", "tag2", ...]] [{bindingconfig}]
Note: Parts in square brackets ([]) are optional.
Example:
Number LivingRoom_Temperature "The Temperature is [%.1f °C]" <temperature> (gTemperature, gLivingRoom) ["TargetTemperature"] {knx="1/0/15+0/0/15"}
The example above defines an item:
- of type
Number
- with name
LivingRoom_Temperature
- formatting its output in format
%.1f °C(See Formatting section for syntax explanation)
- displaying icon
temperature
- belonging to groups
gTemperatureand
gLivingRoom
- tagged as a thermostat (“TargetTemperature”) for usage with I/O addons like Hue Emulation
- bound to the openHAB binding
knxwith write group address
1/0/15and listening group address
0/0/15
Item Types
The item type defines which kind of values can be stored in that item and which commands can be sent to it.
Each item type has been optimized for certain components in your smart home. This optimization is reflected in the data types, and command types.
An example: A Philips Hue RGB light bulb provides three pieces of information. Its on or off state, its current brightness, and the color.
If you want to change one of these values you can use any of four item types.
- Switch the bulb on or off (
Switchitem)
- Increase or decrease the brightness (
Dimmeritem)
- Set the brightness to a specific value (
Numberitem)
- Change the bulb’s color (
Coloritem)
All available openHAB2 item types and their relevant commands can be viewed here.
Dimmers vs Switches
While a Dimmer item can accept either On/Off, Increase/Decrease, or Percent updates, Dimmer items store their state as a Percent value. See the following example:
item:
Dimmer Light_FF_Office "Dimmer [%d %%]" {milight="bridge01;3;brightness"}
Switch item=Light_FF_Office Slider item=Light_FF_Office
When the Switch widget is used, it sends ON or OFF commands to the item, but these are mapped to 100% and 0%, respectively. When the slider widget is used, it sends Percent commands to the item, which are used as the item’s state. In the example above, if you move the Slider widget to 60%, move the Switch to OFF, and finally move the switch to ON, the item’s state will be 100%.
Item Name
The item name is the unique name of the item which is used in the .sitemap, .rule etc. files. The name must be unique across all item files. The name should only consist of letters, numbers and the underscore character. Spaces cannot be used.
Item Label
The label text has two purposes. First, this text is used to display a description of the specific item (for example, in the sitemap). Second, it can be used to format or transform output from the item (for example, making DateTime output more readable). If you want to display a special character you must mask the character with a ‘%’. So, to display one ‘%’ enter the text ‘%%’.
Groups
The item type group is used to define a group in which you can nest/collect other items, including other groups.
You don’t need groups, but they are a great help for your openHAB configuration.
Groups are supported in
rules,
functions, the
bindingname.cfg files, and more places.
In all these places you can either write every single applicable item, i.e. All temperature sensors, or if you have grouped your items, you just use this group instead.
A simple example group definition is:
Group TemperatureSensors
Nested Groups
To take this a step further you can begin to nest groups like in the example below:
Group All Group gSensor (All) Group gTemperature (gSensor) Number Sensor_Temperature "The Temperature is [%.1f °C]" <temperature> (gTemperature) {knx="1/0/15+0/0/15"}
The item
Sensor_Temperature is a member of the group
gTemperature, which is itself a member of the group
gSensor, which is a member of the group
All.
The item will only be included into each group once, regardless of the number of times the group is nested.
To give an example: the item
Sensor_Temperature only exists once in the group
All.
Group item types
Group items can also be used to easily determine one or more items with a defined value or can be used to calculate a value depending on all values within the group. Please note that this can only be used if all items in the group have the same type. The format for this is:
Group:itemtype:function itemname ["labeltext"] [<iconname>] [(group1, group2, ...)]
By default, if no function is provided to the group, the Group uses OR. So for a Group of switches the Group state will be ON if any of the members states are ON. But this means that once one Item in the group has its state change to ON, the Group’s state gets set. Each subsequent Item that changes state to ON will not trigger “myGroup changed” because the Group isn’t changing.
This is not a bug, it is the expected and designed behavior. Because the group state is an aggregate, every change in the Item members does not necessarily result in a change to the Group’s state.
Group functions can be any of the following:
An example of this would be:
Group:Contact:OR(OPEN,CLOSED) gMotionSensors (All)
Formatting
Formatting is done applying Java formatter class syntax, therefore the syntax is
%[argument_index$][flags][width][.precision]conversion
Only the leading ‘%’ and the trailing ‘conversion’ are mandatory. The argument_index$ must be used if you want to convert the value of the item several times within the label text or if the item has more than one value. Look at the DateTime and Call item in the following example.
Number MyTemperature "The Temperature is [%.1f] °C" { someBinding:somevalue } String MyString "Value: [%s]" { someBinding:somevalue } DateTime MyLastUpdate "Last Update: [%1$ta %1$tR]" { someBinding:somevalue }
The output would look like this:
Temperature 23.2 °C Value: Lorem ipsum Last Update: Sun 15:26
Transforming
Another possibility in label texts is to use a transformation.
They are used for example to translate a status into another language or convert technical value into human readable ones.
To do this you have to create a .map file in your
transform folder.
These files are typical key/value pair files.
key1=value1 key2=value2 ...
Let’s make a small example to illustrate this function. If you have a sensor which returns you the number 0 for a closed window and 1 for an open window, you can transform these values into the words “opened” or “closed”. Create a map file named window.map for example and add the desired keys and values.
0=closed 1=opened NULL=unknown -=unknown
Next we define two items. One showing the raw value as it is provided from our sensor and one with transformed value.
Number WindowRaw "Window is [%d]" { someBinding:somevalue } Number WindowTransformed "Window is [MAP(window.map):%s]" { someBinding:somevalue }
The output will be:
Window is 1 Window is opened
Transform files use UTF-8 encoding, so Unicode symbols will also work.
ARIES=♈ Aries TAURUS=♉ Taurus WAXING_CRESCENT=🌑→🌓 Waxing Crescent FIRST_QUARTER=🌓 First Quarter
Icons
OpenHAB provides you a set of basic icons by default.
However if you wish to use custom icons you need to place them inside the
conf/icons/classic/ folder.
These icons will be used in all of the openHAB frontends.
The images must be in .png or .svg format, and have a name with only small letters and a hyphen or underscore (if required).
The PaperUI interface (or via the classicui.cfg or basicui.cfg files) allows you to define whether you use Vector (.svg) or Bitmap (.png) icon files.
As an example, to use a custom icon called
heatpump.svg the correct syntax is
<heatpump>.
Dynamic Icons
You can dynamically change the icon depending on the item state. You have to provide a default file and one icon file per state with the states name append to the icons name.
Example:
switch.svg switch-off.svg switch-on.svg
If you want to use the dynamically items just use the image name without the added states.
Switch Light_FrontDoor "Front Door light is [MAP(en.map):%s]" <switch> {somebinding:someconfig}
Binding Configuration
The binding configuration is the most import part of an item. It defines from where the item gets it values, and where a given value/command should be sent.
You bind an item to a binding by adding a binding definition in curly brackets at the end of the item definition
{ channel="ns:bindingconfig" }
Where ns is the namespace for a certain binding like “network”, “netatmo”, “zwave” etc. Every binding defines what values must be given in the binding configuration string. That can be the id of a sensor, an ip or mac address or anything else. You must have a look at your Bindings configuration section to know what to use. Some typical examples are:" }
When you install a binding through PaperUI it will automatically create a
.cfg file in
conf/services/ for the appropriate binding.
Inside these files are a predefined set of.
If you need to use legacy openHAB 1.x bindings then you need to enable this feature through the PaperUI menu by turning on “Include Legacy 1.x Bindings” found at
/configuration/services/configure extension management/.
After downloading the legacy .jar files, they need to be placed in the
/addons/ folder.
If further configuration is required then you will need to create an
openhab.cfg file in
/conf/services/ and paste the appropriate binding configuration into this.
For all other native openHAB2 bindings, configuration is done through a
bindingname.cfg file in the same location.
Restore States
When restarting your openHAB installation you may find there are times when your logs indicate some items are UNDEF. This is because, by default, item states are not persisted when openHAB restarts. To have your states persist across restarts you will need to install a Persistence extension.
Specifically, you need to use a
restoreOnStartup strategy for all your items.
Then whatever state they were in before the restart will be restored automatically.
Strategies { default = everyUpdate } Items { // persist all items on every change and restore them from the MapDB at startup * : strategy = everyChange, restoreOnStartup } | http://docs.openhab.org/configuration/items.html | CC-MAIN-2017-22 | refinedweb | 1,827 | 64.51 |
I’ve been having an interesting talk with Doug McClean about appropriate locations of methods. We’re discussing if the ICollection<A> interface should include the Transform method. Specifically should the interface look like this:
public interface ICollection<A> {
…
ICollection<B> Transform<B>(IBijection<A,B> bijection);
…
}
Doug thinks (feel free to correct me Doug and I’ll update this page) that Transform isn’t really appropriate on the main collection interface because it carries a burden on consumers of the ICollection interface to understand it. Instead it should be pushed down a specialized subinterface (like ITransformableCollection) and a dummy implementation on a helper class. i.e.
public static class CollectionHelpers {
public static ICollection<B> Transform<A,B>(ICollection<A> collection, IBijection<A,B> bijection) {
ITransformableCollection<A> tc = collection as ITransformableCollection<A>;
if (tc != null) {
tc.Transform<B>(bijection);
}
return new TransformedCollection<A,B>(collection, bijection);
}
}
(where TransformedCollection is a specialized class that uses the bijection to pass values to and from the underlying collection).
I was thinking about this and trying to determine how you decide what should go on an interface. One could make the argument that you should keep the interface as simple as possible and only provide the bare minimum of methods that give you full funcationality. However, if I were to take that argument to it’s logical conclusion than the entire ICollection interface would look like:
public interface ICollection<A> {
B Fold(Function<B,Function<A,B>>, B accumulator);
}
Using that one could get every other bit of functionality that is in the list interface. You could implement ‘ForAll’, ‘Exists’, ‘Find’,’Count’, ‘Iterate’, ‘Transform’, ‘FindAll’, ‘Filter’, and everything else in the current interface on top of Fold. However, this wouldn’t be a very convenient interface to use. All you’d ever see was folds and you’d always be asking yourself “what is this fold doing?” Chances are a lot of those times you’d be doing something like ‘counting’ or ‘finding an element’. And so one could argue “certain actions that people commonly do on a collection should be pushed into the interface”. So what happens when you run into a method like ‘Transform’. I’ve already run into cases where I’ve needed it. However, is it common enough that other people will run into it? Or is it something that will be used all of 0.01% of the time. Is that enough to keep it in the interface? Should that even be part of the criteria?
I’d love thoughts on this problem, addressing this issue if possible, or other cases where you’re run into this.
Good summary of my position, Cyrus, I have no objections to that characterization.
It’s obviously a matter of opinion, but I think that the existing FCL design of ICollection is fine (count, synchronization, and enumerability). Copying to an array is questionable, because it’s easily defined on top of enumerability and Count, but I think that almost all or all likely collection designs can provide more performant implementations and the burden of understanding is low.
Agreed that the fold-only definition is the logical conclusion, but even that can be defined on top of IEnumerable. Basically ICollection is just IEnumerable with a known Count. If you know more, such as that an ordering exists, IOrderedCollection could allow easily finding the Max and Min. ITransformableCollection could allow you to provide a more performant implementation of Transform than standard.
Defining the Collection by the fold-only method basically inverts a principal design decision of .NET collections, which was to use external iterators through the IEnumerable interface. Fold is essentially the general purpose internal iterator method.
My head is about to explode, I need to stop thinking about this for a while and watch some baseball.
Doug: Actually, my collections don’t have a Count property. Otherwise they wouldn’t be able to represent infinitely large collections. I’ve left out count because of that.
Yeah, I’ve had issues with infinitely large collections too. Maybe ICollection just doesn’t exist, and we should mix and match IEnumerable, IFiniteCollection, ITransformableCollection, …
One abstraction at a time.
Also, this isn’t a big deal, but my name is McClean not McLean (in the article).
Something else to think about here (which could go on the language feature request thread too) is that at this level of granularity, which I think is conceptually useful, it is difficult to properly type your parameters if you require some features of more than one interface. This can sometimes be worked around with generic methods and constraints, but I’m wondering if there isn’t a more general solution.
In general, a set of interface types A = {I1, I2, .. IN} defines another type TypeA that only allows values that are of types that implement every interface in A. Could we use types like that as parameter types?
Doug: Could you explain the last bit about the set of interface types?
Sure Cyrus. You were actually talking about it before in a really old post, about how having lots of small interfaces is unwieldy if you need access to features from some set of them in order to write a method.
Postulate these types:
interface IEnumerable<T> // as defined in mscorlib now
interface IFiniteCollection<T> : IEnumerable<T> {
int Count {get;}
}
interface IOrderedCollection<T> : IEnumerable<T> {
IOptional<T> MaximumValue {get;}
IOptional<T> MiniumValue {get;}
IEnumerator<T> GetOrderedEnumerator();
}
Suppose you desire to write a method that will return the third quartile of a collection of some numeric type that can be subtracted and divided. Since we haven’t worked out the operators yet, lets just suppose the type is double, so that we have this:
SomeFiniteOrderedCollectionType<double> theList; // initialized somehow
// note that SomeOrderedCollectionType<T> : IFiniteCollection<T>, IOrderedCollection<T>, …
Our problem is, we need access to the count, from IFiniteCollection<T>, and the maximum and minimum values from IOrderedCollection<T>, but we don’t want to require the concrete type of the parameter be anything specific. Ooops. Now we are up a creek without a paddle. We could type the parameter as one or the other, and throw an exception if it wasn’t both. Or type it is IFiniteCollection<T> and fallback to searching for the Min and Max if it happened not to be IOrderedCollection<T>, but suppose that we don’t want either of those solutions. (I am trying to make a simple example of a case where we need access to two distinct interfaces.)
Suppose we had a syntax like this:
double ComputeThirdQuartile({IFiniteCollection<double>,IOrderedCollection<double>} list) {
// in here, the compiler knows that list implements both IFiniteCollection<double> and IOrderedCollection<double>, and requires callers to pass something that is both those things
return (list.MaximumValue – list.MinimumValue) / list.Count;
// TODO: handle the case of empty list and hence unwrapping the IOptional<double> instances. Consider this psuedocode to get my point across.
}
This obviously could be refined, or we could change the syntax, or whatever, but my point is that we should think about this because it removes the number one drawback to using very granular interfaces, namely that they can’t be freely mixed and matched.
Doug: I see exactly what you mean now. Another alternative is this:
double ComputeThirdQuartile<T>(T list) where T : IFiniteCollection<double>, IOrderedCollection<double> {
}
But it’s certainly verbose.
I think what I’d prefer is if C# moved to having a system where we combined type inference and structural subtyping so that you could just do:
double ComputeThirdQuartile(list) {
uint count = list.Count;
IOptional<double> max = list.Max;
}
and then we’d figure out all the types.
Yeah, that’s what I had in mind when I wrote "This can sometimes be worked around with generic methods and constraints, but I’m wondering if there isn’t a more general solution." Maybe it can always be worked around, but I have a feeling I had a counter-example once. I might find it in my notes somewhere. Declaring a return type like this, would be one complication.
I like the type inference, to a point. But there are serious versioning issues, I think, as well as issues with abstract and virtual declarations. It could be a good approach for some languages, but it doesn’t seem in keeping with the C# style in some ways.
This area seems worth some more thought. I’m not sure any of our three approaches so far is the way to go entirely.
This is fascinating stuff, guys!
Some thoughts—
– The pattern of querying for optional interfaces and falling back to a general implementation in terms of other interfaces, as you demonstrate with Transform<A,B>, is *very* handy. Follow my link for more musings on this. Letting an implementer derive from IEnumerable<T> alone, while giving a caller a convenient way to call Count, is the best of all worlds, far superior to using abstract base classes as some suggest. The main downside is that you need a *static* function Count to encapsulate the query-call/fall, which is a little harder when you want to type l-i-s-t-dot and find the proper method in IntelliSense. But we already face that as, for example, with Array.Sort (thank goodness!). This was one of the great things about STL—with static functions doing all the algorithmic work, one person can add things like stable_partition while another adds things like hash_set and neither has to know about the other. And, returning to C#, if a caller really needs an IFiniteCollection<T> to pass to something else, one can always offer a method to build one off an arbitrary IEnumerable<T>, with the caveat that you can’t query it for other interfaces on the original object (I muse about this problem too).
– So I say: at least offer an interface with the absolute bare minimum (Fold or whatever). Then offer other interfaces, possibly derivative, in case someone decides, for example, that there is a better way to count the elements in an array than by using enumeration & iteration (duh). But we must be clear that these other interfaces are for specialization (maybe hide them on the class as with IConvertible), otherwise users will demand to see them everywhere, and we’ll end up with interface bloat yet again.
– It is possible to define an interface that combines two other interfaces and adds nothing (e.g. interface IBoth : ILeft, IRight {}), but unfortunately implementing this interface is not considered the same as just implementing the two base interfaces. Or, you often see interfaces that inherit from other interfaces for no sound reason besides convenience, like IDataReader, which is interface bloat again. If you start down this slippery slope then you end up with monstrosities like IFiniteOrderedTransformableCollectionThatCanMakeToastAndWalkYourDog, for any combination of any two or more interfaces anywhere in the framework.
– Users get frustrated when they *know* a class implements each of two independent interfaces, but they can’t use a single reference of either interface type without letting go of the other one and having to cast later on; so, they end up abandoning interfaces altogether and using the class interface directly, which is no better than an anonymous instance of the aforementioned monstrosity (worse, IMHO).
– In cases like ComputeThirdQuartile where you use two independent interfaces, can’t you just accept two parameters? You then lose the constraint that they be on the same object, but when do you ever really need that constraint? Saying ComputeThirdQuartile(list, list) does look kind of strange, though.
– The idea of {I1, I2} as—how do you say?—an implicit aggregate interface is very interesting. Then, I suppose, any class that implements both I1 and I2 will automatically implement {I1, I2}, and you can have a List<{I1,I2}> if you like. Besides making certain things a lot simpler, I think this does solve some real, though perhaps obscure, problems not yet covered by generics; for example:
interface I1 { int F1(); }
interface I2 { int F2(); }
class Cat : I1, I2 { void Meow() {…} int I1.F1() {…} int I2.F2() {…} }
class Dog : I1, I2 { void Bark() {…} int I1.F1() {…} int I2.F2() {…} }
interface IFoo<T> { int Bar(T x); }
class Foo<T> : IFoo<T> where T : I1, I2 { int Bar(T x) { return x.F1() – x.F2(); } }
class Test { public int TryMe<T>(IFoo<T> i) where T : I1, I2 { return i.Bar(new Cat()) – i.Bar(new Dog()); } }
Then you try to create a Foo<T> to pass in to TryMe and realize that no choice of T will work, because T must derive from both I1 & I2 and yet be a base of both Cat & Dog. The only way we solve this now is to slide down that slippery slope, to anticipate the problem when writing Cat & Dog and explicitly create & use a third interface serving no other purpose than to aggregate I1 & I2. What we really need is to make the aggregation of I1 & I2 a valid type in its own right. Or am I missing an obvious better way?
Another thing enabled by types like {I1, I2} is a language syntax like this:
SomeType x; // init somehow
x.DoStuff();
x.DoOtherStuff();
when(x is I1) {
// variable x has the type {SomeType, I1} in this scope
x.DoStuffDefinedByI1();
}
This would be much easier to use and more readable than the ubiquitous:
I1 xAsI1 = x as I1; // it’s usually difficult to name this new variable
if(xAsI1 != null) {
xAsI1.DoStuffDefinedByI1();
}
Code of this type is a common source of mistakes or inefficiencies in beginner’s C# programs also, and syntax support for this scenario would go a long way to changing that. | https://blogs.msdn.microsoft.com/cyrusn/2004/06/20/how-do-you-decide-what-goes-in-an-interface/ | CC-MAIN-2016-30 | refinedweb | 2,279 | 51.48 |
Mrope, at some point I think "Open Files" will act in a similar way to project folders on which "Remove Folder from Project" appears but the normal menu appears too.Regards
So after a lot of trial & more error with these 7 commands, I managed to get them all working! I did have to change your commands however; none of them worked in their provided state, so I experimented - removing backslashes, spaces etc - until I finally tried the commands without any backslashes & just entered the file/app locations as they & low & behold,they worked.
I had to change 6 & 7's app name to Adobe Photoshop CS5 as that's how my app is named.
Just so we're clear, here's one of them:
import subprocess; subprocess.Popen('open', '-a', '/Applications/Adobe CS5/Adobe Photoshop CS5/Adobe Photoshop CS5.app', 'Logo.psd'], cwd='/Users/mrmartineau/Dropbox/Work/Web/Clients (Current)/Company/Logo/')
After that I thought I would toy around with the sublime-menu file, which I got working. Instead of providing the app's location, I just provided the name (without backslashes if there are spaces etc) and it now works perfectly!! Here's my full sublime-menu file for reference:
{"id": "side-bar-files-open-with",
"children":
//application 1
{
"caption": "Photoshop",
"id": "side-bar-files-open-with-photoshop",
"command": "side_bar_files_open_with",
"args": {
"paths": ],
"application": "Adobe Photoshop CS5.app",
"extensions":"psd|png|jpg|jpeg|gif" //any file with these extensions
}
},
//separator
{"caption":"-"},
//application 2
{
"caption": "Espresso",
"id": "side-bar-files-open-with-espresso",
"command": "side_bar_files_open_with",
"args": {
"paths": ],
"application": "Espresso.app",
"extensions":"css" //open all even folders
}
},
//application n
{
"caption": "CSS Edit",
"id": "side-bar-files-open-with-cssedit",
"command": "side_bar_files_open_with",
"args": {
"paths": ],
"application": "CSSEdit.app",
"extensions":"css" //any file with extension
}
},
{"caption":"-"}
]
}
]
If you need more info, let me know..
Thanks, please update and let me know if still works for you.Also, it would be good if you can test the button "Open / Run" and let me knowRegards
I have buid 2144 and I installed it through the package control. It worked fine on Mac (Open With menu) after replacing the Windows config with the one posted by MrMartineau on his latest reply without any change.
This plugin has been updated:
This plugin has been updated to include the preference "close_affected_buffers_when_deleting_even_if_dirty" which is by default "False".
This preference allow you to automatically close all the buffers affected by a deleting operation.
Regards.? | https://forum.sublimetext.com/t/sidebar-enhanc-clipboard-open-with-reload-renamed/2784/27 | CC-MAIN-2016-22 | refinedweb | 404 | 50.67 |
cursor location
cursor location hi,please how to change cursor location by java code ,i use this code but not change the location
JTextArea a=new JtextArea();
if(resultText.equalsIgnoreCase("class")){
a.append("a { \n }");
PointerInfo
Location finding error - JSP-Servlet
Location finding error Location needs from drive name:
My file uploading program has an error. It requires the location should be given from... information from JSP Request Header
String contentType = request.getContentType
Java Get Class Location
Java Get Class Location
... location. For this, we
have used the classes URL and ClassLoader. The class...(classLocation)
returns the location of the class.
import
java code - JSP-Servlet
java code hi i have made an application in which i have a fuctionality. in which i get the location of xml files as links on jsp page and when... the tomcat.Also check the location of xml files.
Thanks
Find Exact Location from IP address in java?
Find Exact Location from IP address in java? I am looking for API where we can pass IP address and get the location (Cityname,Country name).
please suggest any API OR sample code.
Thank you
Location Reminder
Location Reminder Hi, i am planing to do a project called location... mark thar place in my mobile, and later if i visit that location,my mobile has to give a reminder.
How to mark a location on mobile using GPS?
Please give me
how to write function of copy from one to another location in this code
how to write function of copy from one to another location in this code I need to write a code to copy a file from one location to another using browse button in it. i have written code for the browse button. please help me
Byte Code
Byte Code
Bytecode is a term
that denotes a form of intermediate code, a binary representation... defines java instruction set which
has one-byte opcodes followed by optional
Hot to Upload TIFF file to a sepcified location - JSP-Servlet
is i need to upload a TIFF file to a specified folder location on any other... folders... So please help me to get this code as soon as possible this would... tech team
Thank you in advanced
please send the code
How to display Jfreechart from servlet in jsp web page at specified location
How to display Jfreechart from servlet in jsp web page at specified... in Servlet which is in image format.plz sir give me the code to display this chart in jsp web page .
Thank you very much Sir
File location in FileOutputStream - JSP-Servlet
File location in FileOutputStream Hai,
For uploading a file i... a method to specify a location to store the file which is uploaded. I required...\webapps\mca2006sfssjc.co.in\stud\images
by changing the location to the folder
jsp code - Java Beginners
JSP code and Example JSP Code Example :
<%@ page language="java" contentType="text/html; charset=ISO-8859-1... = con.createStatement();
st.executeQuery(query);
%>
<jsp:forward
Java Code - JSP-Servlet
Java Code Write a JSP program which displays a webpage containg arrival of new items within a particular month in the different branches of a retail company
JavaScript method location
JavaScript method location... using location property of the window object. One of
them is location.href which... the user to it.
Here is the code:
<html>
<h2>Use of property
java code - JSP-Servlet
java code Code to send SMS through mobile to a web application
jsp code - Java Beginners
jsp code hello sir
i have a problem in in loop while(itr.hasNext... to retrieve the value of staxapp when i wana use it in entire jsp.
thanks Hi Friend,
Try the following code Code - Java Beginners
Jsp Code Hi,
I am new to java programming & as per the requirement, i need to implement a 'SEARCH' functionality which will search the database & should display a unique record.
The design contains the 4 input boxes--
">
java code - JSP-Servlet
java code how to read SMS from a connected SIM Card to a web application Hi,
Im trying to do a report which should generate...:
-----------------------------------------------
code rep_number desc...;%
db.connect();
rsUser = db.execSQL("SELECT * FROM reportID WHERE code = 'J
java code - JSP-Servlet
java code How to write a java code for sending sms from internet. Hi friend,
public class SMSClientDemo implements Runnable...://
java/jsp code to download a video
java/jsp code to download a video how can i download a video using jsp/servlet
JSP code - JSP-Servlet
JSP code Hi!
Can somebody provide a line by line explanation of the following code. The code is used to upload and download an image.
<... have successfully upload the file by the name of:
Download
/*Code hi there can some one tell me how i can throw an alert message in every hour after getting the system time
java code
java code write a java code for finding a string in partiular position in a delimited text file and replace the word with the values given by user and write the file in new location error - Java Beginners
jsp code error Hi,
I have a problem with following code... part. Is it possible to display a message box or alert box in jsp code??. plz help...; Hi friend ,
Try this code:
/*out.println("Login Failed
How to avoid Java Code in JSP-Files?
How to avoid Java Code in JSP-Files? How to avoid Java Code in JSP-Files
jsp code problem - Java Beginners
jsp code problem Hi,
I have a problem with else part. It did not show the message box when the result set is null. plz, help me. thank u in advance
How to downloads an application of the file from remote location?
How to downloads an application of the file from remote location? Hi,
Can help me How to downloads an application of Java file from remote location?
Thanks,
Hi,
As per your query i fell this example
java Compilation error:jsp code - JSP-Servlet
java Compilation error:jsp code I am getting an Generated Servlet... code:
<%
{
Dbclass2 d= new Dbclass2...");
out.println("<TABLE border='3
cursor by java code
cursor by java code hi, please how change cursor location automatically in java code
servlet code - JSP-Servlet
servlet code how to implement paging or pagination in java code using servlets. Hi Friend,
Try the following code:
import java.io.... of JSP page");
out.println("");
out.println("");
out.println
java code
java code java database code to retrieve data at runtime and please give codes for insert delete too.... using jsp and withot jsp
1... language="java"%>
<%@page import="java.sql.*"%>
<form method="post
avoid java code in jsp - Java Beginners
avoid java code in jsp i want to show the arrayList values in a drop down box in struts the front page is jsp ,i am using struts1.3 ,i want to avoid java code in my jsp Hi Friend,
Please visit the following link
embedding a chatting code in jsp page - JSP-Servlet
embedding a chatting code in jsp page i need to know that how can i embed my chatting code in java networking in my jsp page
PDF gets launched at server location only
PDF gets launched at server location only Hi,
I have an application through which I create a PDF and then launch it, using the following code:
PdfWriter.getInstance(document, new FileOutputStream(file_name);
document.open
java code for cursor
java code for cursor hi,please how to change cursor location by java code ,iam use this code but not change the location
JTextArea a=new JtextArea(); if(resultText.equalsIgnoreCase("class")){ a.append("a { \n }"); PointerInfo
java code - Java Beginners
java code i want code of combo box,that is ,if i select county ,then it has to display all the states name Hi Friend,
Area you using JSP or Java Swing? Please clarify this.
Thanks
Map code
to see the location vashi, nerul, turbhe....
means want to zoom into this area and then again zoom in and see nerul location more properly or other location... this can be done????????????/
can u help me to do so.
plz provide a code which
text to speech code in jsp - Java Magazine
text to speech code in jsp Is their any code in jsp for text to speech
i.e when i enter text in text area and press submit button , the text i entered should come in voice as output
how to copy files from remote location to local using java?
how to copy files from remote location to local using java? I want to copy all files from shared folder to local.
Please help code - Java Server Faces Questions
jsp code How can I access the javascript variable value in the same jsp page .please say me to the code.
My javascript function is given below...;
alert(strValue);
}
I want to access the value of "strValue" in my jsp
java code - Java Beginners
java code how can we display in jsp page selecting multiple records from serevlet Hi Friend,
Please visit the following link:
Thanks
jsp code
jsp code what are the jsp code for view page in online journal
Java Source code
Java Source Code for text chat application using jsp and servlets Code for text chat application using jsp and servlets
Code rally
Code rally
A Java-based, real-time programming game based on the
Eclipse platform.
What is CodeRally?
CodeRally is a Java?-based, real-time programming
game based
Transferring values between javascript and java code in jsp - JSP-Servlet
Transferring values between javascript and java code in jsp Is there a way to transfer values between the javascripts and the java code(scriptlet, expressions etc) in a jsp page?
Hi Friend,
1)Pass value from jsp
java code for sending sms - JSP-Servlet
java code for sending sms hello sir,
I want a code for sending sms on mobile .
please send me if u have this
Thanks & regards
Dharmendra
java code - Java Beginners
java code i want to appear any text in jsp one by one each text stop for 15 seconds in jsp page. Hi friend,
Code to display text after "15 seconds"
function get_random()
{
var ranNum= Math.floor
generate java code and html code - Java Beginners
generate java code and html code create a web application for museum....a)the first page wil be a login page for administrators.. passwords for all..., current location(cabinet1, cabinet 2 etc)
c)administrator should be able to enter
java code for uploading a resume in a form - JSP-Servlet
java code for uploading a resume in a form can anyone help me with the codes 4 uploading a resume in a registration form Refer this link
Thanks
Rajanikant
Jsp Code:Refreshing Page - Java Beginners
Jsp Code:Refreshing Page Dear Frnds,
I have a problem where i need to refresh a page based on the button click. once a page is updated, it should refresh the data in another page. structure is given bellow...
Empid EmpName
JSP CODE
JSP CODE what is the code for downloading images from database using JSP?
Please visit the following link:
Java Script Code Problem - JSP-Servlet
Java Script Code Problem how to concatenate html table values(there are 3 rows,each row contains 3 fields) into variable and display it using javascript Hi Friend,
Try the following code:
document.write code hi i am Ruchi can anybody plz tell me the jsp code... visit the following links:
jsp code
jsp code i want health management system project code using jsp.its urgent
How to write jsp/servlet code to integrate LINKDIN?
How to write jsp/servlet code to integrate LINKDIN? How integrate linkdin api's in java codding
code
code
how to write this in java
in java, how to store the oputput in tha hard disk in a particular location
in java, how to store the oputput in tha hard disk in a particular location how to store the output in the hard disk
Java Scripting - JSP-Servlet
Java Scripting Hello Friends,
I am doing a jsp... dialogue box appearing indefinetly.
Code for this program...}
Work Location
code required
code required I am making a blog in java using netbeans and database connectivity with SQL Server 2008.
I am using JSP pages for the same... .jpg,,png etc files)
But i am not getting how to provide this option on the JSP
jsp and java
jsp and java how to write a jsp and related java code to enter student marks into database
how to custom location of a object after dragging to the drop target
how to custom location of a object after dragging to the drop target ...?
Please visit the following link:
no not like that, i just want to know
code
code hi
I need help in creating a java code that reminds user on a particular date about their festival.
i have no clue of how to do it..
am looking forward to seek help from you
java bean code - EJB
java bean code simple code for java beans Hi Friend,
Java Beans are reusable components. They are used to separate Business logic from....
Java Bean Code:
public class EmployeeBean{
public int id;
public
Java Code - Swing AWT
Java Code How to Display a Save Dialog Box using JFileChooser and Save the loaded Image from Panel in any Location. Hi Friend,
Try the following code:
import java.io.*;
import java.awt.*;
import java.util.:
code
code <
comp xlink:
how to write this in java
Jsp code to enable and disable certain links using jsp code - Java Beginners
Jsp code to enable and disable certain links using jsp code Hi Everyone,
I have a doubt in JSP,I have created a web application which has... write the code to disable these links..
Can anyone help me?? its really really
jsp code - JSP-Servlet
jsp code I need code for bar charts using jsp. I searched some code but they are contain some of their own packages. Please give me asimple code... friend,
Code to solve the problem :
Thanks
java code - JDBC
java code how to store the online form in database using jdbc
ND TO RETRIVE the that data
Hi Friend,
Try the following code:
1... information, visit the following link:
Thanks
jsp code - JSP-Servlet
jsp code sample code to create hyperlink within hyperlink
example:
reservation:
train:
A/C department
non A/c Department
java script code
java script code Hi Deepak,
Firstly wanna share the problem em facing:
working with servlet and jsp for my project. I have 3 main jsp pages which interacts with user for accepting user input and supply them
java, - JSP-Interview Questions
java, hi..
define URI?
wht is difference b/w URL and URI
wht... that represent the address or location of resources, typically on the internet, and how... the internet resource.
3) It is not a specific file location.
4)It is preferred
JSP
JSP how to open and view a flat file in browser using java code in jsp?
Hi Friend,
If you want to simply open a file then try the following code:
<%@page import="java.util.*"%>
<%
Runtime rt | http://www.roseindia.net/tutorialhelp/comment/81339 | CC-MAIN-2015-06 | refinedweb | 2,533 | 60.35 |
Costin Manolache wrote:
> I'm not very familiar with the /admin - how difficult
> would it be to change the naming format for Contexts ?
It's not TOO difficult. You'll need to change createObjectName() for
context in MBeanUtils and also in context actions classes so that they
query for the right mbean name. There're quiet a few places... :-(
>
> JSR77 defines some pretty clear names for Context and Servet -
> and I think we should use that where possible.
>
> Another issue I have is the name of the Valves, which uses
> the hashcode of the valve object. I would preffer to have
> an easier form - a counter indicating the position of the valve
> in the chain ( unique for the container where the valve is attached ).
same for valves.
>
> Again - need help with the /admin.
>
> Finally, the issue of "domain". In JSR77 ( and in general )
> the domain can be used to create separate namespaces - and I think
> the "domain" should match the engine name and the jsrRoute. That
> would simplify a lot:
> - a domain represents a particular tomcat Engine.
> - each engine must have a unique identifier
> - this will be used for load balancing ( as jvmRoute - no longer separate
> config )
> - it will also be visible in the JMX console. Assuming remote-JMX
> is supported - each tomcat will be visible in a separate domain.
> - you can have multiple Engines in the same VM ( just like today ),
> but each will have a separate domain and will be completely separated
> from each other.
>
> Not sure if the /admin is using the domain somehere.
I don't think admin uses domain currently.
>
> Opinions ? Anyone willing to help ?
I'm willing to help if you send new mbean name formats for context and
valves. I can't promise anything quick since I'm in the middle of
different things. :-)
Thanks,
Amy
>
>
>> | http://mail-archives.apache.org/mod_mbox/tomcat-dev/200301.mbox/%3C3E234667.7060004@apache.org%3E | CC-MAIN-2016-40 | refinedweb | 303 | 73.47 |
In the following listing I have used cin.get() to keep the console window open when I run the .exe file - it has worked before for me but in this program it doesn't - the console shuts immediately after outputting the list - I just know this is going to be something obvious so sorry in advance!!
Code:#include <algorithm> #include <iostream> #include <istream> #include <ostream> #include <vector> using namespace std; int main() { vector<int> data; // initialized to be empty int x(0); // Read integers one at a time. while (cin >> x) // Store each integer in the vector. data.push_back(x); // Sort the vector. sort(data.begin(), data.end()); // Print the vector, one number per line. for (vector<int>::size_type i(0); i != data.size(); i = i + 1) { cout << data.at(i) << '\n'; } cin.get(); | http://cboard.cprogramming.com/cplusplus-programming/141171-keep-console-open.html | CC-MAIN-2014-10 | refinedweb | 134 | 68.06 |
ls prints differently depending on whether the output is to a terminal or to something else.
ls
e.g.:
$ ls .
file1 file2
$ ls . | head
file1
file2
Is there some way to make ls print out on one line as if it's to a terminal when it's not. There's a -C argument that sorta does that, but it will split it into several lines.
-C
$ ls
file1 file10 file11 file12 file13 file14 file15 file16 file17 file18 file19 file2 file3 file4 file5 file6 file7 file8 file9
$ ls -C . | head
file1 file11 file13 file15 file17 file19 file3 file5 file7 file9
file10 file12 file14 file16 file18 file2 file4 file6 file8
The reason I want to do this is that I want to monitor the files in a directory that were changing quickly. I had constructed this simple command line:
while [[ true ]] ; do ls ; done | uniq
The uniq prevents it from spamming my terminal and only showing changes. However it was printing it all on differnet lines, which was making the uniq useless, and increasing the amount of noise. In theory one could use watch for this, but I wanted to see a file as soon as it appeared/disappeared.
watch
This is the final solution:
while [[ true ]] ; do ls | tr '\n' ' ' ; done | uniq
i don't know of a switch which could do that, but you can pipe your output through tr to do it:
tr
ls | tr "\n" " " | <whatever you like>
If your ls has this option, you can use a high value and it might do what you want:
ls -w 10000 -C . | head
ah, now that you've updated the question....
while true ; do echo * ; done | uniq
will do what you posted, just simpler.
however, you are better off using something that uses inotify to do this.. like
inotifywait -m . -e create,delete
if you don't have inotify, then something like this works well too:
import os
import time
last = set()
while True:
cur = set(os.listdir('.'))
added = cur-last
removed = last-cur
if added: print 'added', added
if removed: print 'removed', removed
last = set(os.listdir('.'))
time.sleep(0.1)
This may be what you are looking for but I may have misunderstood your question but here goes :)
A few commands worth looking into:
watch - execute a program periodically, showing output fullscreen
xargs - build and execute command lines from standard input (-0 if you want to handle files with spaces etc)
You can do something like the following to show the last 10 files/dirs that changed with a 2 second interval (default for watch)
watch "ls -lart | tail -10"
watch "ls -lart | tail -10"
the options -lart tell ls to be verbose and sort based on modification time.
If you really just want the files I would just do something like:
watch "ls -lart | awk '{print \$8}' |
tail -10 | xargs"
watch "ls -lart | awk '{print \$8}' |
tail -10 | xargs"
or just to display them:
ls -lart | awk '{print $8}' | tail -10
| xargs
ls -lart | awk '{print $8}' | tail -10
| xargs
By posting your answer, you agree to the privacy policy and terms of service.
tagged
asked
3 years ago
viewed
1096 times
active | http://serverfault.com/questions/105838/make-ls-print-it-all-on-one-line-like-in-terminal | CC-MAIN-2013-48 | refinedweb | 528 | 69.65 |
Two kinds of source repositories are hosted at opensolaris.org: centralized and distributed. The centralized source management model uses the Subversion (SVN) source control management program. Repositories managed in a distributed fashion will be avaiable via the Mercurial source control management program. This document describes Subversion.
Subversion is available via
OpenSolaris and Solaris Express (build
62 or later).
Developers with commit rights will access repositories through their opensolaris.org accounts. Commit rights are managed by Project Leaders. If you do not have an account, sign up to acquire one. Additionally, you will have to provide a Secure Shell (SSH) public key.
The creation of an SVN repository on opensolaris.org is done through the webpages. You have to be a project leader to create a new repository.
On the main page for a project, there is an item called "SCM
Console". This item will lead you to the SCM configuration
page. Choose "Create Repository". You will be asked to provide a name
for the repository, a notification email address, the repository type
(Subversion in this case), and whether anonymous access is allowed or
not. Click the "Create"
svn+ssh://user@svn.opensolaris.org/svn/projectname/reponame
Where "projectname" is the name of your project and "reponame" the name of the newly created repository. "user" is an opensolaris.org username.
If you are creating a repository that you want to populate with a pre-existing SVN repository, the repository contents must be manually uploaded at the moment.
Please send email to tools dash discuss at opensolaris dot org:
Let's assume that your opensolaris.org user id is "joe", and that you have been given access to a repository called "repo" in the project "software".
The first thing you should do is to check out a copy of the repository, even if it is still empty. The command to do this would be:
svn co svn+ssh://joe@svn.opensolaris.org/svn/software/repo
This will create a checked out copy of the repository in a
directory called "repo", in your current working directory. If you're
working with an already populated repository, the checkout
command mentioned above will have pulled over a copy of the
repository. The best starting point for further steps is to start
reading the SVN reference book at the
guided tour, and look at the "Initial Checkout" section.
If you just created the repository, it'll be empty, so the first
step is obviously to start adding source code. For an existing source
tree that is not yet in the repository, the normal way to put it into
an SVN repository is to use the import command. Read the
the
guided tour in the SVN reference book, but ignore references to
the svnadmin create command, since you already have an
existing repository.
import
svnadmin create
If you are behind a firewall that requires that SSH connections be tunnelled through a SOCKS proxy, then your $HOME/.ssh/config file needs to contain a directive like:
Host *.opensolaris.orgProxyCommand /usr/lib/ssh/ssh-socks5-proxy-connect -h [socks proxy address] %h %p
Host *.opensolaris.orgProxyCommand /usr/lib/ssh/ssh-socks5-proxy-connect -h [socks proxy address] %h %p
Sun employees should note that proxying should no longer be used from
Sun's internal network. If you have ssh configured to use a proxy,
you will eventually start seeing timeouts or other errors as the
proxies are being decommissioned.
For detailed information on SVN, see the SVN reference book.
Page Last Modified: 17 Apr 2009
Privacy |
Trademarks |
Site Guidelines |
HelpYour use of this web site or any of its content or software indicates your agreement to be bound by these Terms of Use.Copyright © 1995-2009 Sun Microsystems, Inc. | http://www.opensolaris.org/os/community/tools/scm/svn_help/ | crawl-002 | refinedweb | 620 | 56.45 |
Windows Guide to Installing Wicket on Eclipse with Maven
Download & Install Maven
Maven is a project management tool. It does a million things, but I only know three of those things. We'll use Maven to get the Wicket Quickstart, convert it to an Eclipse project, and package our WARs. But first we need to get Maven.
1. Go to.
2. Click the "apache-maven-2.0.10-bin.zip" link.
3. Click the link at the top of the page.
4. That will prompt you to download a file called apache-maven-2.0.10-bin.zip . Save it to your desktop.
5. Inside the zip file is a folder called apache-maven-2.0.10. Drag that folder and put it directly onto your C: drive--C:\apache-maven-2.0.10 . *IMPORTANT*---Maven has problems if its path has any spaces in it. For example, don't put Maven under your "Program Files" folder, since there's a space in "Program Files".
6. Add an environment variable called MAVEN_HOME with a value of C:\apache-maven-2.0.10 . You can learn how to set environment variables here:
7. Add Maven's "bin" directory to your PATH environment variable. In this case, you can just paste
; C:\apache-maven-2.0.10\bin
to the end of your PATH. Don't forget to put the semicolon in front, to separate it from anything that's already in your PATH.
8. If you don't have a JAVA_HOME environment variable, then create one of those too, pointing at a JDK installation on your computer.
9. Now you have Maven ready to go. You can check that it's been installed correctly by opening a command prompt (Start -> Run... -> cmd) and typing in "mvn -version". That should display a couple lines of information about your Maven installation.
Download Eclipse
Eclipse is a great IDE for developing Java applications.
1. Go to .
2. Click the Eclipse IDE for Java Developers link.
3. Click the big green download arrow.
4. That will prompt you to download a file called eclipse-jee-ganymede-SR2-win32.zip. Save it to your desktop.
5. Inside the zip file is a folder called eclipse. Drag that folder and put it directly onto your C: drive---_C:\eclipse_ .
6. That's it. Now you can run Eclipse by going into the eclipse folder and running eclipse.exe.
Download WTP (optional)
WTP is an Eclipse plugin that provides nice web editing tools, including a good HTML editor. It's not necessary, it's nice to have. If you don't want WTP, skip this part. You can always come back and do it later.
1. Go to .
2. Click the 3.0.4 link.
3. Then click the wtp link under *Web App Developers.*
4. Then click the big green arrow.
5. That will prompt you to download a file called wtp-R-3.0.4-20090213193639.zip. Save it to your desktop.
6. Inside the zip file is a folder called eclipse. Drag that folder and put it directly onto your C: drive. A popup window will tell you that there's already a folder called eclipse there, and ask if you want to continue. Say yes. That will copy the contents of this eclipse folder into the eclipse folder that's already on your C: drive.
7. That's it. Now you will have access to the WTP tools when using Eclipse.
Install M2Eclipse
M2Eclipse is an Eclipse plugin that allows you to run your Maven project from within Eclipse.
1. Open Eclipse.
2. Go to the Help menu and select Software Updates...
3. A pop-up window will open. Make sure the Available Software tab is selected at the top of the pop-up window.
4. Click the "Add Site..." button on the right. That will pop up another window.
5. Paste into the Location bar. Then click OK.
6. This will add a line to the Available Software list titled Maven Integration for Eclipse Update Site
7. Check the checkbox next to Maven Integration for Eclipse Update Site and click "Install...".
8. A window will pop-up saying that the items you selected may not be valid yadda yadda yadda. Click "Yes".
9. Uncheck the boxes next to Maven Integration for AJDT and Maven SCM handler for Subclipse.
10. Click "Finish". That's it. Now you've got everything ready to build your first Wicket application.
Build Wicket Quickstart
We're almost there. Everything you've done so far will never need to be done again. This section contains all the directions to start a new project. Whenever you want to start a new project, you can come back to these steps.
The Wicket Quickstart contains all of the files and libraries necessary to make a Wicket project. It lives in the Maven repository, so we'll use Maven to download it and build it, and then we'll import it into Eclipse for you to play with.
1. Create a folder called on wicket on your C: drive to contain your Wicket projects---C:\wicket.
2. Now open a browser and go to .
3. Under the "Creating the project" section of the page, enter a GroupId and an ArtifactId. The GroupId can be any string that reasonably identifies your organization. The ArtifactId will be the name of your project. Leave Version at 1.3.5. (You're welcome to try 1.4, but I haven't had much luck with that.)
4. Now open a command prompt (Start -> Run... -> cmd) and navigate to _C:\wicket_.
5. Copy the text inside the "Command Line" textbox from step 3 above and paste it into your command prompt. Hit enter. Then wait as Maven downloads a bunch of stuff.
6. When that finishes, you will see that a new folder called firstWicketProject has been created in your C:\wicket_ folder. From your command prompt, navigate into _firstWicketProject.
7. Your command prompt should now be in C:\wicket\firstWicketProject. From here, type
mvn eclipse:eclipse
and hit Enter. Wait while Maven download more stuff.
8. Now open Eclipse, if you don't already have it open. Go to the File menue and select Import... A window will pop up with several folders.
9. Expand the top folder, named "General". Select the "Existing Projects into Workspace" option and click "Next".
10. Click the "Browse..." button to the right of the "Select root directory" prompt.
11. Navigate to C:\wicket\firstWicketProject and click "OK".
12. The Projects area of the window will now show "firstWicketProject" with a checkbox checked next to it. Click Finish.
Running the Application
Congratulations! You've installed the necessary software and built your first Wicket project. Now lets look at the project files and get it running.
- In the Package Explorer on the left hand side of the screen, you'll now see a folder called "firstWicketProject". If you expand that folder you'll lots of stuff. The important items are src/main/java, src/test/java, and src.
- src/main/java contains the project Java and HTML files. This is where you'll add new pages.
- src/test/java contains the embedded server. We'll come back here in a minute.
- src contains your web.xml file. You'll find it under src/main/webapp/WEB-INF. Use that to set up your project configuration.
- Now go back to src/test/java. Inside you'll see a package that has the same name as the GroupId you entered on the Quickstart website.
- Expand the package inside src/test/java and you'll see a Java file called Start.java. Right-click Start.java and go down to "Debug as..." and select "Java Application". You'll see the server starting up inside the console at the bottom of the screen.
- To test to see if everything is working, open a browser and go to . You should see a message telling you and Wicket is running.
- To stop the server, click the red square at the top right of the console in Eclipse. You may need to stop and start the server after you make programming changes in order for the changes to take effect.
Bonus Section
That's just about everything. Now you're ready to go into your src/main/java and start building your application. However, there are two more changes I suggest you make.
- Open the pom.xml file in the project root directory and scroll toward the bottom, where you'll find:and add the line
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-eclipse-plugin</artifactId> <configuration> <downloadSources>true</downloadSources> </configuration> </plugin>right after
<version>2.5.1</version>
<artifactId>maven-eclipse-plugin</artifactId>
- Go back to src/test/java and open the Start.java file into the Eclipse editor.
- Delete the entire contents of the file and paste in the following instead. I find this change helps the embedded server to pick up your code changes without needing to be restarted.
package edu.chemeketa; import java.lang.management.ManagementFactory; import javax.management.MBeanServer; import org.mortbay.jetty.Server; import org.mortbay.jetty.nio.SelectChannelConnector; import org.mortbay.jetty.webapp.WebAppContext; import org.mortbay.management.MBeanContainer; /** * Seperate startup class for people that want to run the examples * directly. */ public class Start { /** * Main function, starts the jetty server. * * @param args */ public static void main(String[] args) throws Exception { Server server = new Server(); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(8080); server.addConnector(connector); WebAppContext web = new WebAppContext(); web.setContextPath("/"); web.setWar("src/main/webapp"); server.addHandler(web); MBeanServer mBeanServer = ManagementFactory .getPlatformMBeanServer(); MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer); server.getContainer().addEventListener(mBeanContainer); mBeanContainer.start(); try { System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP"); server.start(); while (System.in.available() == 0) { Thread.sleep(5000); } server.stop(); server.join(); } catch (Exception e) { e.printStackTrace(); System.exit(100); } } } | https://cwiki.apache.org/confluence/display/WICKET/Windows+Guide+to+Installing+Wicket+on+Eclipse+with+Maven | CC-MAIN-2019-26 | refinedweb | 1,647 | 69.48 |
Controlling Filter Dynamics
Whereas the amplitude of samples are manipulated in the VCA, the cutoff frequency of a Low Pass Filter (LPF) is manipulated by our VCF. An idealized LPF response graph is shown in Figure 3. What this figure indicates is that frequencies lower than the filter's cutoff frequency are passed unaltered whereas frequencies higher than the cutoff frequency are severely attenuated (reduced in level).
Let's take a minute to talk about what this means in the subtractive synthesis environment. With subtractive synthesis, you start with a harmonically rich sound like a square or a sawtooth wave. These waveforms have harmonics that are multiples of the waveform's fundamental frequency. If the cutoff frequency of a LPF in the signal chain is set high, most of the harmonics are passed through the filter with the result being little modification of the waveform's native sound. As the cutoff frequency of the filter is lowered, more and more of the waveform's harmonics are filtered out and the sound changes to become more pure. If the cutoff frequency of the LPF is set at or below the fundamental frequency of the waveform, the sound approximates that of a sine wave.
Sweeping a LPF with an EG causes a dynamic and dramatic change in the produced sound. If the sweep goes from high to low, you get the full sound of the waveform that morphs over time into a purer sound. If the sweep goes from low to high, you hear the pure sound first that then transitions to the native sound of the waveform.
As with our VCA, the
VCF class extends
EnvelopeGenerator and implements
SampleProviderIntfc. This arrangement allows the EG's APIs to be directly available to the user of the
VCF class. The
noteOn and
noteOff methods are again the control interface for the VCF.
The filter we are using is a sweepable, 24 db/octave, variable resonance, LPF (is that a mouthful or what?) whose code was taken from the Music DSP site. This filter is found in the comment section of the "Moog VCF" topic. The theory of how this filter works is beyond the scope of this article because it enters the realm of Digital Signal Processing (DSP) and requires knowledge of filter design to understand. Suffice it to say that this filter is a cascaded arrangement of four single pole filters providing a total of 24 db/octave cutoff slope.
As this filter's resonance is increased, it will begin to self oscillate just like the MiniMoog's filter. Oscillating filters have their own uses in electronic music including synthesizing the sound of bells under certain circumstances.
The depth control API method determines the range and direction of the cutoff frequency sweep as illustrated in Table 1:
See Listing Two for the code for the VCF and the embedded javadocs for the details of the VCF's API.
Listing Two: The code for the VCF.
public class VCF extends EnvelopeGenerator implements SampleProviderIntfc { public static final double MIN_CUTOFF = 20.0; public static final double MAX_CUTOFF = 8000.0; public static final double MIN_DEPTH = -2.0; public static final double MAX_DEPTH = 2.0; /** * Set the static cutoff frequency of the filter. * Cutoff frequency must be between MIN_CUTOFF and MAX_CUTOFF. * Envelope signal varies the cutoff frequency from this static value. * @param cutoff Cutoff frequency in Hz */ public void setCutoffFrequencyInHz(double cutoff) { cutoff = (cutoff < MIN_CUTOFF) ? MIN_CUTOFF : cutoff; cutoff = (cutoff > MAX_CUTOFF) ? MAX_CUTOFF : cutoff; cutoffFrequencyInHz = cutoff; this.cutoff = cutoff; recalculate(); } /** * Set the resonance of the filter. * Valid values are between 0.0 and 1.0 where<br> * 0.0 is no resonance and 1.0 is full resonance or oscillation. * @param resonance The resonance value to set */ public void setResonance(double resonance) { this.resonance = resonance; recalculate(); } /** * Set the depth of the filter effect. * depth == 0 env gen has no affect on cutoff frequency<br> * depth < 0 env gen drives cutoff sweep downward<br> * depth == -1 sweep is 1 octave; depth = -2 sweep is 2 octaves<br> * depth > 0 env gen drives cutoff sweep upward<br> * depth == 1 sweep is 1 octave; depth = 2 sweep is 2 octaves<br> * Depth value must be between MIN_DEPTH and MAX_DEPTH. * @param depth The depth to set */ public void setDepth(double depth) { depth = (depth < MIN_DEPTH) ? MIN_DEPTH : depth; depth = (depth > MAX_DEPTH) ? MAX_DEPTH : depth; this.depth = depth; } /** * Setup the provider of samples * @param provider The provider of samples for the VCF. */ public void setSampleProvider(SampleProviderIntfc provider) { this.provider = provider; } /** * Recalculate filter parameters on changes to cutoff or resonance */ private void recalculate() { double f = (cutoff + cutoff) / (double) SamplePlayer.SAMPLE_RATE; p = f * (1.8 - (0.8 * f)); k = p + p - 1.0; double t = (1.0 - p) * 1.386249; double t2 = 12.0 + t * t; r = resonance * (t2 + 6.0 * t) / (t2 - 6.0 * t); } /** * Process a single sample through the filter * @param input The input sample to process * @return Filtered sample */ private short processSample(short input) { // Process input x = ((double) input/Short.MAX_VALUE) - r*y4; // Four cascaded one pole filters (bilinear transform) y1 = x*p + oldx*p - k*y1; y2 = y1*p + oldy1*p - k*y2; y3 = y2*p + oldy2*p - k*y3; y4 = y3*p + oldy3*p - k*y4; // Clipper band limited sigmoid y4 -= (y4*y4*y4) / 6.0; oldx = x; oldy1 = y1; oldy2 = y2; oldy3 = y3; return (short) (y4 * Short.MAX_VALUE); } /** *); // Get value from envelope generator in the range 0.0 .. 1.0 double v = getValue(); // Calculate actual cutoff freq given depth and env gen modifiers cutoff = cutoffFrequencyInHz * Math.pow(2.0, depth * v); recalculate(); // Return processed sample from filter s = processSample(s); // Store the processed sample buffer[index++] = (byte)(s >> 8); buffer[index++] = (byte)(s & 0xFF); } return SamplePlayer.BUFFER_SIZE; } // Instance data private double resonance, depth, cutoff, cutoffFrequencyInHz; private double x, r, p, k, y1, y2, y3, y4, oldx, oldy1, oldy2, oldy3; private SampleProviderIntfc provider; } | http://www.drdobbs.com/jvm/music-components-in-java-the-synthesizer/231000557?pgno=3 | CC-MAIN-2015-06 | refinedweb | 970 | 57.06 |
After discussing optimizing and debugging cross-compiled ActionScript I would like to take a look at testing cross-compiled ActionScript. The short answer I can offer is: testing cross-compiled ActionScript is not much different from testing JavaScript. But of course there is more to it. There is always more…
Testing your patience
Be warned, this is a long post. I thought about splitting this post up as I have done in previous posts. But in this case I think everything should stay together. That said, let’s dive in!
In my opinion there are two different testing scenarios:
- Testing your cross-compiler.
- Testing client code.
In both scenarios we test JavaScript, but as we will see the goals and methods are different. Before we jump right in let me also point out that there are two types of testing, automated testing and manual (interactive) testing. Of course we prefer automated testing, because it is cheaper, less error prone, and can be integrated into Continuous Integration (CI) loops.
For running the Tamarin Acceptance Tests, which tests the cross-compiler, I use Chrome’s d8 (the debugger for V8) and for testing client code and running regression tests I use the default browser (usually Safari on OSX) with Google’s js-test-driver.
Correctness versus Consistency
As mentioned above the goals for testing your cross-compiler and testing client code are different. When you test your cross-compiler you want to ensure that all language constructs in the source language are correctly cross-compiled to the target language. The term “correct” refers to preserving the internal consistency of the source code in the target code, not correctness in an abstract sense. I tried to explain this idea in a previous post, where in ActionScript and JavaScript you’ll get a mathematically incorrect result when adding 0.2 to 0.1:
// yields 0.30000000000000004, and not 0.3 in AS3 and JS. trace( 0.2 + 0.1 );
I argued that in the context of cross-compiling one language into another it is very important to produce the same results in both worlds (here 0.30000000000000004) even if the results are incorrect. Our test suites need to follow that principle as well. As wrong as it may seem we should include a unit test that tests against 0.2 + 0.1 = 0.30000000000000004.
Missing Language Specification
Testing implies that you know the correct and expected results of your tests. When testing your cross-compiler the expected results are defined by the grammar of the source and target languages. What we need in our case are the language specifications of ActionScript and JavaScript. Herein lies a big problem. While the current JavaScript specification is summarized in ECMA-262 you won’t find a language specification for ActionScript. Just to be clear, a “language specification” is a document that describes the language grammar (usually formulated in Backus-Naur Form), so that developers can build a compiler for that language. A language specification is not a tutorial, FAQ, or online help about that language. For example Dart has a language spec, on the other hand Coffeescript’s langage reference does not qualify as a specification.
Neither does ActionScript’s online help. The closest to a language specification that Adobe currently offers is a section in the online help called Learning ActionScript 3.0 . You might argue that an ActionScript language specification is not really necessary, because the syntax of ActionScript is by now well known and documented. I am afraid you cannot assume that everything about ActionScript is well documented. Just try find the exact syntax for Vectors in Learning ActionScript 3.0. I found this snippet under Array/Advanced Topics (you also find other bits and pieces under Basics of Arrays):
Note: You can use the technique described here to create a typed array. However, a better approach is to use a Vector object. A Vector instance is a true typed array, and provides performance and other improvements over the Array class or any subclass. The purpose of this discussion is to demonstrate how to create an Array subclass.
Even though it’s not really my fault, I truly regret that Adobe has never properly published a language specification for ActionScript. One could even argue that all computer languages can be divided into “hobby languages” and “professional languages”. The latter have language specifications.
Tamarin Acceptance Tests
The lack of a language specification for ActionScript has another nasty side effect. Without a language specification you also won’t find a corresponding language validation suite, which tests a compiler against the language specification. But that’s exactly what we need: a test suite that tells us that our cross-compiler complies to the language specification.
The next best thing to a language validation suite are currently the Tamarin Acceptance Tests. Those tests are grouped into different sections:
- abcasm
- as3
- e4x
- ecma3
- misc
- mmgc
- mops
- recursion
- regress
- spidermonkey
- versioning.
Oberflächenverdoppelung
In fact, the Tamarin Acceptance Tests only seem to care about the behavior of the ActionScript VM in the Flash Player not changing in new versions of the Tamarin VM. The definition “ActionScript is what passes the Tamarin Acceptance Tests” does unfortunately not work as we will see in the following chapters.
There is a wonderful, but rarely used German philosophical term for this kind of circular reasoning (ActionScript is what passes the Tamarin Tests, which validate Tamarin VM results, which reflect ActionScript language rules). It is called “Oberflächenverdoppelung“, which I would translate as “surface duplication“. By creating tests that just confirm the results of an existing VM you only reiterate the knowledge of your own belief system. Instead of probing for truth you merely duplicate the surface of what you already know.
typeof Number
Assuming that the “ecma3″ section of the Tamarin Acceptance Tests validates against ECMA-262 (even the 3rd edition) there is a cluster of tests, which are in my opinion incorrect. To be precise, I believe ActionScript does not always comply to ECMA-262, and the Tamarin tests just bend to the status quo of ActionScript. For example, test e15_4_2_2_2, which is under ecma3/Array, would fail in every browser, because of this tiny difference between ActionScript 3 and JavaScript:
// ActionScript typeof(new Number()) == "number"// JavaScript typeof(new Number()) == "object"
I asked our specialists here at Adobe why there is this difference and this was one of the replies:
“In javascript, new Number(…) evaluates to an Object that wraps a number value. In AS3, new Number(…) return a number value. In both languages the Array constructor creates an Array of length 1 if given an object and an array of length n if given a number, where n is the value of the number.“
But does ECMA-262 really allow both points of view? Is it allowed to return a number value for “new Number(…)” without fragmenting the language specified by ECMA-262? The ECMA-262 Language Overview chapter says (highlights added by me):and URIError.
Number is clearly defined as an Object and typeof(new Number()) = "object" seems to be the correct result according to ECMA-262. There is also a whole chapter on Number Objects in ECMA-262. But I couldn’t find any supporting arguments for typeof(new Number()) = "number".
As mentioned earlier it is important to preserve the behavior of the source language in the target language. But I decided that in this case, ActionScript (and the bending Tamarin tests) are incorrect, if you assume that “ecma3″ really does validate against ECMA-262. This would be similar to, say, getting 0.2 + 0.1 = 0.30000000000000004 in AS3 and 0.2 + 0.1 = 0.3 in JS. If you get a different result in AS3 and JS and JS reports the correct result I usually decide against AS3. You can’t rely on the Tamarin Acceptance Test. Their definition of correctness only preserves behavior exhibited in pre-existing C++ implementations of the ActionScript VM.
In either case, this was one of the rare exceptions where I decided to stick with ECMA-262 and not with what the Tamarin tests says is ActionScript (who really knows what ActionScript is without a language spec). As we just learned, one nice thing about language specifications is that there are almost no ambiguities (Number is an Object). I’ll get to the “almost” in a second.
function.toString()
There are many more Tamarin tests, that I find questionable and sometimes even absurd. This one is particularly annoying, because the test could have been phrased to serve a broader definition of what function.toString() may return. This code yields different results in ActionScript 3.0 and JavaScript in browsers:
(Array(1,2)).toString;// Result in ActionScript "function Function() {}"// Result in JavaScript "function toString() { [native code] }"
It turns out that ECMA-262 does not specify what function.toString() should exactly return. But we do know the retuned value is of type String and it should start with “function “. Instead of validating against “function ” the Tamarin Acceptance Tests unfortunately check for what the Tamarin VM returns, which is “function Function() {}” and therefore triggers numerous false negatives in browser environment.
What shall we do about it? Shall we perhaps decide against ActionScript like we did for “typeof Number” above? This is a tough one, and I don’t think I am allowed to implement the JavaScript version by ignoring the ActionScript version as I did with “typeof Number”, because ECMA-262 is in regards to function.toString() somewhat ambiguous. (At least I try to be consistent in the way I am fragmenting the ActionScript language!)
So here is the compromise that I came up with. I added a new compiler option to the cross-compiler called “-js-extends-dom”, which defaults to “true”. If you compile the Tamarin tests, -js-extends-dom will be true and the cross-compiler will emit this ugly glue code at the top of your generated JavaScript:
// Additions to DOM classes necessary for passing Tamarin's acceptance tests. // Please use -js-extend-dom=false if you want to prevent DOM core objects changes. if( typeof(__global["Math"].NaN) != "number" ) { /** * @const * @type {function()} */ var fnToString = function() { return "function Function() {}"; }; /** @type {object} */ var proto = {};
// Additions to Math __global["Math"].NaN = NaN;
// Additions to Array (see e15_4_1_1, e15_4_2_1_1, e15_4_2_1_3, e15_4_2_2_1) proto = __global["Array"].prototype; proto.toString.toString = fnToString; proto.join.toString = fnToString; proto.sort.toString = fnToString; proto.reverse.toString = fnToString; if( Object.defineProperty ) { proto.unshift = (function () { /** @type {function()} */ var f = proto.unshift; return function() { return f.apply(this,arguments); }; })(); Object.defineProperty( proto, "unshift", {enumerable: false} ); }
// Additions to Error (see e15_11_2_1) proto = __global["Error"].prototype; proto.getStackTrace = proto.getStackTrace || function() { return null; }; proto.toString = (function () { /** @type {function()} */ var f = proto.toString; return function () { return (this.name == this.message || this.message == "") ? this.name : f.call(this); }; })();
proto = __global["Object"].prototype; // Additions to Object (see e15_11_2_1) proto.toString = (function () { /** @type {function()} */ var f = proto.toString; return function () { return (this instanceof Error) ? ("[object " + this.name + "]") : f.call(this); }; })(); }
The glue code above contains all the hacks for passing the Tamarin tests. In October 2011 my cross-compiler passed 40930 of the ecma3 Tamarin tests, which is about 95%.
In case you are wondering, of course I tell all my clients to run my cross-compiler with -js-extends-dom=false.
Validating versus Testing
In my test suite I differentiate between validating and testing. Validating unit tests generate JavaScript that I diff against a known, correct JavaScript version of the same test. All other tests are just run in the browser or in d8 as mentioned earlier. If the generated JavaScript is different during validation, I’ll get an error. If I accepted the newly generated JavaScript as the correct version then I would copy the new version to the saved version. If I detected a bug in the delta code of the newly generated JavaScript, I would reject the build. This method has been very successful and helped me keeping my bug regression rate at an astonishing low level.
Testing Client Code
I have a few test apps that I always cross-compile as part of my unit tests. One of them is SpriteExample, which is one of the first examples that I ever cross-compiled to JavaScript. You can find that example at the bottom of the Flex online help for flash.display.Sprite .
The SpriteExample is actually not that trivial, because it uses constructor functions (which I very much dislike):
var sprite:Sprite = Sprite(event.target);
In order to get this example to work you would also have to solve event dispatching and drag and drop for Sprites. The drag and drop part can only be tested manually, though.
The End
That’s it, I hope! Now I have told you almost everything I know about cross-compiling ActionScript to JavaScript. There are still many topics that I could discuss in more detail. But after almost three month since my first post when I started this series, I think, we all deserve a break.
Next week, I am starting a new series about something completely different. Well, maybe not completely different… | http://blogs.adobe.com/bparadie/2012/02/23/testing-cross-compiled-actionscript/ | CC-MAIN-2014-41 | refinedweb | 2,183 | 56.05 |
view raw
Consider the following python2 code
In [5]: points = [ (1,2), (2,3)]
In [6]: min(points, key=lambda (x, y): (x*x + y*y))
Out[6]: (1, 2)
>>> min(points, key=lambda p: p[0]*p[0] + p[1]*p[1])
(1, 2)
def some_name_to_think_of(p):
x, y = p
return x*x + y*y
def star(f):
return lambda args: f(*args)
min(points, key=star(lambda x,y: (x*x + y*y))
No, there is no other way. You covered it all. The way to go would be to raise this issue on the Python ideas mailing list, but be prepared to argue a lot over there to gain some traction.
Actually, just not to say "there is no way out", a third way could be to implement one more level of lambda calling just to unfold the parameters - but that would be at once more inefficient and harder to read than your two suggestions:
min(points, key=lambda p: (lambda x,y: (x*x + y*y))(*p)) | https://codedump.io/share/wExTc1rjGBhp/1/what-is-the-good-python3-equivalent-for-auto-tuple-unpacking-in-lambda | CC-MAIN-2017-22 | refinedweb | 171 | 61.53 |
JetBrains News
CLion 2017.2 released: Clang-Tidy, Force Step Into, better C++ support and performance improvements
Please.
Read on for details and get a free 30-day trial to evaluate all the newVCF7 skips the frames without sources. We hope this makes the feature easier to use and more intuitive., shift cmd A.
Another time-consuming operation is CMake reload. You can now cancel it at any time, by simply clicking the Stop button in the CMake tool window. The output logs were updated to get the indication of successfully finished reload (to distinguish from a canceled run). line numbers, navigation icons, and markers for local changes.
- To make the preview even more compact, results from the same line are merged into one line in the preview panel..
2017.2, a new massive update for IntelliJ IDEA, is out and it’s packed full of new features and important bugfixes. Get a copy of this new release, and see for yourself, but before you do, it is worth spending a couple of minutes reading this summary for ideas on where to look.
- Smarter code completion and control flow analysis
- Smart Completion becomes aware of builder classes and suggests chains of method calls on its first call, and the chain suggestions are sorted according to how frequently symbols are used in the current project.
- Control flow analysis has become much smarter and
- Debugger: filtering arrays, collections, and maps
- Spring Boot run dashboard and actuator endpoints
- Managing multiple applications is now easier, thanks to the new Run Dashboard tool window
- Both the Run and Run Dashboard tool windows now provide temporarily Unloaded to conserve CPU and memory resources when working on large projects.
- You can suspend indexing and resume it at your convenience, for example, to save battery power.
For more details about the new and improved features (only the most notable of which are mentioned here), check out the release What’s New page.
Your feedback, as always, is very much appreciated in our issue tracker.
JetBrains recommends: to stay up-to-date with the latest releases, and, when needed, be able to safely switch between several IDE versions, install our Toolbox App.
Good news, everyone — Upsource 2017.2 is here! It comes with a number of highly anticipated features, brings some fun elements into your daily routine and, as usual, enhances the existing functionality. Here's a quick recap.
External Inspection Engines
Running SonarQube/ReSharper/IntelliJ Inspections on TeamCity? Now you can see the results straight in Upsource. This makes a reviewer's job even easier than before, especially if you're working on a .NET project!
Python Support
Code insight functionality is now also available to teams using Python. As for other supported languages this includes code-aware navigation, static code analysis, Find Usages and Usages diff.
Reactions
When there's no need for an elaborate answer, give your feedback in a fast and compact form using a reaction.
GitLab Support
We've received a number of requests to support GitLab merge requests, so you'll be pleased to know that you can now perform code review for your GitLab merge requests in Upsource.
NPM Support
To improve "Go to declaration" and "Find usages" in JavaScript code, we install dependencies listed in your package.json file using npm or yarn (whichever is available).
Suggested Revisions in Reviews
We have employed advanced statistical analysis to suggest revisions that should be added to a review. Similar to the reviewer suggestions that were implemented several releases ago, this is another powerful tool that helps you review code more efficiently.
Achievements
To make it easier to discover new features and to add some fun to your interactions with Upsource, we are introducing an achievements/badges system. So far we've added only a few basic achievements but that's just the beginning!
That's not all of it! If you'd like to learn more about the new Upsource 2017.2 features, please check out the What's New page.
Eager to try? Download the build and don't forget to backup your current instance!!
Our first big update this year includes:
-
Modern C++ standards
As C++17 has already been approved, we've sped up to support the latest C++ standards. The following features of C++14 are recognized in v2017.1:
- auto return type,
- generic lambdas,
- variable templates, and
- generalized lambda captures.
Support for these language features includes correct highlighting and no false-positives in code analysis, as well as correct code completion, navigation and refactorings.
This means that only constexpr is actually missing from C++14. As for C++17, we've started with the most upvoted feature, nested namespaces.
There are dozens of fixes for incorrect code resolve and thus no more false code analysis and other related issues. Check out the build to see if CLion got better for you!
Support for C++11 and C++14 will be polished in 2017.1.x and 2017.2 releases, and hopefully we'll be able to devote more time to C++17.
Make auto
While working on modern C++ standards, developers see how new language features can help make their code more accurate and readable. What if an IDE could assist you with the task of modernizing your code? Sounds good, doesn't it?
The first step we've taken in this direction is to add a , new-expressions.
Precompiled headers and more
Precompiled headers and the -include compiler option is a way to reduce compilation time and keep large-scale codebases structured and clear. When using this, you simply compile expensive includes once and then guide the compiler to reuse that information.
CLion 2017.1 correctly resolves symbols from such headers, suggests code completion, navigate to the declarations and definitions. Check more details.
Debugger
The debugger in CLion 2017.1 received several important bug fixes and a workaround for the GDB timeout issue (which unfortunately still happens to some CLion users).
However, the most important and long-awaited change is the disassembly view in the debugger. When the sources are unavailable, you still can step into and view the disassembly code. Step through it to investigate the issue in your program deeper or to understand what's happening inside a library call.
For now this only works for GDB. For more about the limitations and known issues, see this.
Besides, if you just open a .s or .asm file in CLion (or other extensions, if you add them to Settings | Editor | File Types | Assembly Language) which uses the AT&T dialect and no preprocessor, it will be appropriately highlighted in the editor.
Catch
There are lots of unit testing frameworks for C++: Google Test, Boost, CppUnit, CppTest and many more. Catch is one that's known for its easy starting process (just include a simple header) and convenient and flexible test cases.
CLion has had Google Test support for a while, and now we've introduced Catch support. It includes a built-in test runner that allows you to view the test results and sort them by duration, rerun failed tests, export test results, navigate instantly to the source code, etc.
One more feature that many of our users have requested is support for Microsoft Visual C++ compiler.
There are three important things you need to know if you'd like to try it in CLion:
- Use the Registry option clion.enable.msvc to enable this support.
- CLion supports Microsoft Visual C++ compiler that ships with VS 2013, 2015 and 2017.
- There's no support for msbuild. CLion works through CMake and the NMake generator.
CLion auto-detects the Visual Studio versions installed on your machine; provides settings to configure the Microsoft Visual C++ compiler path, architecture and platform; and finally runs Microsoft Visual C++ compiler to compile your program. It also helps with navigation through the compiler errors in the Messages Build tool window.
It's important to understand that this support is currently experimental, meaning there are known issues, the biggest being that there's no support yet for specific Microsoft C++ language extensions. We will continue to work on it within the 2017.2 EAP.
Find in Path
In CLion it's possible to search for text across the whole project or any selected scope, with the Find in Path and more
IntelliJ IDEA 2017.1 is available for download! In addition to many important bug fixes, this massive update brings lots of improvements to supported languages, frameworks, and built-in tools.
- Java 9: The latest builds of JDK 9 are fully supported, with assisted project import and coding assistance for editing module declarations. Built-in inspections validate module declarations and. | http://www.jetbrains.com/allnews.jsp?year=2009 | CC-MAIN-2017-47 | refinedweb | 1,447 | 63.8 |
'/>
to the example.gwt.xml file. We'll rewrite the main code and add a couple packages to do calls to servers that provide JSON output (see The Same Origin Policy sidebar). For this, add two classes to the client: JSONRequest and JSONRequestHandler; their code is shown in Listings 2 and 3.
The Same Origin Policy
The Same Origin Policy (SOP) is a security restriction, which basically prevents a page loaded from a certain origin to access a page from a different origin. By origin, we mean the trio: protocol + host + port. In, the protocol is http, the host is, and the port is 80. The SOP would allow access to any document coming from, but disallow going to (different protocol), (different host) or (different port).
Why is this a good idea? Without it, it would be possible for JavaScript from a certain origin to access data from another origin and manipulate it secretly. This would be the ultimate phishing. You could be looking at a legitimate, valid, true page, but it might be monitored by a third party. With SOP in place, you know for certain that whatever you are viewing was sent by the true origin. There can't be any code from other origins.
Of course, for GWT, this is a bit of a bother, because it means that a client application cannot simply connect to any other server or Web service to get data from it. There are (at least) two ways around this: a special, simpler way that allows getting JSON data only or a more complex solution that implies coding a server-side proxy. Your client calls the proxy, and the proxy calls the service. Both solutions are explained in the Google Web Toolkit Applications book (see Resources). In this article, we use the JSON method, and you can find the source code at.
The simple JSON method requires a special callback routine, and this could be a showstopper. However, many sites implement this, including Amazon, Digg, Flickr, GeoNames, Google, Yahoo! and YouTube, and the method is catching on, so it's quite likely you will be able to find an appropriate service.
Listing 2. Source Code for the JSONRequest Class
package com.kereki.client;.kereki.client.JSONRequestHandler:: onRequestComplete( Lcom/google/gwt/core/client/JavaScriptObject;)(j); }; eval( "window." + callbackName + "=tmpcallback" ); }-*/; }
Note that the last two methods are written in JavaScript instead of Java; the JavaScript code is written inside Java comments. The special @id... syntax inside the JavaScript is used for accessing Java methods and fields from JavaScript. This syntax is translated to the correct JavaScript by GWT when the application is compiled. See the GWT documentation for more information.
Listing 3. Source Code for the JSONRequestHandler Class
package com.kereki.client; import com.google.gwt.core.client.JavaScriptObject; public interface JSONRequestHandler { public void onRequestComplete(JavaScriptObject json); }
You can find the code for this listing and the previous one at.
Let's opt to create the screen completely with GWT code. The button will send a request to a server (in this case, Yahoo! News) that provides an API with JSON results. When the answer comes in, we will display the received code in a text area. The complete code is shown in Listing 4, and Figure 3 shows the running program.
Listing 4. Source Code for the Main Program
package com.kereki.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.user.client.ui.*; import com.google.gwt.json.client.*; import com.google.gwt.http.client.URL; import com.kereki.client.JSONRequest; import com.kereki.client.JSONRequestHandler; public class example implements EntryPoint { public void onModuleLoad() { final TextBox tbSearchFor = new TextBox(); final TextArea taJsonResult = new TextArea(); taJsonResult.setCharacterWidth(80); taJsonResult.setVisibleLines(20); final HorizontalPanel hp1 = new HorizontalPanel(); Button bGetNews = new Button("Get news!", new ClickListener() { public void onClick(Widget sender) { JSONRequest.get( ""+ "NewsSearchService/V1/newsSearch?"+ "appid=YahooDemo&query="+ URL.encode(tbSearchFor.getText())+ "&results=2&language=en"+ "&output=json&callback=", new JSONRequestHandler() { public void onRequestComplete( JavaScriptObject json) { JSONObject jj= new JSONObject(json); taJsonResult.setText(jj.toString()); }; } ); } }); hp1.add(new Label("Search for:")); hp1.add(new HTML(" ",true)); hp1.add(tbSearchFor); hp1.add(new HTML(" ",true)); hp1.add(bGetNews); RootPanel.get().add(hp1); RootPanel.get().add(new HTML("<br>",true)); RootPanel.get().add(taJsonResult); } }
The code in Listing 4 shows access to a single service, but it would be easy to connect to several sources at once and produce a mashup of news.
After testing the application, it's time to distribute it. Go to the directory where you created the project, run the compile script (in this case, example_script.sh), and copy the resulting files to your server's Web pages directory. In my case, with OpenSUSE, it's /srv/www/htdocs, but with other distributions, it could be /var/www/html (Listing 5). Users could use your application by navigating to, but of course, you probably will select another path.
Listing 5. Compiling the Code and Deploying the Files to Your Server
# cd ~/examplefiles/ # sh ./example-compile Output will be written into ./www/com.kereki.example Copying all files found on public pathCompilation succeeded # sudo cp -R ./www/com.kereki.example /srv/www/htdocs/
We have written a Web page without ever writing any HTML or JavaScript code. Moreover, we did our coding in a high-level language, Java, using a modern development environment, Eclipse, full of aids and debugging tools. Finally, our program looks quite different from classic Web pages. It does no full-screen refreshes, and the user experience will be more akin to that of a desktop program.
GWT is a very powerful tool, allowing you to apply current software engineering techniques to an area that is lacking good, solid development tools. Being able to apply Java, a high-level modern language, to solve both client and server problems, and being able to forget about browser quirks and incompatibilities, should be enough to make you want to give GWT a spin.
Resources
Google Web Toolkit Applications by Ryan Dewsbury, Prentice-Hall, 2008.
Google Web Toolkit for AJAX by Bruce Perry, PDF edition, O'Reilly, 2006.
Google Web Toolkit Java AJAX Programming by Prabhakar Chaganti, Packt Publishing, 2007.
Google Web Toolkit Solutions: Cool & Useful Stuff by David Geary and Rob Gordon, PDF edition, Prentice Hall, 2007.
Google Web Toolkit Solutions: More Cool & Useful Stuff by David Geary and Rob Gordon, Prentice Hall, 2007.
Google Web Toolkit—Taking the Pain out of AJAX by Ed Burnett, PDF edition, The Pragmatic Bookshelf, 2007.
GWT in Action: Easy AJAX with the Google Web Toolkit by Robert Hanson and Adam Tacy, Manning, 2007.
AJAX: a New Approach to Web Applications:
AJAX: Getting Started: developer.mozilla.org/en/docs/AJAX:Getting_Started
AJAX Tutorial:
Apache 2.0 Open Source License: code.google.com/webtoolkit/terms.html
Eclipse:
Google Web Toolkit: code.google.com/webtoolkit
GWT4NB, a Plugin for GWT Work with NetBeans:
Java SE (Standard Edition): java.sun.com/javase
Java Development Kit (JDK): java.sun.com/javase/downloads/index.jsp
JSON:
JSON: the Fat-Free Alternative to XML:
NetBeans:
Same Origin Policy, from Wikipedia: en.wikipedia.org/wiki/Same_origin_policy
Web 2.0, from Wikipedia: en.wikipedia.org/wiki/Web_2
What Is Web 2.0?, by Tim O'Reilly:
XML:. | https://www.linuxjournal.com/magazine/web-20-development-google-web-toolkit?quicktabs_1=0 | CC-MAIN-2018-22 | refinedweb | 1,212 | 50.12 |
React and React Native finally feel the same
If you're a developer of both React and React Native apps, it can be tough to switch between platforms because they feel so different. And in many ways React Native feels relatively... well, backwards.
Despite great improvements in DX (Developer Experience) for web development with animation libraries like Framer Motion and much easier styling with Tailwind CSS, React Native is still mired in the madness of creating StyleSheets and managing animation states with Animated or Reanimated.
Yes, I know it's basically all JSX. But jumping from CSS and declarative animations on web to React Native's Animated.spring and StyleSheet.create is just a real big pain, and requires a lot of learning.
This is a big problem for small teams - vastly different platforms means developers need to learn a lot more to do both, or you need to hire more developers on separate web and mobile teams.
But this problem is finally solved 🎉
<motion.div React Native component </Text> </MotionView>
Using tailwindcss-react-native and Legend-Motion we can now write React and React Native code using the same styling and animation patterns, and even mix them together in React Native Web.
In this example you can see an HTML element in React right next to a React Native element in React Native Web, styled and animated in the same way 🤯.
The Problem
React and React Native are similar but different in significant ways, so although React components and React Native components share the same concepts, they need to be written fundamentally differently because:
- Styling is different: React uses CSS and React Native uses StyleSheet.
- Animations are different: React uses CSS transitions or libraries like Framer Motion while React Native uses the built-in Animated or Reanimated.
- Navigation is different: Web and mobile apps are just fundamentally different, so (for now) we're fine with having separate navigation systems and we're focusing on the components themselves. Though, Solito is an interesting project trying to align them that we're watching closely.
The Solution
React developers have recently aligned around using Tailwind CSS for styling and Framer Motion for animations. These both have great DX that feels in many ways easier than the built-in React Native solutions. So if we use libraries for React Native that bring our favorite APIs to React Native, then we can have the same developer nirvana on both platforms.
1. Styling with tailwindcss-react-native
tailwindcss-react-native is a new library that uses Tailwind CSS as a universal design system for all React Native platforms. It has three features that are crucial for us:
- It uses
classNameas a string, just like React components.
- It has great performance because it converts
classNameto styles with a Babel plugin so there is almost no runtime cost.
- In React Native Web it simply passes
classNamestraight through to the DOM components, so it uses normal Tailwind CSS with no overhead.
This means we can have convenient and familiar Tailwind CSS usage on mobile with no overhead, and on React Native Web it just uses Tailwind CSS directly. If you inspect the example below in your browser developer tools you'll see the classNames passed through to the rendered div element.
import { Pressable, Text } from "react-native"; /** * A button that changes color when hovered or pressed * The text will change font weight when the Pressable is pressed */ export function MyFancyButton(props) { return ( <Pressable className="p-4 rounded-xl component bg-violet-500 hover:bg-violet-600 active:bg-violet-700" > <Text className="font-bold component-active:font-extrabold" {...props} /> </Pressable> ); }
2. Animations with Legend-Motion
Legend-Motion is a new library (that we built) to bring the API of Framer Motion to React Native, with no dependencies by using the built-in Animated. This lets us create animations declaratively with an
animate prop, and the animation will update automatically whenever the value in the prop changes.
Try hovering over and clicking the box to see it spring around.
<Motion.View initial={{ y: -50 }} animate={{ x: value * 100, y: 0 }} whileHover={{ scale: 1.2 }} whileTap={{ y: 20 }} transition={{ type: "spring" }} />
3. Mix React and React Native Web
React Native Web supports mixing HTML and React Native elements together, so it's easy to incrementally drop React Native Web components into a React app. That's a huge boon because we can drop our React Native components into our web apps without needing to write the whole thing with React Native Web.
<motion.div React Native Element </Motion.Text> <motion.div className="p-5 mt-6 bg-blue-600 rounded-lg" whileHover={{ scale: 1.1 }} transition={{ type: 'spring' }} > DIV text </motion.div> </Motion.View> </motion.div>
Putting it all together
Using tailwindcss-react-native and Legend-Motion together we can build complex React Native components in an easy declarative way that will look very familiar to React developers:
<Motion.View className="p-4 font-bold bg-gray-800 rounded-lg" animate={{ x: value * 50 }} > <Text> Animating View </Text> </Motion.View> <Motion.View className="p-4 font-bold bg-gray-800 rounded-lg" whileHover={{ scale: 1.1 }} whileTap={{ x: 30 }} > <Text> Press me </Text> </Motion.View>
Try it now
1. Legend-Motion
Legend-Motion has no dependencies so it's easy to install.
npm i @legendapp/motion
Then using it is easy:
import { Motion } from "@legendapp/motion" <Motion.View animate={{ x: value * 100, opacity: value ? 1 : 0.5, scale: value ? 1 : 0.7 }} > <Text>Animating View</Text> </Motion.View>
See the docs for more details and advanced usage.
2. tailwindcss-react-native
tailwindcss-react-native has some tailwindcss configuration and a babel plugin so see its docs to get started.
3. React Native Web
React Native Web support for this is right on the bleeding edge. The pre-release version of React Native Web 0.18 adds the style extraction features that tailwindcss-react-native depends on. But there's an issue in its implementation of Animated that breaks all other styles when using using extracted styles. I have a fork of the pre-release 0.18 version that fixes this, so if you want to try it now, install
react-native-web from my fork:
npm i
It's a pre-release version so of course be careful when using it in production, but we're using it for the examples on this site and another app in development and haven't found any issues. Hopefully RNW 0.18 will release soon with Animated working well, and we can stop using my fork 🤞.
Towards Developer Utopia 🌟☀️✨🌈
To get to the utopic future of one platform that runs everywhere there's basically three paths:
- All web: This has long been the only viable solution, but mobile web apps can be slow and clunky if not done right. It is possible to build great mobile web apps, and we'll have a future blog post on that, but it's hard.
- All React Native: React Native Web is getting there! But it still needs to progress further, and we hope it does! See The Case for the React Native Web Singularity for a deeper dive. For now, it has a performance overhead compared to normal web apps and doesn't support all web features yet.
The problem with both of those solutions is you have to go all in on one platform and accept the limitations. We prefer what I like to call:
- A Pleasant Mix 🥰: We use React Native for mobile apps where it shines. We use React for web apps where it shines, and we drop in React Native Web components when we want to share components. For example, we have an admin dashboard in React with a Preview button that embeds the actual React Native components users see in the mobile apps.
Now that we finally can use the same styling and animation patterns, it's much easier for one team to work on both React and React Native. Until recently we had separate web and mobile teams, but in just the past few weeks that we've been using tailwindcss-react-native and Legend-Motion, we've already merged everyone into one team that can do anything 🚀.
Stay tuned
We are very excited about this new world of React and React Native working beautifully together! And we hope you are too 🎉🥳.
A huge shoutout to tailwindcss-react-native for being so great. Give it a star on Github and follow Mark Lawlor for updates.
Legend-Motion is our first open source library and we plan to keep improving it. We're also working on pulling out more of our core code into open source projects, so keep an eye on this blog and follow us or me on Twitter for updates: @LegendAppHQ or @jmeistrich. | https://legendapp.com/dev/react-and-native/ | CC-MAIN-2022-40 | refinedweb | 1,466 | 53 |
A raw_ostream of a file for reading/writing/seeking. More...
#include "llvm/Support/raw_ostream.h"
A raw_ostream of a file for reading/writing/seeking.
Definition at line 597 of file raw_ostream.h.
Open the specified file for reading/writing/seeking.
If an error occurs, information about the error is put into EC, and the stream should be immediately destroyed.
Definition at line 908 of file raw_ostream.cpp.
References llvm::make_error_code(), and llvm::raw_fd_ostream::supportsSeeking().
Check if
OS is a pointer of type raw_fd_stream*.
Definition at line 931 of file raw_ostream.cpp.
References llvm::raw_ostream::get_kind(), and llvm::raw_ostream::OK_FDStream.
This reads the
Size bytes into a buffer pointed by
Ptr.
On success, the number of bytes read is returned, and the file position is advanced by this number. On error, -1 is returned, use error() to get the error code.
Definition at line 921 of file raw_ostream.cpp.
References assert(), llvm::raw_fd_ostream::error_detected(), llvm::raw_fd_ostream::get_fd(), llvm::raw_fd_ostream::inc_pos(), llvm::MipsISD::Ret, and llvm::Check::Size. | https://www.llvm.org/doxygen/classllvm_1_1raw__fd__stream.html | CC-MAIN-2021-39 | refinedweb | 166 | 53.78 |
I am trying to write a program that will allow the user to search for a first or last name within a document full of people's names, and respond with the position of that name within the .txt file. What I have right now keeps returning -1 for the position and I'm not sure what's wrong. Any help would be much appreciated.
import java.io.*; import java.util.Scanner; class SearchFunction { public static void main(String[] args) { //prompts user for name to search for Scanner input = new Scanner (System.in); System.out.println("Who would you like to search for (family or given name)?"); String searchText = input.nextLine(); //chooses the name.txt document to search through String fileName = "names.txt"; StringBuilder sb = new StringBuilder(); try { BufferedReader reader = new BufferedReader(new FileReader(fileName)); //Reads until the end of the file while (reader.ready()) { //Read line-by-line sb.append(reader.readLine()); } } catch(IOException ex) { ex.printStackTrace(); } String fileText = sb.toString(); System.out.println("Position in file : " + fileText.indexOf(searchText)); } } | https://www.daniweb.com/programming/software-development/threads/421685/trouble-searching-a-txt-file | CC-MAIN-2022-21 | refinedweb | 171 | 60.51 |
Details
- Type:
Bug
- Status:
Closed
- Priority:
Major
- Resolution: Fixed
- Affects Version/s: None
- Fix Version/s: 1.9-beta-4, 1.8.4
- Component/s: None
- Labels:None
- Number of attachments :
Description
Performing a lot of system calls causes Groovy to die on Linux with an IOException for "Too many open files". The cause is streams which are left open by system calls:
(1..n).each{ "ls".execute().text }
This method should be changed to close all streams after it gets the text from them.
Issue Links
- is superceded by
GROOVY-5058 Improved process execution
Activity
Uri, what version of Groovy are you talking about? File.text will use BuffereReader.text and the code for that looks like this:
public static String getText(BufferedReader reader) throws IOException { StringBuilder answer = new StringBuilder(); // reading the content of the file within a char buffer // allow to keep the correct line endings char[] charBuffer = new char[8192]; int nbCharRead /* = 0*/; try { while ((nbCharRead = reader.read(charBuffer)) != -1) { // appends buffer answer.append(charBuffer, 0, nbCharRead); } Reader temp = reader; reader = null; temp.close(); } finally { closeWithWarning(reader); } return }
I know we had problems with that kind of thing quite some time back, but these are supposed to be solved. And the code above does close the Reader.
Groovy Version: 1.8.0 JVM: 1.6.0_14
have you a program showing that problem?
Yes please see the snippet in the stackoverflow thread linked above. I think the input, output, and error streams need to be closed.
Ok, so the problem is on Process, not on File. I haven't seen that, sorry. Process#getText closes the InputStream. The question is if it makes sense to also close error and output streams through this method. I guess that is something we can do, but we would potentially break some code. Also if we go this route we have to think of the case of process error and/or process input stream buffers being full and thus blocking the process from finnishing what it had to tell us.
Paul, isn't that something for you?
Hmm yeah maybe it should just close the STDOUT stream. It will break some legacy code but in those cases the stream would have been empty anyway. If my proposal for new mergedText and close methods are accepted, then we'll be able to concicesly close all the streams in all cases. We'll just need to write some notes documenting the pitfalls of executing commands and how to avoid them using the new methods.
I see a stacktrace on stackoverflow but no code. Perhaps I am missing something. Do you have some code which illustrates the problem you are talking about? Thanks.
Attached file to bug report. You can uncomment the "No error" code to see that closing the streams does fix the error.
...
<removed dir>
<removed dir>
<removed dir>
Caught: java.util.concurrent.ExecutionException: org.codehaus.groovy.runtime.InvokerInvocationException: java.io.IOException: Cannot run program "ls": java.io.IOException: error=24, Too many open files
at groovyx.gpars.GParsPool.runForkJoin(GParsPool.groovy:305)
at UsageAnalyzer2$_run_closure2_closure6.doCall(UsageAnalyzer2.groovy:36)
at groovyx.gpars.GParsPool$_withExistingPool_closure1.doCall(GParsPool.groovy:170)
at groovyx.gpars.GParsPool$_withExistingPool_closure1.doCall(GParsPool.groovy)
at groovyx.gpars.GParsPool.withExistingPool(GParsPool.groovy:169)
at groovyx.gpars.GParsPool.withPool(GParsPool.groovy:141)
at groovyx.gpars.GParsPool.withPool(GParsPool.groovy:117)
at UsageAnalyzer2$_run_closure2.doCall(UsageAnalyzer2.groovy:35)
@Paul, the example basically is (1..n).each{ "ls".execute().text }
@Uri, getText does close STDOUT. Since you are not happy with that, it is obviously not enough.
It seems that the output stream can be closed safely once the process has exited. It makes sense that text would only close STDOUT since it only reads STDOUT. What's missing is the ability to read both STDOUT and STDERR and close both concisely.
Changing the behavior of the DGM process methods is certainly a possibility. However, the current "design" of many of these methods is very much a mix and match toolkit style. The getText() method has never been designed to be an all-in-one solution, rather a light-weight layer over the existing process methods to make them a little bit nicer.
A common existing usage pattern is:
p = "ls = build.gradle".execute() p.waitFor() println "O: " + p.text // O: build.gradle println "E: " + p.err.text // E: ls: =: No such file or directory
If getText() closed all the streams, then obviously the second println above would fail.
The existing methods allow closing of the error stream directly if desired:
def p = "ls = build.gradle".execute() p.waitFor() p.err.close() println "O:\n" + p.text
Trying to change the existing methods is possible but might not be what people expect given the current mix and match style.
At the moment, the closest we have to an all in one solution is the waitForProcessOutput() methods. At the moment, they don't close the output and error streams but probably should. In the first instance, that is what I am going to fix. That will then allow the following solutions to the above problem:
p = "ls = build.gradle".execute() def sout = new StringBuilder() def serr = new StringBuilder() p.waitForProcessOutput(sout, serr) println "O:\n" + sout println "E:\n" + serr
Or if merging of the streams is desired:
p = "ls = build.gradle".execute() def sb = new StringBuffer() p.waitForProcessOutput(sb, sb) println "OE:\n" + sb
This should stop the "Too many open files" error albeit not in as compact a syntax as might be desired.
I think a more compact solution needs further discussion. It might need to be separate from the existing solutions or we might have to bite the bullet and do some wrapping of Process objects.
OK, change made. If you are in a position to test your example with a snapshot jar and alter your code to use the slightly longer version usign waitForProcessOutput(), that would be great. It would be interesting to ensure that the errors go away. At present I am not closing the input stream as none should be in use but it would be useful to see what results you get.
Sure I could test it. Just send me the file and instructions on how to install it.
It might be useful to have an example for evaluating proposals. I'll suggest the following snippet, written in Perl:
if (`ls *.ext1` =~ /\S+/) { ... } elsif (`ls *.ext2` =~ /\S+/) { ... }
Right now, it would look like this.
def sb1 = new StringBuffer() def process1 = "ls *.ext1".execute() process1.waitForProcessOutput(sb1, sb1) def sb2 = new StringBuffer() def process2 = "ls *.ext2".execute() process2.waitForProcessOutput(sb2, sb2) if (sb1 =~ /\S+/) { ... else if (sb2 =~ /\S+/) { ... }
If you grab a snapshot jar from our CI server and just replace your existing groovy or groovy-all jar.
You should grab the one closest to your current versions, pick groovy/groovy-all and pick the latest 1.7.x or 1.8.x jar depending on what you are currently using.
I grabbed groovy-all-1.8.3-SNAPSHOT.jar and placed it into my groovy embeddable directory and renamed it to groovy-all-1.8.2.jar. I then changed the script to use waitForProcessOutput() and ran it in the case showing the error and it still occurs. Did I test it right?
It depends on how your are running groovy. If you are referencing the groovy-all jar directly (e.g. in an IDE) then you have done the correct steps. If you are using groovy from the commandline or groovyConsole in is likely using the non-all jar in the lib directory.
The change seems to prevent the exception now.
Cool. Thanks for trying that out. Next we'll have to think about further shorthands!
Though perhaps that could be a separate issue given the title of this issue?
Discussed here: | http://jira.codehaus.org/browse/GROOVY-5049?attachmentOrder=asc | CC-MAIN-2013-48 | refinedweb | 1,306 | 68.06 |
Hi. It seems that cProfile does not support throwing exceptions into generators properly, when an external timer routine is used.
The problem is that _lsprof.c: ptrace_enter_call assumes that there are no exceptions set when it is called, which is not true when the generator frame is being gen_send_ex'd to send an exception into it (Maybe you could say that only CallExternalTimer assumes this, but I am not sure). This assumption causes its eventual call to CallExternalTimer to discover that an error is set and assume that it was caused by its own work (which it wasn't).
I am not sure what the right way to fix this is, so I cannot send a patch. Here is a minimalist example to reproduce the bug:
import cProfile import time p=cProfile.Profile(time.clock) def f(): ... yield 1 ... p.run("f().throw(Exception())") Exception exceptions.Exception: Exception() in <cProfile.Profile object at 0xb7f5a304> ignored Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/cProfile.py", line 135, in run return self.runctx(cmd, dict, dict) File "/usr/lib/python2.5/cProfile.py", line 140, in runctx exec cmd in globals, locals File "<string>", line 1, in <module> File "<stdin>", line 1, in f SystemError: error return without exception set | https://mail.python.org/archives/list/python-dev@python.org/message/D27MT3HVWHM6RZTGC5E2BWCLUS3PJNGO/ | CC-MAIN-2021-04 | refinedweb | 217 | 64.91 |
11). If it does, then we allocate enough memory to hold a copy of that string (line 14). Finally, we have to manually copy the string (lines 17 and 18).
Now let’s do the overloaded assignment operator. The overloaded assignment operator is slightly trickier:
Note that our assignment operator is very similar to our copy constructor, but there are three major differences:
Please remove my first comment.
NOTE: make a sense immediately nulling pointer.
// assumes m_data is initialized
void MyString::deepCopy(const MyString& source)
{
// first we need to deallocate any value that this string is holding!
delete[] m_data;
m_data = nullptr;
// because m_length is not a pointer, we can shallow copy it
m_length = source.m_length;
// m_data is a pointer, so we need to deep copy it if it is non-null
if (source.m_data)
{
// allocate memory for our copy
m_data = new char[m_length];
// do the copy
for (int i{ 0 }; i < m_length; ++i)
m_data[i] = source.m_data[i];
}
}
Your code writes to `m_data` twice (Once to set it to `nullptr`, once again to set it to the new array). When you move `m_data = nullptr` to the `else` part, you're only writing to it once.
"Your code writes to `m_data` twice" -- It is normal practice. Please check it.
1) You should to nulled a freeing memory (delete [] m_buf).
2) You can to forget to nulled memory in condition "else"
Be careful with code.
// assumes m_data is initialized
void MyString::deepCopy(const MyString& source)
{
// first we need to deallocate any value that this string is holding!
delete[] m_data;
// because m_length is not a pointer, we can shallow copy it
m_length = source.m_length;
m_data = nullptr;
I think the deepCopy method will cause unexpected behavior if you call MyString myString{"Something"}; myString.deepCopy(myString); because there is no self assignment-like brace! Unless the method is private so it can't be called (which is still not extremely safe) or perhaps the const parameter input is smart enough to not allow deleting itself indirectly, I am still learning so I don't know.
I think you can simplify the code of your assignment operator overload (DRY) from this
to this
Good point, lesson updated
In your copy constructor, you initialise `m_data` with `nullptr`:
Is there any particular reason why you do this? Is it because you want `m_data` to point to something when you call `delete`?
This lesson didn't follow the always-initialize-everything recommendation. If the constructor didn't initialize `m_data`, `deepCopy` would try to `delete` an invalid pointer, which causes undefined behavior. (Deleting a `nullptr` is a no-op).
I've updated the lesson to initialize all members at their declaration. Now the constructor doesn't have to do it manually anymore.
Hello guys. I tried to write the full program of this lesson and i have a question for it. Here is the code.
1) Error C6386:Buffer overrun while writing to m_data: the writable size is m_length 1 bytes, but two bytes might be written. How to fix this error and what does it really mean?
If i did something else wrong too, would be glad to hear it.
- `getLength()` doesn't return the length of the string
- Functions that don't modify a member should be `const`
- Line 50 is always `true`
1) C6386 is a warning. It means that `m_data` is an array with 1 element but you're accessing 2 elements. You're not doing that though, this warning is wrong.
I corrected those mistakes but it still gets me this error:
"HEAP CORRUPTION DETECTED. CRT detected that the application wrote to memory after end of heap buffer."
what should i do about it?
You've got a problem in your code that causes this. I'm not going to tell you what it is, because your compiler should have told you. Either you didn't enable warnings, or you're ignoring them. Enable warnings, read them, and your mistake is obvious.
Do we need the condition "if (source.m_data)" in the code below as we have assert(source) defined in the constructor? So, source can't be NULL.
We also already set m_data=nullptr in deepCopy, why do we do that again in copy constructor?
Why can't we have the copy constructor format and used different member function like 'deepCopy'?
I meant, can't we just have the following?When we have our own copy constructor, then the default one won't be called to do shallow copies.
In the above code if I use delete p to prevent memory leak I am getting
*** Error in `./a.out': double free or corruption (out): 0x0000000000400890 ***
Aborted
Can you please explain why ?
Thanks,
Ruchika
`p` is uninitialized in line 21. The object didn't exist at that point, so there's no need to delete anything.
But in your deep copy example you did the same
We're initializing `m_data` to a `nullptr` before calling `deepCopy`. Deleting a `nullptr` has no effect, so this is alright. You didn't initialize `p`, so you get undefined behavior.
Got it . thanks !
Hi!
Could we not just put the deepCopy()-contents into the operator= function and then use it instead of deepCopy() in the copy constructor?
Interestingly, the compiler didn't complain about using the this-pointer in a constructor. So that means even constructors have the this pointer?
I can't think of a reason not to do this in `operator=`.
All non-static member functions have a `this` pointer.
Hi.I just want to be sure:
In @deepCopy line 5 when you delete m_data, what is your intention?
Is it because it contains garbage address and we want to initialize it first?
or we want it to be nullptr?
It shouldn't be to avoid self assigning troubles, we've done the check in the overload when calling @deepCopy from the =overload)!
or it may cause some other trouble if we don't do so in some other cases?
I've checked:
without that line code runs fine.(I assume that even if it is garbage we will give it a proper address value)
And for the sake of matter, I've replaced line 5 with
and it also runs right.
Is it safe to say that both assigning nullptr and deleting m_data are the same(in this context of course)? And also the nullptr assigning here won't cause memory leak, will it?
`deepCopy` assumes that `m_data` is initialized, ie. either it's a `nullptr`, in which case `delete[]` has no effect, or it's pointing to dynamically allocated memory, so we need to `delete[]` it to avoid a leak.
Under Deep copy example , line 5 why do you delete m_data which is a null pointer ? (being a null pointer it already contains nothing right ? )
`m_data` doesn't have to be a `nullptr`, eg. in line 9 of the assignment operator example (last snippet).
in this lesson for the MyString class why do you have the char as const in the constructor? I tried without const and i got a convertion error.
A string literal can't be stored in a `char*`.
Whenever you have a pointer or reference and don't modify it, mark it `const`.
// self-assignment guard
if (this == &fraction)
return *this;
Hey Alex, can you clarify what these lines are doing i have a bit of trouble understanding them.
It checks if `fraction` is the same object as `this`. Not comparing the contents of the fractions, but comparing their addresses. This is covered in lesson 9.14.
Hello,
in the below snippet of yours, you delete the m_data at 5th line of the MyString::deepCopy(..) function, but still when you define copy constructor you assign m_data(nullptr) at 26th line knowing that it will call deepCopy and be deleted , why is that?
thanks!
All members should be initialized during construction.
`delete[]` doesn't modify the pointer, it deletes the pointed-to object. Since `nullptr` doesn't point anywhere, `delete[]` has no effect.
If `m_data` wasn't initialized, `delete[]` would try to delete an invalid pointer, causing undefined behavior.
thank you
-"All members should be initialized during construction."
But why the m_length is not initialized on 26th line then?
`deepCopy` is called by that constructor. `deepCopy` overrides `m_length` and doesn't read from it, so it doesn't have to be initialized. `m_data` has to be initialized, because `deepCopy` reads from it.
Also, I assume, if only used in constructor copy, line 11 `delete[]` of `deepCopy` makes no senses because a new object is created, but because we our overloading the assignment operator(=) (and reusing `deepCopy`) when our object could already be created (and having m_data allocated) we do `delete[]`.
Hi. Some typos after first code snippet showing deep copying.
As you can see, this is quite a bit more involved than a simple shallow copy! First, we have to check to make sure source even has a string (line 8(must be 11)). If it does, then we allocate enough memory to hold a copy of that string (line 11(must be 14)). Finally, we have to manually copy the string (lines 14 and 15(must be 17 and 18)).
Alex, the typos Arthur pointed out still remain to be fixed (i.e., the line numbers referenced in your description need to be adjusted).
And as so many others have said, thank you for such a finely detailed, logical, and orderly overview of C++!
Thanks for the reminder! Lesson updated.
Wouldn't it be preferable to put the deep copying logic into a function to avoid code duplication?
Yes, though deepCopy should handle an already allocated m_data -- otherwise calling the function could cause the original m_data to be leaked. I've updated the lesson accordingly.
In this code snippet present above in this lesson:
Shouldn't line 18 be:
instead?
Yes. Updated. Thanks!
MyString::MyString(const MyString& source)
{
// because m_length is not a pointer, we can shallow copy it
m_length = source.m_length;
// do the copy
for (int i=0; i < m_length; ++i)
m_data[i] = source.m_data[i];
}
else
m_data = 0;
}
In the above code for deep copy
The m_length = source.m_length should have been m_length = source.m_length+1 to allocate one extra bit to store the bull character '\0' Right????
No, @source.m_length includes the 0-terminator already.
Std::vector tends to be a little slow and std::array has some of the limitations of C-style arrays. While C++ standard library provides tools of first choice, occasionally a class needs to perform its own dynamic memory management.
Here's the skeleton of a container class that encapsulates a dynamic array and defines its special member functions: an all-in-one illustration of tutorial concepts up to "Inheritance". To keep it simple, I've substituted a global const MAX for a potential member variable, m_length. The latter would be required for flexible-sized arrays.
To demonstrate how the compiler handles the move constructor and move assignment class functions, I've inserted calls to a function printAp(), which display the addresses of selected objects. Calls to printAp are bracketed in the class functions to mark them for later removal. To force the creation of an anonymous (temporary) object, a member function reverse() returns an object of the class. Main() serves as a test program as discussed below:
Main does 2 things. Superficially, it creates objects A, B, C, and D. These objects encapsulate unsigned char arrays. Main sets and retrieves values of the first or last elements of the arrays during the test of each class member function. On a deeper level, main shows the behavior of the move constructor and move assignment member functions using the "print a pointer" function, printAp(). The console output on my machine using Visual Studio 2017 in DEBUG mode:
Default Construc, 0
Copy Construc, 1
First Assign, 3
Chain Assign, 3
in reverse, Temp address = 0041F5E4
in move construc, rhs address = 0041F5E4
in move construc, this address = 0041F774
Move Construc, 5
in reverse, Temp address = 0041F5E4
in move construc, rhs address = 0041F5E4
in move construc, this address = 0041F66C
in move assign, rhs address = 0041F66C
in move assign, this address = 0041F78C
Move Assign, 3
object B address = 0041F78C
object C address = 0041F780
object D address = 0041F774
This output is far simpler than it first appears. There's text to show the purpose of each test, and to print an element of the encapsulated array to verify the result. So far so dull.
The rest is interesting. The third-to-last block of text shows a call to my move constructor for the statement D = C.reverse(). What I want to do is create D and move the result of reverse() into it. To accomplish this, the compiler calls my move constructor for D and hands me an r-value reference to the object "Temp", which I created in reverse() for a return value. Smart! Within the move constructor, "this" contains the address of D, and &rhs contains the address of "Temp". As Temp is already constructed, all I really need to do is "capture" its data. My move constructor accomplishes this task by first assigning Temp's m_ptr to D's, then assigning NULL to Temp's m_ptr (effectively marking the latter unusable upon its release to the heap). Voila! So far so good.
But what's all this mess for B = D.reverse()? B already exists, so what I want to do is move the result of reverse() directly to it. The compiler does this in 2 steps. First, it creates an anonymous object, then it calls my move constructor to capture Temp's data to it. Just like it did for D above. What? Alright, we get it: move constructor is named a "constructor" for a reason. After capturing "Temp" as an anonymous object, the compiler calls my move assignment function, for the purpose of moving the contents of its anonymous object into my preexisting variable B. Notice in the move assignment function, the anonymous object is passed as an r-value reference, and you can trace its address from "this" (in the move constructor) to &rhs (a parameter in move assignment). Now, within move assignment, "this" points to my existing object, B. The contents of object B will be replaced, so I delete[] its dynamic memory. Then another rehash: I "capture" the anonymous object's data by first assigning the memory ptr of the anonymous object to B's m_ptr, followed by assigning NULL to rhs.m_ptr (marking the latter as unusable upon its release to the heap).
I'd prefer doing the B = D.reverse() in one move-assignment step. Here's the output from the RELEASE build with optimization, skipping up to "Chain Assign":
in reverse, Temp address = 003AF9DC
Move Construc, 5
in reverse, Temp address = 003AF9D8
in move assign, rhs address = 003AF9D8
in move assign, this address = 003AF9E8
Move Assign, 3
object B address = 003AF9E8
object C address = 003AF9E4
object D address = 003AF9DC
The optimized .exe fulfills my wish: it calls my move assignment function with "this" pointing to B, while passing an r-value reference to "Temp" directly. What about my D = C.reverse()? My move constructor isn't even called! D is simply given Temp's address. Hurray for elision!
The reason for looking "under-the-hood" of this process is to know what demands Array objects place on the heap. reverse() passes its return "by-value", but it does not consume any significant heap storage beyond what is required to generate an object for the return (in my case, "Temp"). This understanding is important when MAX is expanded to the thousands.
Alex makes this clear: as a member variable of Array class, m_ptr keeps the code RAII compliant, so (hopefully) no dangling pointer runs amuck. The big disadvantage of doing one's own memory management is that less-than-meticulous code (like not checking ranges) can corrupt the heap.
Hi.
About this line in the first paragraphs:
"... C++ copies each member of the class individually (using the assignment operator for overloaded operator=, and direct initialization for the copy constructor)."
Did you mean to say "initialization" rather than "direct initialization"? As I understand, a copy constructor is invoked during any of the 3 kinds of initialization:
1. copy initialization,
2. direct initialization, and
3. uniform initialization
In this context, we're talking about copying the _members_ of a class. These members are initialized using direct initialization (as opposed to copy initialization).
Hello again, I can't quite figure something out - for the following code snippet you wrote:
If I delete the brackets on lines 4 and 6, the program compiles, but I get the runtime error: Test(50460,0x10039b380) malloc: *** error for object 0x100403700: pointer being freed was not allocated.
I was under the impression that this would run OK because the variables would all stay in scope until the end of the program and because deleting a null pointer has no effect (is that not what this error message is pointing to?) but it looks like I'm missing something. It does print out "Hello World!" but something is not quite right...
Think I've got it, I believe I conflated null pointer and uninitialized pointer?
All pointers in this example have been initialized, neither is a nullptr.
Both @hello and @copy point to the same char array. Once one of @hello or @copy goes out of scope, the char array will be deleted. The other variable will still point to were the char array used to be. When the other variable goes out of scope, the char array will be deleted again, but it doesn't exist. Behavior is undefined.
Hi Alex!
Third code block, line 17 should use @std::strlen
Fixed! Thanks!
Hi!
1) Since
aren't we sure that we will never be copying / assigning a non-null string (if the allocation was successful)?
2) Shouldn't we assign @m_length after allocating new memory and checking @m_data is non-null?
3) Is there a reason not to use strcpy() and use a for loop?
1)
2)
The order doesn't matter
3)
No
Thank you for the quick reply.
1) If we do that, wouldn't the assertion fail and we wouldn't be able to copy / assign a null source.m_data field - because (unless memory allocation failed) no object with a null m_data field would be created? Shouldn't we check instead that new didn't fail?
2) But if @source.m_data is null because the memory allocation of the source object failed, we are assigning whatever length the source believes it successfully allocated when the source object was created while we assign a nullptr to @m_data.
1) There is not @source object, @source is a const char*. I might have misunderstood your question. Can you elaborate on (1)?
> Shouldn't we check instead that new didn't fail?
All we can do is check for nullptr. If allocation fails without the noexcept version of @new, an exception is thrown and this constructor won't be reached anyway.
2) If @source failed to allocate memory, it will have thrown an exception and you shouldn't be able to use the source object anymore. But I agree with you, setting the length after verifying that there actually is data is better.
1) I think I wasn't too clear in the beginning (sorry for my English). What I meant was: every MyString object seems to have a non-null m_data field because we either assert that in the const char* constructor or, as you just explained, if new fails, the constructor won't be reached anyway. If that's true, why do we then check
in the copy constructor and assignment operator overload?
2) This question doesn't make much sense because I forgot new would throw an exception and then we would have to handle that. Thanks for the explanation!
> why do we then check
Seems redundant. But if you were to add another constructor or function that allows @m_data to be a nullptr, this constructor wouldn't break because of that update.
Name (required)
Website
Save my name, email, and website in this browser for the next time I comment. | https://www.learncpp.com/cpp-tutorial/shallow-vs-deep-copying/ | CC-MAIN-2021-17 | refinedweb | 3,367 | 64.41 |
A container holding a set of related constraints. More...
#include <constraint_set.h>
A container holding a set of related constraints.
This container holds constraints representing a single concept, e.g.
n constraints keeping a foot inside its range of motion. Each of the
n rows is given by: lower_bound < g(x) < upper_bound
These constraint sets are later then stitched together to form the overall problem.
Definition at line 51 of file constraint_set.h.
Definition at line 53 of file constraint_set.h.
Definition at line 54 of file constraint_set.h.
Set individual Jacobians corresponding to each decision variable set.
A convenience function so the user does not have to worry about the ordering of variable sets. All that is required is that the user knows the internal ordering of variables in each individual set and provides the Jacobian of the constraints w.r.t. this set (starting at column 0). GetJacobian() then inserts these columns at the correct position in the overall Jacobian.
If the constraint doen't depend on a
var_set, this function should simply do nothing.
Attention:
jac_bock is a sparse matrix, and must always have the same sparsity pattern. Therefore, it's better not to build a dense matrix and call .sparseView(), because if some entries happen to be zero for some iteration, that changes the sparsity pattern. A more robust way is to directly set as follows (which can also be set =0.0 without erros): jac_block.coeffRef(1, 3) = ...
Implemented in ifopt::ExCost, and ifopt::ExConstraint.
The matrix of derivatives for these constraints and variables.
Assuming
n constraints and
m variables, the returned Jacobian has dimensions n x m. Every row represents the derivatives of a single constraint, whereas every column refers to a single optimization variable.
This function only combines the user-defined jacobians from FillJacobianBlock().
Implements ifopt::Component.
Definition at line 51 of file leaves.cc.
Read access to the value of the optimization variables.
This must be used to formulate the constraint violation and Jacobian.
Definition at line 115 of file constraint_set.h.
Initialize quantities that depend on the optimization variables.
Sometimes the number of constraints depends on the variable representation, or shorthands to specific variable sets want to be saved for quicker access later. This function can be overwritten for that.
Definition at line 128 of file constraint_set.h.
Sets the optimization variables from an Eigen vector.
This is only done for Variable, where these are set from the current values of the solvers.
Implements ifopt::Component.
Definition at line 131 of file constraint_set.h.
Definition at line 115 of file constraint_set.h. | https://docs.ros.org/en/kinetic/api/ifopt/html/classifopt_1_1ConstraintSet.html | CC-MAIN-2022-27 | refinedweb | 431 | 51.55 |
24 February 2010 19:36 [Source: ICIS news]
TORONTO (ICIS news)--Enerkem plans to build a new waste-to-biofuels plant, financing the project through a Canadian dollar (C$) 53.8m ($51.2m) strategic investment in Enerkem by Waste Management and other partners, the Canadian biofuels company said on Wednesday.
The new plant – Enerkem’s second such project – would be built in ?xml:namespace>
Waste Management said its investment in Enerkem would help it to extract more value from the wastes and materials it processes.
In December, Enerkem was awarded $50m by the US Department of Energy to develop a waste-to-biofuels project in
Enerkem has a commercial-scale demonstration facility at Westbury,
($1 = C$1.05). | http://www.icis.com/Articles/2010/02/24/9337699/canadas-enerkem-raises-funds-for-second-waste-to-biofuels-plant.html | CC-MAIN-2013-20 | refinedweb | 118 | 50.16 |
Creating search engines the links wont work). I therefor decided to create my own.
To start with I went to the EPiServer SDK to have a look at the PagingControl class. Here I was able to see the namespace and what .dll file it lives in (EPiServer.dll). I then opened up Reflector, to inspect EPiServer.dll and have a closer look at the code.
Description of Reflector by Red Gate.
.NET Reflector enables you to easily view, navigate, and search through, the class hierarchies of .NET assemblies, even if you don’t have the code for them. With it, you can decompile and analyze .NET assemblies in C#, Visual Basic, and IL.
To find the PagingControl class you can either use the search feature or navigate the namespaces.
The great thing is that all the methods are virtual which means that we can override them :).
Start by creating a new class and inherit from PagingControl (remember to add using EPiServer.Web.WebControls;).
Then create a new page template with a PageList control.
Notice that we set the PageList’s PagingControl property to a new instance of our CustomPager web control.
If you open up a browser and run the code, you’ll just get a standard PagingControl with the JavaScript and bad markup (since we haven’t overridden anything yet).
Lets start by adding an ordered list for the paging items.
To do this we have to override the CreatePagingItems, AddSelectedPagingLink and AddUnselectedPagingLink methods.
I added a private property to hold my ordered list (Container), so that I can easily add child controls to it. I Also removed the calls to the AddLinkSpacing method (since we don’t need it).
If you browse the page you’ll see that everything is inside an ordered list now.
To fix the JavaScript links I created a new method CreatePagingHyperLink that will create the HyperLink control with the correct url. I Then added code in the OnInit method to get the query string and set the PageList’s CurrentPagingItemIndex property.
I also added some CSS code to give you an idea of how easy it is to style and change the look.
The result
Adam Blomberg says:Post Author October 8, 2009 at 14:34
Thanks for an excellent tip which many of our SiteSeeker and EPiServer customers will appreciate! A minor tweaking would be to render the current page in the list not as a link but as pure text (as recommended here:). That would require changing the row:
var child = this.CreatePagingHyperLink(pagingIndex, text, altText);
to instead render text, and slightly modifying the CSS (“.PagingContainer a”).
Frederik Vig says:Post Author October 12, 2009 at 00:26
Thanks for that Adam! I’ve updated the AddSelectedPagingLink method and the CSS code.
Frederik
Peter says:Post Author December 9, 2009 at 17:00
I’ve created the CustomPager-class and assigned it to be used in a pagelist and allthough it renders correctly I get some navigation problems. When pressing the “2” to go to the second page in the listing I get a odd-looking version of the start page and the url is “…/Templates/Public/Pages/Articles.aspx?id=27&epslanguage=sv&p=1” instead of “…/sv/Artiklar/?p=2” that I assumed it would be.
I’ve fiddled around in the CreateUrl-function and the url-variable inside it and added the “.PathAndQuery” to the “HttpContext.Current.Request.Url”. I don’t know excactly what this does but it gives me the disered look of the url but all the links in the pagination ends with “?p=1”.
Any idea of what might be the problem?
Nulled Scripts says:Post Author December 23, 2009 at 00:17
Nice post..Keep them coming 🙂 Thanks for sharing.
Andrey Lazarev says:Post Author January 14, 2010 at 11:18
Hello, Frederik!
I’ve used your approach to implement the custom paging and it works OK, but…
Paging works correctly *ONLY* for logged-in users. For anynomous visitor – when you click “2” in paging the same first page will be just reloaded.
Any ideas why this could be?
Frederik Vig says:Post Author January 14, 2010 at 13:47
@Peter – Sorry for not getting back to you until now.. I’ve updated the code a little now to support both friendly and regular urls (just updated the CreateUrl method)
@Andrey – Sounds like a databinding problem.. have you tried using EPiServer paging control? I’m guessing you’ll get the same result with it. This is only guessing, I’ll need to take a look at your code to give a proper answer.
Andrey Lazarev says:Post Author January 14, 2010 at 15:21
Frederik, you mean – using not custom but ‘standard’ paging control? Yes, I tried this too – it is working.
The only difference from your code is that I didn’t placed the EPiServer.PageList control inside the page template but in the WebControl instead:
pageTemplate[ WebControl[PageList] ]
And now I’m trying to apply custom paging to this PageList.
Also I’ve selected to use simple links instead of …:
protected override LinkButton AddSelectedPagingLink(int pagingIndex, string text, string altText)
{
HtmlGenericControl cntrl = new HtmlGenericControl();
cntrl.Attributes.Add(“class”, this.CssClassSelected);
cntrl.InnerText = text;
HtmlGenericControl cntrlSeparator = new HtmlGenericControl();
cntrlSeparator.InnerHtml = ” “;
this.HtmlContainer.Controls.Add(cntrl);
this.HtmlContainer.Controls.Add(cntrlSeparator);
return null;
}
protected override LinkButton AddUnselectedPagingLink(int pagingIndex, string text, string altText, bool visible)
{
HtmlGenericControl cntrl = new HtmlGenericControl();
HyperLink hlChild = this.CreatePagingHyperLink(pagingIndex, text, altText);
hlChild.CssClass = this.CssClassUnselected;
hlChild.Visible = visible;
HtmlGenericControl hlChildSeparator = new HtmlGenericControl();
hlChildSeparator.InnerHtml = ” “;
cntrl.Controls.Add(hlChild);
cntrl.Controls.Add(hlChildSeparator);
this.HtmlContainer.Controls.Add(cntrl);
return null;
}
// Code for this:
private static string CreateUrl(int count)
{
UrlBuilder url = new UrlBuilder(HttpContext.Current.Request.Url.PathAndQuery);
Global.UrlRewriteProvider.ConvertToExternal(url, null, UTF8Encoding.UTF8);
return UriSupport.AddQueryString(url.ToString(), “p”, count.ToString());
}
protected HyperLink CreatePagingHyperLink(int pagingIndex, string text, string altText)
{
HyperLink link = new HyperLink();
this.LinkCounter++;
link.ID = “PagingID” + this.LinkCounter;
link.NavigateUrl = CreateUrl(pagingIndex);
link.Text = text;
link.ToolTip = altText;
return link;
}
And – removed first-last, prev-next links
I have a public property in my webcontrol named ‘EnablePaging’ and I’m using it to select how PageList should be rendered:
if (EnablePaging == true)
{
this.epiNewsListSimple.Paging = true;
this.epiNewsListSimple.PageLink = newssource;
this.epiNewsListSimple.PagingControl = new {%namespace here%}.CustomPager();
this.epiNewsListSimple.PagesPerPagingItem = 3;
this.epiNewsListSimple.MaxCount = -1;
this.epiNewsListSimple.EnableViewState = true;
}
else
{
this.epiNewsListSimple.Paging = false;
this.epiNewsListSimple.PageLink = newssource;
this.epiNewsListSimple.MaxCount = 3;
}
this.epiNewsListSimple.DataBind();
Andrey Lazarev says:Post Author January 14, 2010 at 15:28
Re-tested once again – still same strange behavior. Standard paging is working for PageList and the custom one – isn’t. 🙁
Frederik Vig says:Post Author January 14, 2010 at 15:31
If you remove all the code inside the CustomPager class, so you only have something like this left.
The paging should work. After making sure it works try adding a few more methods and check that it still works, then some more etc, until you find the source of the problem.
Andrey Lazarev says:Post Author January 14, 2010 at 16:27
Frederik, it looks like a dumb joke, but I got it working making this change:
if (EnablePaging == true)
{
this.epiNewsListSimple.Paging = true;
this.epiNewsListSimple.PageLink = newssource;
this.epiNewsListSimple.PagingControl = new CustomPager();
this.epiNewsListSimple.PagesPerPagingItem = 3;
if (Request.QueryString[“p”] != null)
{
this.epiNewsListSimple.PagingControl.CurrentPagingItemIndex = int.Parse(Request.QueryString[“p”].ToString().Trim());
}
}
else
{
this.epiNewsListSimple.Paging = false;
this.epiNewsListSimple.PageLink = newssource;
this.epiNewsListSimple.MaxCount = 3;
}
this.epiNewsListSimple.DataBind();
So, for me it looks like changes to the paging control made from the custom class didn’t change anything in fact 🙁
Very strange…
Anyway – the control is working as expected now.
Øyvind says:Post Author January 29, 2010 at 13:34
Thanx for sharing. If the datasource of your news list is a pagedatacollection, you need to set the lstNewsList.PagingControl.CurrentPagingItemIndex before the Init in the custom pager. But else it works out of the box.
Peter says:Post Author February 2, 2010 at 11:33
I totally forgot to follow up on this page so no harm done. I’ve got it working now thanks to your friendly url-support. To start out I did have the same problem as Andrey had but it was easily fixed. Thanks!
Peter says:Post Author February 10, 2010 at 08:33
How would you go about to make the pager only show 10 pages at a time? E.g. “1 2 3 4 5 6 7 8 9 10 >”, “”. At the moment my pager shows 27 pages with 10 pages on each one of them and my guess is that when these get to about 45 the page listing will continue on outside the graphics and will be unreachable.
Vidar says:Post Author February 18, 2011 at 10:37
Thanks for this great article.
I’ve two questions.
1. I don’t get friendly URLs. I’ve tried removing if (UrlRewriteProvider.IsFurlEnabled)
and also changed
return UriSupport.AddQueryString(url.ToString(), “p”, count.ToString());
to
return UriSupport.AddQueryString(url.Uri.AbsoluteUri, “p”, count.ToString());
as in the friendly url article just to see if it’s friendly. But I still doesn’t get it.
2. How do I remove the div container?
Again, thank you for you support!
Vidar says:Post Author February 18, 2011 at 12:13
Hey! Problem 1. solved. That was only the case on my dev-domputer, once i put it in the test environment, the urls became friendly. | https://www.frederikvig.com/2009/09/creating-a-custom-episerver-paging-control/ | CC-MAIN-2018-09 | refinedweb | 1,584 | 59.5 |
Background
This post shows a very simple technique for processing a gzip compression on a background thread using c# with Visual Studio 2010. What is unique here is we are using no statics to do it. I’m not totally against using statics, but in general, it is best to avoid them. I’ve heard the notorious Ward Bell say statics are evil and have had many cases where they have bitten me. Since I heard Ward say this, I’ve been trying to avoid them where I can.
The Simple Problem
The problem is to simply compress a file to bytes and return to us the compressed, uncompressed and byte array of the result. We can pass parameters into a thread, however we can not return them (when I say thread, I mean the anonymous method that processes our data).
Some Code
So, to that end, Let’s create a main method as below. Notice that it creates a very simple anonymous method which executes the code cryptoCopress.CompressFile(…), then simply starts that thread. Once the thread starts, it simply waits for the thread to end by looping every 50 milliseconds on the thread.IsAlive method. Finally, when it returns, it simply looks at the cryptCompress object for the results. No Statics!
private static void Main(string[] args)
{
var cryptCompress =
new CryptCompress();
var thread =
new Thread(
() =>
cryptCompress.CompressFile
(@"G:\NoBackup\ext-3.2.1\ext-all-debug-w-comments.js"));
thread.Start();
int cnt = 0;
while (thread.IsAlive)
{
cnt++;
Console.WriteLine("Waiting... " + cnt);
Thread.Sleep(50);
}
Console.WriteLine("Before Compression KBytes: {0}",
cryptCompress.BeforeCompressionBytes/1000);
Console.WriteLine("After Compression KBytes: {0}",
cryptCompress.AfterCompressionBytes/1000);
}
Now, Lets look at the CryptCompress class. Notice that it’s basically got one public method (CompressFile) and 3 public properties that will be used to hold the return values. This way, the main method that started the thread can get the results. Again, notice that there is no word static any place in this project.
public class CryptCompress
{
public byte[] CompressedBytes { get; set; }
public long BeforeCompressionBytes { get; set; }
public long AfterCompressionBytes { get; set; }
public void CompressFile(string fileName)
{
using (var fileStream =
new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
var uncompressedBytes = new byte[fileStream.Length];
fileStream.Read(uncompressedBytes, 0,
(int) fileStream.Length);
CompressedBytes = CompressGzip(uncompressedBytes);
BeforeCompressionBytes = fileStream.Length;
AfterCompressionBytes = CompressedBytes.Length;
fileStream.Close();
}
}
/// <summary>
/// Take a simple stream of uncompressed bytes and compress them
/// </summary>
/// <param name="uncompressedBytes"></param>
/// <returns></returns>
public byte[] CompressGzip(byte[] uncompressedBytes)
{
using (var memory = new MemoryStream())
{
using
(var gZipStream =
new GZipStream(memory, CompressionMode.Compress, true))
{
gZipStream.Write
(uncompressedBytes, 0, uncompressedBytes.Length);
}
return memory.ToArray();
}
}
}
The Results
When we run this, notice that it takes 3 iterations (or 150 milliseconds) to complete. I’m only compressing a small file so no surprise. The file is actually 2.7 Megabytes and compress to .7 Megabytes.
That’s it for now! Hope this helps.
buy generic cialis pills online! No condition how grey a hamper is, there will come a in days of yore when they when one pleases on it abstruse (or unattainable) to accomplish and/or state an erection. And while a fetter dominion experience as if it is the end of the fabulous, it is not. buy cheap kamagra online usa
More willingly than you start having nightmares and screaming “I am too immature representing Viagra!,” take a deep breath and tarry calm. buy cheap kamagra usa.
Maybe he’s talking about using a Task, which uses ThreadPool
Target .net 4.0 (sample project targeted 3.5 for me)
change var thread… and thread.Start() with
Task t = Task.Factory.StartNew(() =>
{
cryptCompress.CompressFile(@”G:\NoBackup\ext-3.2.1\ext-all-debug-w-comments.js”);
});
replace while (thread.IsAlive) with
while(!t.IsCompleted)
This does seem more of a “4.0” way to do it with TPL. It does use the static factory to get an instance of Task but I think it still adheres to the heart of the post as opposed to using something like Parallel.Invoke which is a static only method.
caractacus,
Can you post a short example of using threadpool?
Surely the ThreadPool class provides all the functionality you require, whilst remaining scalable? | http://peterkellner.net/2010/12/04/simple-multithreading-pattern-for-c-sharp-with-no-statics-and-gzip-compression/ | CC-MAIN-2018-05 | refinedweb | 698 | 59.9 |
30 April 2010 15:40 [Source: ICIS news]
LONDON (ICIS news)--High methyl ethyl ketone (MEK) prices in Europe and tight supply have led to increased interest in ethyl acetate (etac) material, producers and buyers said on Friday.
“We have already seen a move towards replacing MEK with etac, and we are sold out [of etac] for April,” said a producer.
With etac spot offers regularly around €500/tonne ($658/tonne) lower than MEK offers, some applications were able to substitute etac for the use of MEK, which has boosted demand for etac.
“The switch to etac could make sense. It’s €500/tonne cheaper at the moment,” said an MEK trader.
The downstream applications that are able to substitute etac for MEK are printing, automotives and a few niche applications, MEK sources said.
“Not all applications are able to switch, but there will be some sectors that notice a difference,” said one reseller.
Etac prices were mostly assessed between €840-870/tonne FD (free delivered) NWE (northwest ?xml:namespace>
One etac producer said there was evidence of prices moving closer to €900/tonne FD NWE for May.
The tight supply of MEK was attributed to stronger-than-expected demand in March, which decreased production stockpiles.
The majority of MEK producers said that they were now sold out for the rest of April.
Many market sources also spoke of possible production problems at a major European MEK producer, which could not be verified.
“I’ve never seen the MEK market as tight as it is,” said one trader.
Low availability of MEK has driven prices sharply higher in recent weeks, with material currently trading at €1,200-1,300/tonne FD NWE, up by €330-380/tonne from 27 March, according to ICIS pricing.
It has been the sharp rise in MEK prices that has prompted players to consider switching to etac, they said.
“We can’t easily switch to etac in our business, but there is certainly a section of MEK buyers who can,” said one large solvents customer.
MEK prices were increasing this week due to low availability, with some numbers as high as €1,800/tonne, although this was not seen as representative of the overall market.
“[MEK is] not available. If you can find product, it’s €1,500-1,800/tonne…,” said a trader.
($1 = €0.76)
Mark Victory contributed to this article.
For more on ethyl acetate and ME | http://www.icis.com/Articles/2010/04/30/9355647/europe-etac-demand-increases-as-some-buyers-switch-from.html | CC-MAIN-2014-52 | refinedweb | 405 | 70.13 |
#include <StelApp.hpp>.
Initialize core and default modules.
Load and initialize external modules (plugins).
Get the module manager to use for accessing any module loaded in the application.
Get the locale manager to use for i18n & date/time localization.
Get the sky cultures manager.
Get the texture manager to use for loading textures.
Get the Location manager to use for managing stored locations.
Get the StelObject manager to use for querying from all stellarium objects.
Get the StelObject manager to use for querying from all stellarium objects.
Get the audio manager.
Get the main loading bar used by modules for displaying loading informations..
Make sure that the GL context of the main window is current and valid.
Get flag for using opengl shaders.
Set flag for activating night vision mode.
Get flag for activating night vision mode.
Get the current number of frame per second.
Return the time since when stellarium is running in second.
Report that a download occured.
This is used for statistics purposes. Connect this slot to QNetworkAccessManager::finished() slot to obtain statistics at the end of the program. | http://stellarium.org/doc/0.10.4/classStelApp.html | CC-MAIN-2016-18 | refinedweb | 182 | 62.34 |
Source code for pyro.poutine.block_messenger
from __future__ import absolute_import, division, print_function from pyro.poutine.messenger import Messenger[docs]class BlockMessenger(Messenger): """ This Messenger selectively hides Pyro primitive sites from the outside world. Default behavior: block everything. BlockMessenger has a flexible interface that allows users to specify in several different ways which sites should be hidden or exposed. A site is hidden if at least one of the following holds: 1. msg["name"] in hide 2. msg["type"] in hide_types 3. msg["name"] not in expose and msg["type"] not in expose_types 4. hide_all == True and hide, hide_types, and expose_types are all None For example, suppose the stochastic function fn has two sample sites "a" and "b". Then any poutine outside of BlockMessenger(fn, hide=["a"]) will not be applied to site "a" and will only see site "b": .. doctest:: :hide: >>> from pyro.poutine.trace_messenger import TraceMessenger >>> def fn(): ... a = pyro.sample("a", dist.Normal(0., 1.)) ... return pyro.sample("b", dist.Normal(a, 1.)) >>> fn_inner = TraceMessenger()(fn) >>> fn_outer = TraceMessenger()(BlockMessenger(hide=["a"])(TraceMessenger()(fn))) >>> trace_inner = fn_inner.get_trace() >>> trace_outer = fn_outer.get_trace() >>> "a" in trace_inner True >>> "a" in trace_outer False >>> "b" in trace_inner True >>> "b" in trace_outer True See the constructor for details. :param bool hide_all: hide all sites :param bool expose_all: expose all sites normally :param list hide: list of site names to hide, rest will be exposed normally :param list expose: list of site names to expose, rest will be hidden :param list hide_types: list of site types to hide, rest will be exposed normally :param list expose_types: list of site types to expose normally, rest will be hidden """ def __init__(self, hide_all=True, expose_all=False, hide=None, expose=None, hide_types=None, expose_types=None): super(BlockMessenger, self).__init__() # first, some sanity checks: # hide_all and expose_all intersect? assert (hide_all is False and expose_all is False) or \ (hide_all != expose_all), "cannot hide and expose a site" # hide and expose intersect? if hide is None: hide = [] else: hide_all = False if expose is None: expose = [] else: hide_all = True assert set(hide).isdisjoint(set(expose)), \ "cannot hide and expose a site" # hide_types and expose_types intersect? if hide_types is None: hide_types = [] else: hide_all = False if expose_types is None: expose_types = [] else: hide_all = True assert set(hide_types).isdisjoint(set(expose_types)), \ "cannot hide and expose a site type" # now set stuff self.hide_all = hide_all self.expose_all = expose_all self.hide = hide self.expose = expose self.hide_types = hide_types self.expose_types = expose_types def _block_up(self, msg): """ Uses rule described in main docstring to decide whether to block or expose. :param msg: current message at a trace site, after all execution finished. :returns: boolean decision to hide or expose site. """ # handle observes if msg["type"] == "sample" and msg["is_observed"]: msg_type = "observe" else: msg_type = msg["type"] is_not_exposed = (msg["name"] not in self.expose) and \ (msg_type not in self.expose_types) # decision rule for hiding: if (msg["name"] in self.hide) or \ (msg_type in self.hide_types) or \ (is_not_exposed and self.hide_all): # noqa: E129 return True # otherwise expose else: return False def _process_message(self, msg): msg["stop"] = self._block_up(msg) return None | http://docs.pyro.ai/en/0.2.1-release/_modules/pyro/poutine/block_messenger.html | CC-MAIN-2018-51 | refinedweb | 505 | 51.65 |
Question:
I'm trying to learn descriptors, and I'm confused by objects behaviour - in the two examples below, as I understood
__init__ they should work the same. Can someone unconfuse me, or point me to a resource that explains this?
import math class poweroftwo(object): """any time this is set with an int, turns it's value to a tuple of the int and the int^2""" def __init__(self, value=None, name="var"): self.val = (value, math.pow(value, 2)) self.name = name def __set__(self, obj, val): print "SET" self.val = (val, math.pow(val, 2)) def __get__(self, obj, objecttype): print "GET" return self.val class powoftwotest(object): def __init__(self, value): self.x = poweroftwo(value) class powoftwotest_two(object): x = poweroftwo(10) >>> a = powoftwotest_two() >>> b = powoftwotest(10) >>> a.x == b.x >>> GET >>> False #Why not true? shouldn't both a.x and b.x be instances of poweroftwo with the same values?
Solution:1
First, please name all classes with LeadingUpperCaseNames.
>>> a.x GET (10, 100.0) >>> b.x <__main__.poweroftwo object at 0x00C57D10> >>> type(a.x) GET <type 'tuple'> >>> type(b.x) <class '__main__.poweroftwo'>
a.x is instance-level access, which supports descriptors. This is what is meant in section 3.4.2.2 by "(a so-called descriptor class) appears in the class dictionary of another new-style class". The class dictionary must be accessed by an instance to use the
__get__ and
__set__ methods.
b.x is class-level access, which does not support descriptors.
Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
EmoticonEmoticon | http://www.toontricks.com/2018/06/tutorial-difference-between-using-init.html | CC-MAIN-2018-43 | refinedweb | 273 | 71 |
sandbox/jmf/faq
Frequenting Alphabetic Questions
Helping you and myself
A
Adaptivity
Basilisk uses quadtrees to allow efficient adaptive grid refinement. The first thing we need to do is to remove the line setting the grid to Cartesian i.e.
#include "grid/cartesian.h" (to remove!!)
and to adapt the resolution according to the (wavelet-estimated) discretisation error of field h at each timestep (i++) we add
event adapt (i++) { adapt_wavelet ({h}, (double []){4e-3}, maxlevel = 8); } tree levels in this case.
Axisymmetric
For problems with a symmetry of revolution around the z-axis of a cylindrical coordinate system.
- The longitudinal coordinate (z-axis) is x and the radial coordinate (r-axis) is y.
- Note that y (and so Y0) cannot be negative.
Use
#include "axi.h"
B
Bugs
to report bugs got to basilsik bugs page
C
Compilation
Useful flags
- -fopenmp (use openmp)
- -g (use debugger)
- -lm (link with math library)
- -Wall (Warning all)
D
Density (and viscosity) variable
The density and viscosity are defined here using the arithmetic average.
#define ρ(f) ((f)*rho1 + (1. - (f))*rho2) #define μ(f) ((f)*mu1 + (1. - (f))*mu2) event properties (i++) { foreach_face() { double fm = (f[] + f[-1,0])/2.; alphav.x[] = 1./ρ(fm); muv.x[] = μ(fm); } foreach() alphacv[] = 1./ρ(f[]); }
Dimensions
By default Basilisk runs on a quadtree grid. This also automatically sets a two-dimensional spatial domain.
For the example; 3 Dimensions (octree grid) are defined by an option during the generation of the source file:
qcc -source -grid=octree -D_MPI=1 atomisation.c
So compile with this option, or add:
#include "grid/octree.h"
at the top of your simulation file.
G
Gravity
Adding gravity force in the y direction
event acceleration (i++) { face vector av = a; foreach_face(x) av.x[] -= 0.98; }
I
Initialization
Face vector.
Volume fraction
To initialize the volume fraction
vertex scalar φ[]; foreach_vertex() phi[] = sq(DIAMETER/2) - sq(x) - sq(y); fractions (phi, c);
K
kdtquery
kdtquery is in the Basilisk release. There is just a missing symbolic link so that it’s automatically accessible through PATH. We will fix this.
In the meantime just do
% cd $BASILISK % ln -s kdt/kdtquery % which kdtquery
M
Mask
mask() only works on trees dont use
#include"grid/multigrid.h" (to remove!!)
Macros
Some macros functions are defined in Basilisk (see src/common.h for details)
@define max(a,b) ((a) > (b) ? (a) : (b)) @define min(a,b) ((a) < (b) ? (a) : (b)) @define sq(x) ((x)*(x)) @define cube(x) ((x)*(x)*(x)) @define sign(x) ((x) > 0 ? 1 : -1) @define noise() (1. - 2.*rand()/(double)RAND_MAX) @define clamp(x,a,b) ((x) < (a) ? (a) : (x) > (b) ? (b) : (x)) @define swap(type,a,b) { type tmp = a; a = b; b = tmp; }
If you have problems with some macros please read K&R … to understand up more on how to use C preprocessor directives (i.e. all the keywords starting with #) correctly.
A few tips:
- always enclose expressions within brackets (see #define clamp)
- be careful to add dots to floating point constants
Minimal example
When you have a problem dont say “I have a problem” or “Dont work”, first take a look to the mailing list and then post a Minimal example please
O
Origin
By default Basilisk place the origin (0,0) at the bottom of the left corner in 2D. To move it at the cent of the box we can set
X0 = -L0/2; Y0 = -L0/2;
or the
origin()function
origin (-L0/2, -L0/2.);
L0 being the box size.
R
Random numbers
The
noise() function returns random numbers between -1 and 1, example for setting 0 and 1 in a circle of center (0,0) and of radius 0.1
foreach() a[] = (x*x + y*y < sq(0.2))*(noise() > 0.); boundary ({a});
S
Surface tension
The surface tension and interface curvature are associated to each VOF tracer.
The interface is represented by the volume fraction field by
#include "vof.h" #include "tension.h" ... scalar c[], * interfaces = {c};
and setting by the way doing
c.σ = 1.;
T
Teaching
Basilisk is used to teach general computational fluid mechanics, see | http://basilisk.fr/sandbox/jmf/faq | CC-MAIN-2018-34 | refinedweb | 689 | 65.93 |
I spent a couple of hours today looking at the problem we encountered yesterday with the xpath() function in BizTalk. We were attempting to use an XPath to extract the value of a nested element and assign it to a string variable. The nested element (<Direction>) was in the global (anonymous) namespace, but was a child of an element in a named namespace. The code failed on XmlSerializer de-serialisation with an error saying "<Direction xmlns=''> not expected".
At first, I strongly suspected that the problem was due to the use of the anonymous namespace, especially as the element was defined in a schema that was then imported into the message schema. Both schemas had the 'Element FormDefault' attribute set to default (unqualified), and we had ended up with a horrible interleaved mess of elements, some of which were in defined namespaces, whilst others were in the global namespace. Always, always set Element FormDefault to 'Qualified' in your schemas, unless you have a really good reason not to. We are now in the process of changing all our schemas to eliminate the use of global namespaces.
After a while, I convinced myself that there was a problem with the .NET XmlSerializer, especially after reading a number of news group threads on the Internet. From what I read, it seemed that the XmlSerializer might have problems with "xmlns=''" declarations. To prove the point, I wrote a little code to reproduce the issue. Unfortunately, however, the XmlSerializer worked perfectly, whatever I did. It seems that it has no issues at all with "xmlns=''".
I then spent some time with Reflector, digging into the BizTalk code to see what it was doing, and eventually I discovered the problem...and it was all our fault!!
We had a line of code in the orchestration that attempted to use the BizTalk xpath() function to return the value held in the <Direction> element and assign it to a string variable. The only problem was that the XPath was addressing the <Direction> node, and not its contents. The XPath processor uses XML DOM internally, and expressions return XML nodes or node sets. In our case, the XPath we used was returning an XmlElement node from our XML message. We were trying to assign this to a string variable (doh)!
This very basic XPath error was made opaque by the fact that we got no compile-time error, but instead suffered an run-time exception thrown by the XmlSerializer class. You might reasonably expect that the exception would indicate some kind of type mismatch or cast failure. Instead, we got a general-purpose XmlSerializer exception statibg that the XML content was unexpected. The reason for this becomes clear when we looked a little deeper into what is happening when we call the xpath function. BizTalk generates C# code for the line that calls the xpath function. The generated code calls a method to which it passes the Type of the variable to which the result of the method will be assigned. This Type is used to initialise an instance of XmlSerializer used internally by BizTalk. In our case, we ended up with an instance of XmlSerializer that attempted to de-serialise an XmlElement (addressed by the XPath) as a string object. This, of course, didn't work, and the XmlSerializer returned an exception saying that the XmlElement 'was not expected'.
The XmlSerializer object is used to deserialise XML content obtained using XPathNavigator and XmlNodeReader. In a reversal of the principle of strong typing, BizTalk's XLang/s langauge effectively 'trusts' the developer to select the right type of variable to hold the results of the xpath() function. If the developer gets this wrong (as we did), the code blindly attempts to perform de-serialisation to the incorrect type, and fails at run time.
The best fix in our case was simply to extend the end of the XPath with '/text()'. This returns the text node contained in the <Direction> node (XML DOM sees the text node as a nested node). This nicely de-serialises to a string. Another option would be to retain the XPath as is, but assign the result to an XmlElement variable, and then extract the inner text. This is less direct, and may require an additional atomic scope because XmlElement is not serialisable.
So, the problem was nothing to do with the use of anonymous namespaces or the .NET XmlSerializer. It was a basic logical error in our own code that took ages to spot due to the exception that was raised. If you use the xpath function and get an "<xxxxx xmlns=''> not expected" exception, check your XPath to see what it is actually returning, and the variable you are assigning the results to.
Skin design by Mark Wagner, Adapted by David Vidmar | http://geekswithblogs.net/cyoung/archive/2006/12/12/100981.aspx | crawl-002 | refinedweb | 800 | 60.85 |
sklearn.metrics.mean_absolute_error in Python
This article is about calculating Mean Absolute Error (MAE) using the scikit-learn library’s function sklearn.metrics.mean_absolute_error in Python.
Firstly, let’s start by defining MAE and why and where we use it. MAE is used to find the difference between two paired observation sets taken under consideration. We use MAE to find out how much an observation set differs from the other paired observation set. So, for this article, we are going to use MAE to measure errors between our predicted and observed values of labels. For that, we are going to use sklearn.metrics.mean_absolute_error in Python.
Mathematically, we formulate MAE as:
MAE = sum(yi – xi)/n ; n = number of instances of each observation set
In other words, MAE is an arithmetic average of absolute errors between two sets of observation
Suppose in your Linear Regression task, you calculate predicted “y_pred” by fitting your dataset in a Linear Regression model. Then, it would be best if you had a means of measuring the performance of your model. Let’s use MAE to check the errors between the two observation sets.
For that, we require scikit-learn library installed on our system. Use the following command in your terminal or command prompt to install scikit learn.
pip install scikit-learn
Then in your Python file, execute this line to check if it’s installed properly.
from sklearn.metrics import mean_absolute_error
For the sake of example, let’s consider two iterables as our test label and predicted label i.e., y_test and y_pred, respectively. Here, we obtain y_test by splitting the dataset into test and training sets. We obtain y_pred from our Linear Regression model.
y_true = [3, -0.5, 2, 7] y_pred = [2.5, 0.0, 2, 8]
We use the imported function mean_absolute_error to find MAE.
MAE = mean_absolute_error(y_true, y_pred) print(MAE)
Output:
0.5
Further reading: | https://www.codespeedy.com/sklearn-metrics-mean_absolute_error-in-python/ | CC-MAIN-2020-45 | refinedweb | 315 | 58.58 |
- I need to create an insertion sort within an array of integers. These integers are drawn from a random integer from a range (0,499). The integer will be inserted in the correct position of the array and sorted.
This next step is where I'm having trouble understanding it.
-Insert 100 integers into the array (one per iteration), which will begin with a size of 1. When the
array is fi lled up, a new array of twice the size is created and the contents of the existing array is copied into the new array and the algorithm will continue.
For example the output will give me a sorted array with 1 element and print out that value as the output. I will then increase this array by 2*(the last array size) until it reaches 128 elements.
I'm am able to implement the 100 integers and sort it to correctly output the contents. I'm just not sure how I would copy an array and display 1 element or 2 elements or 4 elements etc.. Each time it iterates.
I hope this makes sense please ask if i need to clarify something.
#include <iostream> #include <ctime> #include <cstdlib> using namespace std; int main() { srand((unsigned)time(NULL)); int i, key; int num[100] = {0}; cout << "Unsorted Array:" << endl; for (i=1; i<101;i++) { num[i] = (rand())%499; cout << i << ":" << num[i] << endl; } for (int j=1; j<101; j++) //Insertion Sort key = num[j]; while (i>=0 && num[i]>key) { num[i+1] = num [i]; i--; } num[i+1] = key; } cout << endl << "Sorted Array:\t" << endl; for (i=1;i<101;i++) { cout << i << ":" << num[i]<< endl; } int newArray[1] = {0}; return 0; }
Thanks guys. I may be thinking too hard on this. From what I can understand I have to create a for loop that will keep going until there's 128 elements. This first array only has 1 element and is displayed and the next element displays the 2 elements. I can't seem to figure out how to copy the first array into this new array because I keep getting index out of bounds error since the array size can't support it. | http://www.dreamincode.net/forums/topic/212475-c-insertion-sort-with-arrays/ | CC-MAIN-2016-22 | refinedweb | 370 | 68.4 |
Realm with SwiftUI Tutorial: Getting Started
In this SwiftUI Realm tutorial, you’ll learn how to use Realm with SwiftUI as a data persistence solution by building a potion shopping list app.
Version
- Swift 5, iOS 14, Xcode 12
Realm Mobile Database is a popular object database management system. It’s open-source, and it can be used on multiple platforms. Realm aims to be a fast, performant, flexible and simple solution for persisting data, while still writing type-safe, Swift code.
SwiftUI is Apple’s latest and hottest UI framework. It uses a declarative syntax to build your views using Swift code. It relies on states to reactively update its views when the user interacts with it. Since Realm uses Live Objects that also update automatically, mixing both frameworks just makes sense!
In this SwiftUI Realm tutorial, you’ll learn how to:
- Set up Realm
- Define data models
- Perform basic CRUD operations on objects
- Propagate changes from the database to the UI
- Handle migrations when your data model changes
You’ll learn all this by implementing a Realm database in an app that keeps track of all the ingredients you need for making magic potions! So grab your potions kit, because it’s time to dive right into this cauldron. :]
Getting Started
Download the project materials using the Download Materials button at the top or bottom of this tutorial. Open PotionsMaster.xcodeproj inside the starter folder.
PotionsMaster is an app built for all your potion-making needs. Potion brewing is a challenging skill. Stirring techniques, timing, and bottling can be arduous tasks, even for experienced wizards. This app helps you keep track of the ingredients you need and those you’ve already bought. With PotionsMaster, even that difficult new potion you’ve been reading about will be a snap!
Now it’s time to get to work. To start, build and run.
PotionsMaster is a simple app that lets you add, update and delete ingredients in a list. But as you play around with the app, you’ll notice a small problem. No matter what you do, the app doesn’t persist your data! In fact, it doesn’t perform any actions when you try to create, update or delete an ingredient. But don’t worry — you’re about to make it work, using Realm.
Project Structure
Before you dive in and fix the app so you can start brewing your next potion, take a close look at the starter project. It contains the following key files:
- Ingredient.swift: This struct is a representation of an ingredient.
- IngredientStore.swift: This is a class implementation of the Store Pattern. This class handles storing ingredients. It’s also where you’ll perform actions on those ingredients.
- IngredientListView.swift: This is the main view of the app. This class displays a
List. There’s one
Sectionfor ingredients to buy, and another for bought ingredients.
- IngredientFormView.swift: You’ll use this
Formto create and update ingredients.
The project uses the Store Pattern to handle states and propagate changes to the UI.
IngredientStore has a list of ingredients, those you need to buy and those you’ve already bought. When the user interacts with the app, an action mutates the state. Then SwiftUI receives a signal to update the UI with the new state.
Working with Realm
Realm was built to address common problems of today’s apps. It provides many elegant, easy-to-use solutions. And it’s available for multiple platforms, including but not limited to:
- Swift/Objective-C
- Java/Kotlin
- JavaScript
- .NET
The coolest part about Realm is that the skills are transferable. Once you learn the Realm basics in one language, they’re easy to pick up in another language. And because Realm is a cross-platform database, its APIs don’t change much from one language to the next.
Still, Realm is not an all-purpose database. Unlike SQLite, Realm is a NoSQL object database. Like any other NoSQL database, it has advantages and disadvantages. But Realm is a great alternative for keeping multi-platform teams in sync.
Understanding the Realm Database
Before you start setting up Realm, you need to understand a bit about how it works.
Realm uses files to save and manage your database. Each Realm database in your app is called a realm. Your app may have multiple realms, each handling a different domain of objects. That helps keep your database organized and concise in your app. And because it’s available across platforms, you can share pre-loaded Realm files between platforms like iOS and Android. That’s really helpful, right? :]
To open a Realm file, you simply instantiate a new
Realm object. If you don’t pass a custom file path, Realm creates a default.realm file in the Documents folder on iOS.
Sometimes you might want to use a realm without actually writing data on disk. The database provides a handy solution for these situations: in-memory realms. These can be useful when writing unit tests. You can use in-memory realms to pre-load, modify and delete data for each test case without actually writing on disk.
Realm Mobile Database isn’t the only product Realm provides. The company also offers Realm Sync, a solution for synchronizing Realm databases across multiple devices and in the cloud. Additionally, Realm provides a great app to open, edit and manage your databases: Realm Studio.
Setting up Realm
To start using Realm, you must include it as a dependency in your project. There are many dependency management tools you can use for this, such as the Swift Package Manager and CocoaPods. This tutorial uses Swift Package Manager, but feel free to use the tool you’re more comfortable with.
To set up your dependency, select File ▸ Swift Packages ▸ Add Package Dependency…. Copy the following and paste into the combined search/input box:
This is the location of the GitHub repository containing the Realm package. Click Next.
Next, Xcode asks you to define some options for this package. Simply leave the default value of Up to Next Major to use the latest version of Realm. (As of writing this is therefore from 5.4.0, inclusive, to 6.0.0, exclusive.) Click Next.
Finally, select the package products and targets it should add to the project. Select both, Realm and RealmSwift, and click Finish. Xcode downloads the code from the repository and adds the Realm package to the PotionsMasrer target.
Build and run to be sure everything is working.
Now that you have Realm set up, you’re ready to create your first data model.
Defining Your Realm Data Model
To build your ingredient model, add a new Swift file in the Models group and name it IngredientDB.swift. Add the following code:
import RealmSwift // 1 class IngredientDB: Object { // 2 @objc dynamic var id = 0 @objc dynamic var title = "" @objc dynamic var notes = "" @objc dynamic var quantity = 1 @objc dynamic var bought = false // 3 override static func primaryKey() -> String? { "id" } }
Here’s a breakdown of the code you just added:
- First, you define your class, subclassing
Object, Realm’s base class for all data models. You’ll use this class to save your ingredients in Realm.
- Here, you define each
Ingredientproperty that you want Realm to store.
- Finally, you override
primaryKey()to tell Realm which property is the model’s primary key. Realm uses primary keys to enforce uniqueness. A primary key also provides an efficient way to fetch and update data.
That’s it!
You define Realm data models as regular Swift classes. Realm uses these classes to write your data on disk, but there are some restrictions specific to
Object subclasses. Because of it’s cross-platform nature, Realm only supports a limited set of platform-independent property types. Some of those properties are:
- Bool
- Int
- Double
- Float
- String
- Date
- Data
Optional properties have special restrictions. You may declare
String,
Date, and
Data as optional. For the rest, you use the wrapper class
RealmOptional; otherwise, they must have a value.
Each property has the
@objc dynamic keywords. This makes them accessible at runtime via Dynamic Dispatch. Realm uses this Swift and Objective-C feature to create a facade between reading and writing data. When accessing a property, Swift delegates to Realm the responsibility of providing you with the desired data.
Defining Relationships
Realm also supports relationships. You can declare nested objects to create many-to-one relationships. And you can use
List to create many-to-many relationships. When declaring a
List, Realm saves those nested objects together with your data model.
Adding an Initializer
Before moving on, open Ingredient.swift and add the following extension at the bottom of the file:
// MARK: Convenience init extension Ingredient { init(ingredientDB: IngredientDB) { id = ingredientDB.id title = ingredientDB.title notes = ingredientDB.notes bought = ingredientDB.bought quantity = ingredientDB.quantity } }
This extension creates a convenience initializer for mapping
IngredientDB to
Ingredient. You’ll use this later in the project.
Now that you’ve defined your data model, it’s time to add an object to your database.
Adding Objects to the Database
In the ViewModels group, open IngredientStore.swift. Import
RealmSwift by adding the following line at the top of the file:
import RealmSwift
Next, replace the body of
create(title:notes:quantity:) with the following code:
objectWillChange.send()
First, you send a signal to SwiftUI. Because
IngredientStore is an
ObservableObject, SwiftUI subscribes to
objectWillChange and responds to the signal by reloading its view.
Next, add the following code to the method:
do { let realm = try Realm() let ingredientDB = IngredientDB() ingredientDB.id = UUID().hashValue ingredientDB.title = title ingredientDB.notes = notes ingredientDB.quantity = quantity } catch let error { // Handle error print(error.localizedDescription) }
First, create an instance of
Realm by opening the default realm. With it, you can write, read, update and delete objects. Next, create an
IngredientDB object and set its property values from the method’s parameters.
You can instantiate and use Realm data models like any other Swift object. You call those unmanaged objects. That means the database doesn’t know about them yet, and any changes won’t persist. Once you add an object to a realm, it becomes managed by Realm. That means Realm stores the object on disk and keeps tracks of its changes.
Add the model to the realm by adding these few lines to code to the end of the
do block:
try realm.write { realm.add(ingredientDB) }
You start a write transaction by calling
write on the
Realm. Each operation you make on a realm must be inside this write transaction block, including additions, deletions and updates. Inside the transaction, you add the new instance of
IngredientDB to Realm. Realm is now storing the object and tracking its changes, making it a managed object.
Build and run, then go ahead and create an ingredient! Tap New Ingredient, give it a title and tap Save.
But wait, something’s still amiss. You create an ingredient, but nothing happens! It still lists the same ingredients as before.
That’s because
IngredientStore does not fetch ingredients from Realm yet — it’s still using the mock data. You’ll fix this next.
Fetching Objects
Open IngredientStore.swift again, and locate the following:
var ingredients: [Ingredient] = IngredientMock.ingredientsMock var boughtIngredients: [Ingredient] = IngredientMock.boughtIngredientsMock
Replace that code with this:
private var ingredientResults: Results<IngredientDB> private var boughtIngredientResults: Results<IngredientDB>
When fetching objects from Realm, the database returns a
Results type. This type represents a collection of objects retrieved from queries.
Now add the following initializer below the two lines you just added:
// 1 init(realm: Realm) { // 2 ingredientResults = realm.objects(IngredientDB.self) .filter("bought = false") // 3 boughtIngredientResults = realm.objects(IngredientDB.self) .filter("bought = true") }
Here’s what’s going on in the above initializer:
- First, you receive an instance of
Realm. You’ll use this instance to fetch ingredients.
- Next, you fetch ingredients from
realmand filter them with
boughtas
false.
- Then you fetch ingredients from
realmand filter them with
boughtas
true.
Finally, insert the following code after the initializer:
var ingredients: [Ingredient] { ingredientResults.map(Ingredient.init) } var boughtIngredients: [Ingredient] { boughtIngredientResults.map(Ingredient.init) }
These properties turn Realm’s
Result into a regular array. The sample project’s UI uses these computed properties to map the database models to views.
Since
IngredientStore now requires a
Realm in its initializer, you need to provide it. Open ScenceDelegate.swift. After the
import SwiftUI statement, import
RealmSwift by inserting the following:
import RealmSwift
Next, change the code inside
scene(_:willConnectTo:options:) to this:
if let windowScene = scene as? UIWindowScene { do { // 1 let realm = try Realm() let window = UIWindow(windowScene: windowScene) // 2 let contentView = ContentView() .environmentObject(IngredientStore(realm: realm)) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } catch let error { // Handle error fatalError("Failed to open Realm. Error: \(error.localizedDescription)") } }
Here’s what you’re doing:
- You create a new instance of
Realm.
- You instantiate
IngredientStorewith the
Realminstance, and you add it to the
ContentViews environment.
Build and run. Now create an ingredient and see the magic!
Realm works with Live Objects. When you add an ingredient to Realm,
ingredientResults updates automatically without you needed to fetch it each time. SwiftUI receives a signal to update the UI with a new, up-to-date view. Feels like magic, right? Go ahead and create some more ingredients! :]
Now that you can successfully add an ingredient, it’s time to build the functionality to update existing ingredients.
Updating Objects
A key feature of PotionsMaster is the ability to toggle an ingredient to the BOUGHT list. Right now, if you tap the buy button, nothing happens. To fix this, you use Realm to update ingredients on disk.
Toggling Ingredients to BOUGHT
To move an ingredient to the BOUGHT list, you need to update the property value of
bought to
true on disk.
Open IngredientStore.swift and replace the contents of
toggleBought(ingredient:) with the following:
// 1 objectWillChange.send() do { // 2 let realm = try Realm() try realm.write { // 3 realm.create( IngredientDB.self, value: ["id": ingredient.id, "bought": !ingredient.bought], update: .modified) } } catch let error { // Handle error print(error.localizedDescription) }
Here’s what’s happening in this code:
- You send a signal to SwiftUI indicating that the object is about to change.
- You open the default realm.
- You start a new write transaction and call
create(_:value:update:), passing the updated values and the
.modifiedcase. This tells Realm to update the database with the values inside the dictionary. When building the dictionary, you must include the object’s
id. If an object with that
idalready exists, Realm updates it with the new values. Otherwise, Realm creates a new object on disk.
Build and run. Now buy an ingredient by tapping the circular icon on the right of its cell.
When updating
bought, Realm notifies both
ingredientResults and
boughtIngredientResults of this change. The updated ingredient moves to
boughtIngredientResults. And SwiftUI animates the change on the
List! How cool is that? :]
Another way of updating an object is by setting its properties to new values. Again, you do this inside a write transaction. Realm will then update each value on disk.
Updating Other Properties
Now that you know how to update an object, you can use Realm to update other properties just as easily. Change the body of
update(ingredientID:title:notes:quantity:) to the code below:
// 1 objectWillChange.send() do { // 2 let realm = try Realm() try realm.write { // 3 realm.create( IngredientDB.self, value: [ "id": ingredientID, "title": title, "notes": notes, "quantity": quantity ], update: .modified) } } catch let error { // Handle error print(error.localizedDescription) }
Here’s what’s happening in this code:
- Once again, you use
objectWillChangeto send a signal telling SwiftUI to reload the UI.
- You open the default realm.
- You call
create(_:value:update:)inside a write transaction. This call updates the values of the ingredient.
This is similar to the code you added above for buying an ingredient. You call
create(_:value:update:), passing the updated values. Realm updates the values on disk and notifies
ingredientResults of the changes. Then, SwiftUI updates the UI with those changes.
Build and run. Tap an ingredient’s name to open the form again. Edit some fields and tap Update.
Now, all that’s left is deleting ingredients!
Deleting Objects
Tapping the buy button moves an ingredient to the BOUGHT section. But once it’s there you can’t get rid of it. Tapping the trash can icon does nothing.
To fix this, open IngredientStore.swift. Replace the body of
delete(ingredientID:) with the following code:
// 1 objectWillChange.send() // 2 guard let ingredientDB = boughtIngredientResults.first( where: { $0.id == ingredientID }) else { return } do { // 3 let realm = try Realm() try realm.write { // 4 realm.delete(ingredientDB) } } catch let error { // Handle error print(error.localizedDescription) }
Here’s how you delete an ingredient in this code:
- Again, you use
objectWillChangeto send a signal requesting SwiftUI to reload the UI.
- You find the ingredient to delete from
boughtIngredientResults.
- You open the default realm.
- Finally, you call
delete, passing the object you want to delete.
Build and run. Buy an ingredient, and then tap the delete button to remove it from the list.
Adding a New Property to a Realm Object
During development, it’s common for data models to grow and evolve. Property types may change, and you may need to add or remove properties. With Realm, changing your data model is as easy as changing any other Swift class.
In this section, you’ll add a new property to identify your ingredients by color.
Open IngredientDB.swift and add a new property under
bought:
@objc dynamic var colorName = "rw-green"
Next, in Ingredient.swift, add the following property:
var colorName = "rw-green"
You also need to update the initializer to set
colorName. Add the following line at the bottom of the initializer in the file:
colorName = ingredientDB.colorName
In the three lines of code above, you’ve added a property for storing the color name on Realm and for mapping it in the views.
That’s it! The models are ready to store a color name. Next, you’ll update IngredientStore.swift to save this new property in your database.
Storing the New Property in Realm
Open IngredientStore.swift, and locate this code:
func create(title: String, notes: String, quantity: Int) {
Replace it with this:
func create(title: String, notes: String, quantity: Int, colorName: String) {
Now, insert the following line after where you’ve set other properties like the
quantity and
notes:
ingredientDB.colorName = colorName
This adds a new parameter,
colorName, and assigns it to
ingredientDB.
Still in IngredientStore.swift, find this line:
func update(ingredientID: Int, title: String, notes: String, quantity: Int) {
Change it to this:
func update( ingredientID: Int, title: String, notes: String, quantity: Int, colorName: String ) {
Finally, in
update, find this code:
realm.create( IngredientDB.self, value: [ "id": ingredientID, "title": title, "notes": notes, "quantity": quantity ], update: .modified)
Replace it with the following:
realm.create( IngredientDB.self, value: [ "id": ingredientID, "title": title, "notes": notes, "quantity": quantity, "colorName": colorName ], update: .modified)
This code adds a parameter,
colorName, to the update. It adds it to the values dictionary when calling
create(_:value:update:).
Now both the create and the update methods require a
colorName.
But Xcode recognizes that
IngredientFormView does not pass a
colorName when it calls these methods and produces a couple of errors.
To fix this, open IngredientForm.swift. Add the following code just after the property
quantity:
@Published var color = ColorOptions.rayGreen
Now find
init(_:ingredient:) and add the following line at the bottom:
color = ColorOptions(rawValue: ingredient.colorName) ?? .rayGreen
Here you add a property to store the color when the user is creating or updating an ingredient.
Next, open IngredientFormView.swift and find the following code inside
saveIngredient():
store.create( title: form.title, notes: form.notes, quantity: form.quantity)
Replace it with this:
store.create( title: form.title, notes: form.notes, quantity: form.quantity, colorName: form.color.name)
In
updateIngredient(), you need to pass
colorName in the call to
update. To do this, find the following code:
store.update( ingredientID: ingredientID, title: form.title, notes: form.notes, quantity: form.quantity)
Replace it with this:
store.update( ingredientID: ingredientID, title: form.title, notes: form.notes, quantity: form.quantity, colorName: form.color.name)
You’ve now fixed the problem of
IngredientFormView not passing
colorName to
IngredientStore.
Build and run. And you get…
The app crashes! Realm throws a migration error:
Migration is required due to the following errors:. But why is this happening?
Working With Migrations
When your app launches, Realm scans your code for classes with
Object subclasses. When it finds one, it creates a schema for mapping the model to the database.
When you change a data model, there’s a mismatch between the new schema and the one in the database. If that happens, Realm throws an error. You have to tell Realm how to migrate the old schema to the new one. Otherwise, it doesn’t know how to map old objects to the new schema.
Since you added a new property,
colorName, to
IngredientDB, you must create a migration for it.
trueto
deleteRealmIfMigrationNeededwhen you instantiate
Realm.Configuration. That tells Realm that, if it needs to migrate, it should delete its file and create a new one.
Creating a Migration
In the Models group, create a file named RealmMigrator.swift.
Now, add this code to your new file:
import RealmSwift enum RealmMigrator { // 1 static private func migrationBlock( migration: Migration, oldSchemaVersion: UInt64 ) { // 2 if oldSchemaVersion < 1 { // 3 migration .enumerateObjects(ofType: IngredientDB.className()) { _, newObject in newObject?["colorName"] = "rw-green" } } } }
Here's the breakdown:
- You define a migration method. The method receives a migration object and
oldSchemaVersion.
- You check the version of the file-persisted schema to decide which migration to run. Each schema has a version number, starting from zero. In this case, if the old schema is the first one (before you added a new property), run the migration.
- Finally, for each of the old and new
IngredientDBobjects in Realm, you assign a default value to the new property.
Realm uses
migrationBlock to run the migration and update any necessary properties.
At the bottom of
RealmMigrator, add the following new
static method:
static func setDefaultConfiguration() { // 1 let config = Realm.Configuration( schemaVersion: 1, migrationBlock: migrationBlock) // 2 Realm.Configuration.defaultConfiguration = config }
Here's what you're doing in this code:
- You create a new instance of
Realm.Configurationusing your
migrationBlock, and set the current version of the schema to 1.
- You set the new default configuration of Realm.
Finally, in SceneDelegate.swift, call this new method at the top of
scene(_:willConnectTo:options:):
RealmMigrator.setDefaultConfiguration()
Realm uses this configuration to open the default database. When that happens, Realm detects a mismatch between the file-persisted schema and the new schema. It then migrates the changes by running the migration function you just created.
Now build and run again. This time the crash is gone!
You've successfully added a new property to
IngredientDB. And you've taken care of the migration. Now it's time to update the form so the user can choose the color!
Adding a New Field to the Form
Open IngredientFormView.swift and find the comment
// TODO: Insert Picker here. Insert this code below the comment line:
Picker(selection: $form.color, label: Text("Color")) { ForEach(colorOptions, id: \.self) { option in Text(option.title) } }
This adds a new picker view to
IngredientFormView. This picker lets the user choose a color.
Next, open IngredientRow.swift and find the comment
// TODO: Insert Circle view here. Add the following code after the comment:
Circle() .fill(Color(ingredient.colorName)) .frame(width: 12, height: 12)
Here you're adding a circle view to each ingredient row. You fill the circle with the color of that ingredient.
Build and run to see the changes. Now create a new ingredient and select a color for it.
Great job! Now you can go ahead and list all the ingredients you need for that special potion you're brewing. :]
Where to Go From Here
You can download the final project by clicking the Download Materials button at the top or bottom of the tutorial.
In this SwiftUI Realm tutorial, you learned to create, update, fetch, and delete objects from Realm using SwiftUI. In addition to the basics, you also learned about migrations and how to create them.
To learn more about Realm, you can refer to its official documentation. And don't forget to check out our book, Realm: Building Modern Swift Apps with Realm Database.
If you want to learn more about SwiftUI, see our SwiftUI by Tutorials.
I hope you enjoyed this tutorial. If you have any questions or comments, please feel free to join the discussion below. | https://www.raywenderlich.com/12235561-realm-with-swiftui-tutorial-getting-started | CC-MAIN-2021-17 | refinedweb | 4,112 | 51.55 |
An introduction to
pytest and doing test-driven development with Replit
In this tutorial we'll introduce test-driven development and you'll see how to use
pytest to ensure that your code is working as expected.
pytest lets you specify inputs and expected outputs for your functions. It runs each input through your function and validates that the output is correct.
pytest is a Python library and works just like any other Python library: you install it through your package manager and you can import it into your Python code. Tests are written in Python too, so you'll have code testing other code.
Test-driven development or TDD is the practice of writing tests before you write code. You can read more about TDD and why it's popular on Wikipedia.
Specifically you'll:
- See how to structure your project to keep your tests separate but still have them refer to your main code files
- Figure out the requirements for a function that can split a full name into first and last name components
- Write tests for this function
- Write the actual function.
Creating a project structure for
pytest
For large projects, it's useful to keep your testing code separate from your application code. In order for this to work, you'll need your files set up in specific places, and you'll need to create individual Python modules so that you can refer to different parts of the project easily.
Create a new Python repl called
namesplitter. As always, it'll already have a
main.py file, but we're going to put our name splitting function into a different module called
utils, which can house any helper code that our main application relies on. We also want a dedicated place for our tests.
Create two new folders: one called
utils and one called
tests, using the
add folder button. Note that when you press this button it will by default create a folder in your currently active folder, so select the
main.py file after creating the first folder or the second folder will be created inside the first folder.
You want both the folders to be at the root level of your project.
Now add a file at the root level of the project called
__init__.py. This is a special file that indicates to Python that we want our project to be treated as a "module": something that other files can refer to by name and import pieces from. Also add an
__init__.py file inside the
utils folder and the
tests folder. These files will remain empty, but it's important that they exist for our tests to run. Their presence specifies that our main project should be treated as a module and that any code in our
utils and
tests folders should be treated as submodules of the main one.
Finally, create the files where we'll actually write code. Inside the
utils folder create a file called
name_helper.py and inside the
tests folder create one called
test_name_helper.py. Your project should now look as follows. Make sure that you have all the files and folders with exactly these names, in the correct places.
Defining examples for the name split function
Splitting names is useful in many contexts. For example, it is a common requirement when users sign up on websites with their full names and then companies want to send personalised emails addressing users by their first name only. You might think that this is as simple as splitting a name based on spaces as in the following example.
def split_name(name):
first_name, last_name = name.split()
return [first_name, last_name]
print(split_name("John Smith"))
# >>> ["John", "Smith"]
While this does indeed work in many cases, names are surprisingly complicated and it's very common to make mistakes when dealing with them as programmers, as discussed in this classic article. It would be a huge project to try and deal with any name, but let's imagine that you have requirements to deal with the following kinds of names:
- First Last, e.g. John Smith
- First Middle Last, e.g John Patrick Smith (John Patrick taken as first name)
- First Middle Middle Last, e.g. John Patrick Thomson Smith (John Patrick Thomson taken as first name)
- First last last Last, e.g. Johan van der Berg (note the lowercase letters, Johan taken as first name, the rest as last)
- First Middle last last Last, e.g. Johan Patrick van der Berg (note the lowercase letters, Johan taken as first name, the rest as last)
- Last, e.g. Smith (we can assume that if we are given only one name, it is the last name)
Specifically, you can assume that once you find a name starting with a lowercase letter, it signifies the start of a last name, and that all other names starting with a capital letter are part of the first and middle names. Middle names can be combined with first names.
Of course, this does not cover all possibilities, but it is a good starting point in terms of requirements.
Using TDD, we always write failing tests first. The idea is that we should write a test about how some code should behave, check to make sure that it breaks in the way we expect (as the code isn't there). Only then do we write the actual code and check that the tests now pass.
Writing the test cases for our names function
Now that we understand what our function should do, we can write tests to check that it does. In the
tests/test_name_helper.py file, add the following code.
from namesplitter.utils import name_helper
def test_two_names():
assert name_helper.split_name("John Smith") == ["John", "Smith"]
Note that the
namesplitter in the first line is taken from the name of your Replit project, which defines the names of the parent module. If you called your project something else, you'll need to use that name in the import line. It's important to not put special characters in the project name (including a hyphen, so names like
my-tdd-demo are out) or the import won't work.
The
assert keyword simply checks that a specific statement evaluates to
True. In this case, we call our function on the left-hand side and give the expected value on the right-hand side, and ask
assert to check if they are the same.
This is our most basic case: we have two names and we simply split them on the single space. Of course, we haven't written the
split_name function anywhere yet, so we expect this test to fail. Let's check.
Usually you would run your tests by typing
py.test into your terminal, but using Replit things work better if we import
pytest into our code base and run it from there. This is because a) our terminal is always already activated into a Python environment and b) caching gets updated when we press the
Run button, so invoking our tests from outside of this means that they could run on old versions of our code, causing confusion.
Let's run them from our
main.py file for now as we aren't using it for anything else yet. Add the following to this file.
import pytest
pytest.main()
Press the
Run button.
pytest does automatic test discovery so you don't need to tell it which tests to run. It will look for files that start with
test and for functions that start with
test_ and assume these are tests. (You can read more about exactly how test discovery works and can be configured here.)
You should see some scary looking red failures, as shown below. (
pytest uses dividers such as
====== and
------ to format sections and these can get messy if your output pane is too narrow. If things look a bit wonky try making it wider and rerunning.)
If you read the output from the top down you'll see a bunch of different things happened. First,
pytest ran test discovery and found one test. It ran this and it failed so you see the first red
F above the
FAILURES section. That tells us exactly which line of the test failed and how. In this case, it was an
AttributeError as we tried to use
split_name which was not defined. Let's go fix that.
Head over to the
utils/name_helper.py file and add the following code.
def split_name(name):
first_name, last_name = name.split()
return [first_name, last_name]
This is the very simple version we discussed earlier that can only handle two names, but it will solve the name error and TDD is all about small increments. Press
Run to re-run the tests and you should see a far more friendly green output now, as below, indicating that all of our tests passed.
Before fixing our function to handle more complex cases, let's first write the tests and check that they fail. Go back to
tests/test_name_helper.py and add the following four test functions beneath the existing one.
from namesplitter.utils import name_helper
def test_two_names():
assert name_helper.split_name("John Smith") == ["John", "Smith"]
def test_middle_names():
assert name_helper.split_name("John Patrick Smith") == ["John Patrick", "Smith"]
assert name_helper.split_name("John Patrick Thomson Smith") == ["John Patrick Thomson", "Smith"]
def test_surname_prefixes():
assert name_helper.split_name("John van der Berg") == ["John", "van der Berg"]
assert name_helper.split_name("John Patrick van der Berg") == ["John Patrick", "van der Berg"]
def test_split_name_onename():
assert name_helper.split_name("Smith") == ["", "Smith"]
def test_split_name_nonames():
assert name_helper.split_name("") == ["", ""]
Rerun the tests and you should see a lot more output now. If you scroll back up to the most recent
===== test session starts ===== section, it should look as follows.
In the top section, the
.FFFF is shorthand for "five tests were run, the first one passed and the next four failed" (a green dot indicates a pass and a red F indicates a failure). If you had more files with tests in them, you would see a line like this per file, with one character of output per test.
The failures are described in detail after this, but they all amount to variations of the same problem. Our code currently assumes that we will always get exactly two names, so it either has too many or too few values after running
split() on the test examples.
Fixing our
split_name function
Go back to
name_helper.py and modify it to look as follows.
def split_name(name):
names = name.split(" ")
if not name:
return ["", ""]
if len(names) == 1:
return ["", name]
if len(names) == 2:
firstname, lastname = name.split(" ")
return [firstname, lastname]
This should handle the case of zero, one, or two names. Let's run our tests again to see if we've made progress before we handle the more difficult cases. You should get a lot less output now and three green dots, as shown below.
The rest of the output indicates that it's the middle names and surname prefix examples that are still tripping up our function, so let's add the code we need to fix those. Another important aspect of TDD is keeping your functions as small as possible so that they are easier to understand, test, and reuse, so let's write a second function to handle the three or more names cases.
Add the new function called
split_name_three_plus() and add an
else clause to the existing
split_name function where you call this new function. The entire file should now look as follows.
def split_name_three_plus(names):
first_names = []
last_names = []
for i, name in enumerate(names):
if i == len(names) - 1:
last_names.append(name)
elif name[0].islower():
last_names.extend(names[i:])
break
else:
first_names.append(name)
first_name = " ".join(first_names)
last_name = " ".join(last_names)
return [first_name, last_name]
def split_name(name):
names = name.split(" ")
if not name:
return ["", ""]
if len(names) == 1:
return ["", name]
if len(names) == 2:
firstname, lastname = name.split(" ")
return [firstname, lastname]
else:
return split_name_three_plus(names)
The new function works by always appending names to the
first_names list until it gets to the last name, or until it encounters a name that starts with a lowercase letter, at which point it adds all of the remaining names to
last_names list. If you run the tests again, they should all pass now.
The tests were already helpful in making sure that we understood the problem and that our function worked for specific examples. If we had made any off-by-one mistakes in our code that deals with three or more names, our tests would have caught them. If we need to refactor or change our code in future, we can also use our tests to make sure that our new code doesn't introduce any regressions (where fixing problems causes code to break on other examples that worked before the fix.)
Using our function
Let's build a very basic application to use our function. Replace the testing code in
main.py with the following.
from utils import name_helper
name = input("Please enter your full name: ")
first_name, last_name = name_helper.split_name(name)
print(f"Your first name is: {first_name}")
print(f"Your last name is: {last_name}")
If you run this, it will prompt the user for their name and then display their first and last name.
Because you're using the
main.py file now, you can also invoke
pytest directly from the output console on the right by typing
import pytest; pytest.main(). Note that updates to your code are only properly applied when you press the
Run button though, so make sure to run your code between changes before running the tests.
Make it your own
We've written a name splitter that can handle some names more complicated than just "John Smith". It's not perfect though: for example, if you put in a name with two consecutive spaces it will crash our program. You could fork the project and fix this by first writing a test with consecutive spaces and then modifying the code to handle this (and any other edge cases you can think of).
Where next
You've learned to do TDD in this project. It's a popular style of programming, but it's not for everyone. Even if you decide not to use TDD, having tests is still very useful and it's not uncommon for large projects to have thousands or millions of tests.
Take a look at the big list of naughty strings for a project that collects inputs that often cause software to break. You could also read How SQLite Is Tested which explains how SQLite, a popular lightweight database, has 150 thousand lines of code and nearly 100 million(!) lines of tests.
In the next tutorial, we'll show you how to become a Replit poweruser by taking advantage of the productivity features it offers. | https://docs.replit.com/tutorials/test-driven-development | CC-MAIN-2022-27 | refinedweb | 2,470 | 71.24 |
pci_write_config8
pci_write_config8()
Write bytes to the configuration space of a PCI device
Synopsis:
#include <hw/pci.h> int pci_write_config8( unsigned bus, unsigned dev_func, unsigned offset, unsigned count, char* buff );
Arguments:
- bus
- The bus number.
- dev_func
- The device or function ID. The device number is in bits 7 through 3, and the function number in bits 2 through 0.
- offset
- The register offset into the configuration space, in the range [0...255].
- count
- The number of bytes to write.
- buff
- A pointer to a buffer containing the data to be written into the configuration space.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:
The pci_write_config8() function writes individual bytes to the configuration space of the specified device.
Returns:
- PCI_BAD_REGISTER_NUMBER
- An invalid offset register number was given.
- PCI_BUFFER_TOO_SMALL
- The size argument is greater than 100 bytes.
-16(), pci_read_config32(), pci_rescan_bus(), pci_write_config(), pci_write_config16(), pci_write_config32() | http://www.qnx.com/developers/docs/6.3.2/neutrino/lib_ref/p/pci_write_config8.html | CC-MAIN-2013-20 | refinedweb | 153 | 51.34 |
. Many databases can natively store, index, and query spatial data. Common scenarios include querying for objects within a given distance, and testing if a polygon contains a given location. EF Core 2.2 now supports working with spatial data from various databases using types from the NetTopologySuite (NTS) library.
Spatial data support is implemented as a series of provider-specific extension packages. Each of these packages contributes mappings for NTS types and methods, and the corresponding spatial types and functions in the database. Such provider extensions are now available for SQL Server, SQLite, and PostgreSQL (from the Npgsql project). Spatial types can be used directly with the EF Core in-memory provider without additional extensions.
Once the provider extension is installed, you can enable it in your DbContext calling the UseNetTopologySuite method. For example, using SQL Server:()); } }
You can then start adding properties of supported types to your entities. For example:
using NetTopologySuite.Geometries; namespace MyApp { public class Friend { [Key] public string Name { get; set; } [Required] public Point Location { get; set; } } }
You can then persist entities with spatial data:
using (var context = new MyDbContext()) { context.Add( new Friend { Name = "Bill", Location = new Point(-122.34877, 47.6233355) {SRID = 4326 } }); context.SaveChanges(); }
And you can execute database queries based on spatial data and operations:
var nearestFriends = (from f in context.Friends orderby f.Location.Distance(myLocation) descending select f).Take(5).ToList();
For more information on this feature, see the spatial data documentation.
Collections of owned entities
EF Core 2.0 added the ability to model ownership in one-to-one associations. EF Core 2.2 extends the ability to express ownership to one-to-many associations. Ownership helps constrain how entities are used.
For example, owned entities: – Can only ever appear on navigation properties of other entity types. – Are automatically loaded, and can only be tracked by a DbContext alongside their owner.
In relational databases, owned collections are mapped to separate tables from the owner, just like regular one-to-many associations. But in document-oriented databases, we plan to nest owned entities (in owned collections or references) within the same document as the owner.
You can use the feature by calling the new OwnsMany() API:
modelBuilder.Entity<Customer>().OwnsMany(c => c.Addresses);
For more information, see the updated owned entities documentation.
Query tags
This feature simplifies the correlation of LINQ queries in code with generated SQL queries captured in logs.
To take advantage of query tags, you annotate a LINQ query using the new TagWith() method. Using the spatial query from a previous example:
var nearestFriends = (from f in context.Friends.TagWith(@"This is my spatial query!") orderby f.Location.Distance(myLocation) descending select f).Take(5).ToList();
This LINQ query will produce the following SQL output:
-- This is my spatial query! SELECT TOP(@__p_1) [f].[Name], [f].[Location] FROM [Friends] AS [f] ORDER BY [f].[Location].STDistance(@__myLocation_0) DESC
For more information, see the query tags documentation.
Getting EF Core 2.2
The EF Core NuGet packages are available on the NuGet Gallery, and also as part of ASP.NET Core 2.2 and the new .NET Core SDK.
If you want to use EF Core in an application based on ASP.NET Core, we recommend that first you upgrade your application to ASP.NET Core 2.2.
In general, the best way to use EF Core in an application is to install the corresponding NuGet package for the provider your application will use. For example, to add the 2.2 version of the SQL Server provider in a .NET Core project from the command line, use:
$ dotnet add package Microsoft.EntityFrameworkCore.SqlServer -v 2.2.0
Or from the Package Manager Console in Visual Studio:
PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 2.2.0
For more information on how to add EF Core to your projects, see our documentation on Installing Entity Framework Core.
Compatibility with EF Core 2.1
We spent much time and effort making sure that EF Core 2.2 is backwards compatible with existing EF Core 2.1 providers, and that updating an application to build on EF Core 2.2 won’t cause compatibility issues. We expect most upgrades to be smooth, however if you find any unexpected issues, please report them to our issue tracker.
There is one known change in EF Core 2.2 that could require minor updates in application code. Read the description of the following issue for more details:
- #13986 Type configured as both owned entity and regular entity requires a primary key to be defined after upgrading from 2.1 to 2.2
We intend to maintain a list of issues that may require adjustments to existing code on our issue tracker.
What’s next: EF Core 3.0
With EF Core 2.2 out the door, our main focus is now EF Core 3.0. We haven’t completed any new features yet, so the EF Core 3.0 Preview 1 packages available on the NuGet Gallery today only contain minor changes made since EF Core 2.2.
In fact, there are several details of the next major release still under discussion, and we plan to share more information in upcoming announcements, but here are some of the themes we know about so far:
- LINQ improvements: LINQ enables you to write database queries without leaving your language of choice, taking advantage of rich type information to get IntelliSense and compile-time type checking. But LINQ also enables you to write an unlimited number of complicated queries, and that has always been a huge challenge for LINQ providers. In the first few versions of EF Core, we solved that in part by figuring out what portions of a query could be translated to SQL, and then by allowing the rest of the query to execute in memory on the client. This client-side execution can be desirable in some situations, but in many other cases it can result in inefficient queries that may not identified until an application is deployed to production..
- Cosmos DB support: We’re working on a Cosmos DB provider for EF Core, to enable will enable most EF Core features, like automatic change tracking, LINQ, and value conversions, against the SQL API in Cosmos DB. We started this effort before EF Core 2.2, and we have made some preview versions of the provider available. The new plan is to continue developing the provider alongside EF Core 3.0.
- C# 8.0 support: We want our customers to take advantage some of the new features coming in C# 8.0 like async streams (including await for each) and nullable reference types while using EF Core.
- Reverse engineering database views into query types: In EF Core 2.1, we added support for query types, which can represent data that can be read from the database, but cannot be updated. Query types are a great fit for mapping database views, so in EF Core 3.0, we would like to automate the creation of query types for database views.
- Property bag entities:. This feature is a stepping stone to support many-to-many relationships without a join entity, which is one of the most requested improvements for EF Core.
- EF 6.3 on .NET Core:.
Thank you
The EF team would like to thank everyone for all the community feedback and contributions that went into EF Core 2.2. Once more, you can report any new issues you find on our issue tracker.
Good morning Diego, We are intending to start a project using EF Core, in this project we use inheritance and EF Core only has support for TPH. Do you know how long the inheritance will be available for TPT and TPC?
Thank you!
Hello Bruno,
We don’t have an ETA for TPT or TPC support. They are not in the plan for the 3.0 release, and they require a lot of infraestructure changes to be implemented. In the meantime the best way to map tables that are structured like TPT is to use composition instead of inheritnace (e.g. a base Person can have Student data and Employee data associated with it) and for mapping tables that are structured like TPC to have a common based type that is not mapped in the model (each concrete type can be mapped to its own table and EF Core will not reason about the inheritance hierarchy; you write explicit in-memory union queries across mutliple entity types in the hierachy).
To track movent on this features, you can subscribe to issues and.
I created a WebAPI in ASP.NET Core as well as ASP.NET Framework 4.7 but I couldn’t find the EFCore dll in the bin folder. I found out that EFCore is already in the .Net Core 2.2 but you didn’t mention whether it’s in the .Net Framework 4.7. Is it available in .Net Framework 4.7? | https://devblogs.microsoft.com/dotnet/announcing-entity-framework-core-2-2/ | CC-MAIN-2022-27 | refinedweb | 1,495 | 66.64 |
Nmap Development
mailing list archives
On Thu, Aug 15, 2013 at 12:10:48AM +0200, Jacek Wielemborek wrote:
First of all, I found the cause behind the segfault I experienced
during our last meeting. Accidentally, when trying to fix your ROT13
script, I added a redundant super:send before the return
rot13(super:send()) thing. This made the second call not get anything,
because we just flushed the buffer and we're not in a blocking mode.
This made it return EAGAIN, but because I did no error checking, I
tried to do something like memcmp(dst,src,-1).
Once I added the checks, I noticed that an extra ncat_recv_raw call
returning with EAGAIN makes us quit from the read_socket() loop and,
as an effect, close the socket. The reason is that so far we assumed
that socket returning on select() has some data to read, so we call
ncat_recv and if it yields nothing despite the select() signalling
data, the connection must have broken. It's not true anymore and
that's why I changed all ncat_recv calls to check errno for EAGAIN
before they consider a return value of 0 to be an error.
There were two issues left: I had to somehow pass the ncat_recv_raw's
value to differentiate between the disconnection and just EAGAIN and
solve the problem of user returning "", which makes Lua code set
buffer length to zero (rightly so), and zero return value from
ncat_recv meant a connection closed. In this case, I manually change
errno to EAGAIN, so that the ncat_recv callers can notice that.
I do not like this abuse of EAGAIN. It sounds as though you are trying
to handle too many layers at once.
You should try inverting your abstractions. If ncat_recv returns the
string result of possibly many layers of Lua filters, that indeed makes
it hard to test whether the socket is closed. So don't do that. When you
find that a socket is closed (through a zero-byte read), all you need to
do is report it to the next layer up, and only in that one place. The
Lua code in the next layer is now responsible for doing something
intelligent with the error. You should read about how sockets work in
NSE:
When a socket read fails, you want to return (nil, err) to the caller.
You are almost certainly going to have to define a new function at the
top level that understands those Lua return values and transforms them
into something useful for the C caller. You probably will not be able to
use a zero-byte string as a close signal at this level.
In other words, you might want to have ncat_recv at the bottom of your
abstraction layers, not at the top.
If you are having trouble with when to call a C function and when to
call a Lua function, define a minimal Lua socket interface that just
passes its data through verbatim, and always make that Lua function the
thing you call from C. That way you can standardize your return
handling.
BTW, is this the kind of mail I should have CC'ed to dev () nmap org? If
so, please CC the answer there as well.
David Fifield
_______________________________________________
Sent through the dev mailing list
Archived at
By Date
By Thread | http://seclists.org/nmap-dev/2013/q3/354 | CC-MAIN-2014-41 | refinedweb | 556 | 66.47 |
Red Hat Bugzilla – Bug 90106
Clicking 'Probe Videocard' button many times moves monitor listing
Last modified: 2007-04-18 12:53:26 EDT
From Bugzilla Helper:
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2.1) Gecko/20030225
Description of problem:
Version-Release number of selected component (if applicable):
redhat-config-xfree86-0.7.3-2
How reproducible:
Always
Steps to Reproduce:
1. Run redhat-config-xfree86
2. Select Advanced tab on Video Card subarea select Configure...
3. You'll see 'Video card setting' window appear.
4. Click many times 'Probe Videocard' button, see how list of monitors moves to
left. See screenshots.
Additional info:
Created attachment 91477 [details]
Before clicking 'Probe Videocard'
Created attachment 91478 [details]
After clicking 'Probe Videocard' few times
After looking into this, the bug is not with redhat-config-xfree86. The bug
appears to be in the scroll_to_cell() function in gtkTreeView. I'm filing this
against pygtk2, but the actual bug may be in gtk2.
Calling scroll_to_cell on a tree that is too wide for the viewport will cause
the tree start scrolling horizontally a few pixels at a time.
Below is a sample program to demonstrate the behavior. Start clicking the
'clickme' button and watch the tree start moving horizontally, even though the
col_align float value is set to '0.0':
#!/usr/bin/python2.2
import signal
import gtk
import gobject
if __name__ == "__main__":
signal.signal (signal.SIGINT, signal.SIG_DFL)
def clicked(button, store, view, col, iter):
path = store.get_path(iter)
view.set_cursor(path, col, gtk.FALSE)
view.scroll_to_cell(path, col, gtk.TRUE, 0.5, 0.0)
view.grab_focus()
win = gtk.Window()
win.set_size_request(100, 150)
box = gtk.VBox()
store = gtk.ListStore(gobject.TYPE_STRING)
view = gtk.TreeView()
view.set_model(store)
col = gtk.TreeViewColumn(None, gtk.CellRendererText(), text =0)
view.append_column(col)
iter = store.append()
store.set_value(iter, 0, "123456789123456789123456789")
button = gtk.Button("clickme")
button.connect("clicked", clicked, store, view, col, iter)
box.pack_start(view)
box.pack_start(button)
win.add(box)
win.show_all()
gtk.mainloop()
I have filed a new bug (#91845) that addresses the scroll_to_cell() bug more
directly. I'm reassigning this bug back to redhat-config-xfree86.
I just reworked the redhat-config-xfree86 UI so that this bug isn't a problem to
the user anymore. The bug in pygtk2 (or gtk2) still exists, but see bug #91845
for more info on that.
Closing as Rawhide since future versions will have a different UI. | https://bugzilla.redhat.com/show_bug.cgi?id=90106 | CC-MAIN-2016-50 | refinedweb | 407 | 52.66 |
Susy3 Configuration
Susy3 has 4 core settings, in a single settings map. You’ll notice a few differences from Susy2:
Columns no longer accept a single number, like
12,
but use a syntax more similar to the new
CSS grid-template-columns –
a list of relative sizes for each column on the grid.
Unitless numbers in Susy act very similar to
fr units in CSS,
and the
susy-repeat() function (similar to the css
repeat())
helps quickly establish equal-width columns.
susy-repeat(12)will create 12 fluid, equal-width columns
susy-repeat(6, 120px)will create 6 equal
120px-wide columns
120px susy-repeat(4) 120pxwill create 6 columns, the first and last are
120px, while the middle 4 are equal fractions of the remainder. Susy will output
calc()values in order to achieve this.
Gutters haven’t changed –
a single fraction or explicit width –
but the
calc() output feature
means you can now use any combination of units and fractions
to create static-gutters on a fluid grid, etc.
Spread existed in the Susy2 API as a span option, and was otherwise handled behind the scenes. Now we’re giving you full control over all spread issues. You can find a more detailed explanation of spread on the blog.
You can access your global settings at any time
with the
susy-settings() function,
or grab a single setting from the global scope
with
susy-get('columns'),
susy-get('gutters') etc.
Related
Article: Understanding Spread in Susy3 [external]
@function susy-get()
$susy (Map)
$susy: () !default;
The grid is defined in a single map variable,
with four initial properties:
columns,
gutters,
spread and
container-spread.
Anything you put in the root
$susy variable map
will be treated as a global project default.
You can create similar configuration maps
under different variable names,
to override the defaults as-needed.
Since
3.0.0-beta.1:
columns setting no longer accepts numbers
(e.g.
12) for symmetrical fluid grids,
or the initial
12 x 120px syntax for
symmetrical fixed-unit grids.
Use
susy-repeat(12) or
susy-repeat(12, 120px) instead.
Map Properties
columns: (list)
Columns are described by a list of numbers,
representing the relative width of each column.
The syntax is a simplified version of CSS native
grid-template-columns,
expecting a list of grid-column widths.
Unitless numbers create fractional fluid columns
(similar to the CSS-native
fr unit),
while length values (united numbers)
are used to define static columns.
You can mix-and match units and fractions,
to create a mixed grid.
Susy will generate
calc() values when necessary,
to make all your units work together.
Use the
susy-repeat($count, $value) function
to more easily repetative columns,
similar to the CSS-native
repeat().
susy-repeat(8): an 8-column, symmetrical, fluid grid.
Identical to
(1 1 1 1 1 1 1 1).
susy-repeat(6, 8em): a 6-column, symmetrical, em-based grid.
Identical to
(8em 8em 8em 8em 8em 8em).
(300px susy-repeat(4) 300px): a 6-column, asymmetrical, mixed fluid/static grid using
calc()output.
Identical to
(300px 1 1 1 1 300px).
NOTE that
12 is no longer a valid 12-column grid definition,
and you must list all the columns individually
(or by using the
susy-repeat() function).
gutters: (number)
Gutters are defined as a single width,
or fluid ratio, similar to the native-CSS
grid-column-gap syntax.
Similar to columns,
gutters can use any valid CSS length unit,
or unitless numbers to define a relative fraction.
0.5: a fluid gutter, half the size of a single-fraction column.
1em: a static gutter,
1emwide.
Mix static gutters with fluid columns, or vice versa,
and Susy will generate the required
calc() to make it work.
spread: narrow (string)
Spread of an element across adjacent gutters:
either
narrow (none),
wide (one), or
wider (two)
- Both spread settings default to
narrow, the most common use-case. A
narrowspread only has gutters between columns (one less gutter than columns). This is how all css-native grids work, and most margin-based grid systems.
- A
widespread includes the same number of gutters as columns, spanning across a single side-gutter. This is how most padding-based grid systems often work, and is also useful for pushing and pulling elements into place.
- The rare
widerspread includes gutters on both sides of the column-span (one more gutters than columns).
container-spread: narrow (string)
Spread of a container around adjacent gutters:
either
narrow (none),
wide (one), or
wider (two).
See
spread property for details.
Examples
// 4 symmetrical, fluid columns // gutters are 1/4 the size of a column // elements span 1 less gutter than columns // containers span 1 less gutter as well $susy: ( 'columns': susy-repeat(4), 'gutters': 0.25, 'spread': 'narrow', 'container-spread': 'narrow', );
// 6 symmetrical, fluid columns… // gutters are static, triggering calc()… // elements span equal columns & gutters… // containers span equal columns & gutters… $susy: ( 'columns': susy-repeat(6), 'gutters': 0.5em, 'spread': 'wide', 'container-spread': 'wide', );
Related
Spread examples on CodePen [external]
$_susy-defaults [private]
@function susy-repeat()
Used By
@function susy-repeat()
Similar to the
repeat(<count>, <value>) function
that is available in native CSS Grid templates,
the
susy-repeat() function helps generate repetative layouts
by repeating any value a given number of times.
Where Susy previously allowed
8 as a column definition
for 8 equal columns, you should now use
susy-repeat(8).
Parameters & Return
$count: (integer)
The number of repetitions, e.g.
12 for a 12-column grid.
$value: 1 (*)
The value to be repeated.
Technically any value can be repeated here,
but the function exists to repeat column-width descriptions:
e.g. the default
1 for single-fraction fluid columns,
5em for a static column,
or even
5em 120px if you are alternating column widths.
@return (list)
List of repeated values
Examples
// 12 column grid, with 5em columns $susy: ( columns: susy-repeat(12, 5em), );
// asymmetrical 5-column grid $susy: ( columns: 20px susy-repeat(3, 100px) 20px, ); /* result: #{susy-get('columns')} */
/* result: 20px 100px 100px 100px 20px */
Used By
@function susy-normalize-columns()
@function susy-settings()
Return a combined map of Susy settings,
based on the factory defaults (
$_susy-defaults),
user-defined project configuration (
$susy),
and any local overrides required –
such as a configuration map passed into a function.
Parameters & Return
$overrides…: (maps)
Optional map override of global configuration settings.
See
$susy above for properties.
@return (map)
Combined map of Susy configuration settings,
in order of specificity:
any
$overrides...,
then
$susy project settings,
and finally the
$_susy-defaults
Examples
@each $key, $value in susy-settings() { /* #{$key}: #{$value} */ }
/* columns: 1 1 1 1 */ /* gutters: 0.25 */ /* spread: narrow */ /* container-spread: narrow */
$local: ('columns': 1 2 3 5 8); @each $key, $value in susy-settings($local) { /* #{$key}: #{$value} */ }
/* columns: 1 2 3 5 8 */ /* gutters: 0.25 */ /* spread: narrow */ /* container-spread: narrow */
Used By
@function susy-normalize-columns()
@function susy-get()
@function susy-compile()
@function susy-get()
Return the current global value of any Susy setting
Parameters & Return
$key: (string)
Setting to retrieve from the configuration.
@return (*)
Value mapped to
$key in the configuration maps,
in order of specificity:
$susy, then
$_susy-defaults
Example
/* columns: #{susy-get('columns')} */ /* gutters: #{susy-get('gutters')} */
/* columns: 1 1 1 1 */ /* gutters: 0.25 */ | https://www.oddbird.net/susy/docs/config | CC-MAIN-2022-27 | refinedweb | 1,204 | 53.21 |
#include <mlRuntime.h>
It manages a dictionary of runtime types, it can create and remove runtime types. This class contains only static components and must be initialized with init() and destroyed with destroy().
Thread-safety: This class is not thread-safe and should only be used from the main thread. The same applies to the initClass() method of classes derived from the ml::Base class.
Definition at line 47 of file mlRuntime.h.
Returns a global badtype instance of
RuntimeType.
Creates a new (runtime)type, representing a class with parent class name
parentName, typename
name and a callback function
callback to create an instance of this class.
The callback may be NULL for abstract types. The type is inserted into the runtime dictionary to be accessible later. When inserting, it is tested whether a same named type exists and if it existed, this function returns NULL because same named types are not supported by the runtime type system. Also an error is send with ML_PRINT_ERROR(). Notifies MLNotify on valid insertion. See mlMLNotify.h for more infos.
Destroys runtime type dictionary.
Deletes all RuntimeTypes from the runtime dictionary which belong to the the dll with name
dllName.
This call is ignored if no types are found or a NULL name is passed as
dllName.
Destroys a dictionary entry with a given
name.
Nothing is done if type is not found. Notifies
notify. See
mlMLNotify.h for more infos.
Returns the (runtime)type of a class given by its
name using the runtime type dictionary.
NULL is returned if no runtime type with
name is found.
Returns a list of all runtime types derived from
parentType.
The returned list will be empty if no type is found or if
parentType is NULL. If
onlyFromDifferentDlls is
false (the default), all derived types are added; if it is
true, only types with differing dllNames are added. If
dllNames strings are not set, empty or different then the types are considered from different dlls.
Returns the first runtime type entry in dictionary.
Returns the next runtime entry in dictionary (or NULL if none).
Returns the name of the most recently loaded dll.
Returns NULL if no dll has been loaded.
Initializes runtime type dictionary.
Initializes a new type and tests for double init call.
classType is the still uninitialized pointer to the badType() runtime type instance.
parentName is the string name of the parent class type.
classPrefix is the string name of a prefix which will be added as prefix before
className.
className is the string name of the class type itself and
createCB is the callback to create an instance of the type. For abstract types it may be NULL. All strings must be null-terminated or - if permitted - NULL. Return value is the initialized runtime type on success;
classType if type is already initialized,
badType() if same type name already exists.
Sets the
name of the most recently loaded dll.
Clears name if NULL is passed. Only to be called from the ML! | http://www.mevislab.de/fileadmin/docs/current/MeVisLab/Resources/Documentation/Publish/SDK/ToolBoxReference/classml_1_1Runtime.html | crawl-003 | refinedweb | 500 | 67.76 |
#include <stdio.h> int ungetc(int c, FILE *stream);
The ungetc () function pushes the byte specified by c (converted to an unsigned char) back onto the input stream pointed to by stream. The pushed-back bytes will be returned by subsequent reads on that stream in the reverse order of their pushing. A successful intervening call (with the stream pointed to by stream) to a file-positioning function ( fseek(3C), fsetpos(3C) or rewind(3C)) discards any pushed-back bytes for the stream. The external storage corresponding to the stream is unchanged.
Four bytes of push-back are guaranteed. If ungetc() is called too many times on the same stream without an intervening read or file-positioning operation on that stream, the operation may fail.
If the value of c equals that of the macro EOF, the operation fails and the input stream is unchanged.
A successful call to ungetc() clears the end-of-file indicator for the stream. The value of the file-position indicator for the stream after reading or discarding all pushed-back bytes will be the same as it was before the bytes were pushed back. The file-position indicator is decremented by each successful call to ungetc(); if its value was 0 before a call, its value is indeterminate after the call.
Upon successful completion, ungetc() returns the byte pushed back after conversion. Otherwise it returns EOF.
No errors are defined.
See attributes(5) for descriptions of the following attributes:
read(2), Intro(3), __fsetlocking(3C), fseek(3C), fsetpos(3C), getc(3C), setbuf(3C), stdio(3C), attributes(5), standards(5) | http://docs.oracle.com/cd/E36784_01/html/E36874/ungetc-3c.html | CC-MAIN-2016-22 | refinedweb | 265 | 62.58 |
18.1.1.
The central class in the
Message class,
imported from the:
- class
The constructor takes no arguments.
as_string([unixfrom])¶
Return the entire message flattened as a string. When optional unixfrom is
True, the envelope header is included in the returned string. unixfrom defaults to
False.instance and use its
flatten()method directly. For example:
from cStringIO import StringIO from email.generator import Generator fp = StringIO() g = Generator(fp, mangle_from_=False, maxheaderlen=60) g.flatten(msg) text = fp.getvalue()
is_multipart()¶
Return
Trueif the message’s payload is a list of sub-
Messageobjects, otherwise return
False. When
is_multipart()returns
False, the payload should be a string object..
get_payload([i[, decode]], or if the payload has bogus base64 data, the payload is returned as-is (undecoded). If the message is a multipart and the decode flag is
True, then
Noneis returned. The default for decode is
False.
set_payload(payload[, charset])¶
Set the entire message object’s payload to payload. It is the client’s responsibility to ensure the payload invariants. Optional charset sets the message’s default character set; see
set_charset()for details.
Changed in version 2.2.2: charset argument added..
get_charset()¶
Return the
Charsetinstance.
__contains__(name)¶
Return true if.
has_key(name)¶
Return true if the message contains a header field named name, otherwise return false.
get(name[, failobj])¶
Return the value of the named header field. This is identical to
__getitem__()except that optional failobj is returned if the named header is missing (defaults to
None).
Here are some additional useful methods:
get_all(name[, failobj] must.
New in version 2.2.2..
get_content_maintype()¶
Return the message’s main content type. This is the maintype part of the string returned by
get_content_type().
New in version 2.2.2.
get_content_subtype()¶
Return the message’s sub-content type. This is the subtype part of the string returned by
get_content_type().
New in version 2.2.2.
get_default_type()¶
Return the default content type. Most messages have a default content type of text/plain, except for messages that are subparts of multipart/digest containers. Such subparts have a default content type of message/rfc822.
New in version 2.2.2.
set_default_type(ctype)¶
Set the default content type. ctype should either be text/plain or message/rfc822, although this is not enforced. The default content type is not stored in the Content-Type header.
New in version 2.2.2.
get_params([failobj[, header[, unquote]]].
get_param(param[, failobj[, header[, unquote]]].
Changed in version 2.2.2: unquote argument added, and 3-tuple return value possible.
set_param(param, value[, header[, requote[, charset[, language]]]].
del_param(param[, header[, requote]])¶_type(type[, header][, requote].
get_filename([failobj].
New in version 2.2.2.
get_charsets([failobj].
defects¶
The defects attribute contains a list of all the problems found when parsing this message. See
New in version 2.4. | https://docs.python.org/2/library/email.message.html | CC-MAIN-2017-17 | refinedweb | 465 | 54.49 |
C Program to generate random numbers. Random Numbers are numbers which are produced by a process and its outcome is unpredictable.The function srand() is used to seed the random sequence. The rand() function shall compute a sequence of pseudo-random integers in the range [0, {RAND_MAX}] with a period of at least 2^32.
Read more about C Programming Language .
Read more about C Programming Language .
/***********************************************************
* You can use all the programs on
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit
* and browse!
*
* Happy Coding
***********************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main() {
int i, num;
printf("Enter how many random numbers you want?n");
scanf("%d", &num);
//The function srand() is used to seed the random sequence.
//srand() will generate a specific "random" sequence over and over again.
srand(time(NULL));
//The rand() function shall compute a sequence of pseudo-random
//integers in the range [0, {RAND_MAX}] with a period of at least 2^32.
for (i = 0; i < num; i++) {
printf("random_number[%d]= %dn", i + 1, rand());
}
printf("A number between 0 and 99: %dn", rand() % 100);
printf("A number between 0 and 9: %dn", rand() % 10);
return 0;
}) | https://c-program-example.com/2011/10/c-program-to-generate-random-numbers.html | CC-MAIN-2020-40 | refinedweb | 210 | 67.65 |
Hi all,
I'm using x86_64-w64-mingw32-gcc-4.7.2-release-win64_rubenvb.7z on Windows 7 x64. I need to work with large arrays (>2GB) and read/write them to a disk. When I try to write an array using std::ofstream::write(), it never returns if the block size (the second argument) is more than 2GB. Here's a test program to reproduce the bug. The file is created, but the assertion is never executed:
#include <cstddef> #include <cassert> #include <fstream> int main() { const std::size_t size = 3000000000ULL; // ~3GB char *data = new char[size]; std::ofstream ofs("test.tmp", std::ios_base::out | std::ios_base::binary); ofs.write(data, size); assert(false); return 0; }
Any suggestions on how to fix it? Maybe I should try another version of mingw? I read the following on the main page:
Version 3.0 (Currently in trunk and considered unstable) has some LFS64 support that allow traditional Unix programs to use 64-bit large file support if they so choose.
Is that related to my problem? | http://sourceforge.net/p/mingw-w64/discussion/723797/thread/7364f2d9/ | CC-MAIN-2016-07 | refinedweb | 174 | 67.55 |
Java AWT Package Example
will learn how to create Button on frame
the topic of Java AWT package...
This program shows you how to create a frame in java AWT package... to create Radio Button on the frame.
The java AWT , top-level window
Radio Button In Java
;
Introduction
In this section, you will learn how to create Radio
Button on the frame. The
java AWT , top-level window, are represent by the CheckBoxGroup... how to create
and show the Checkboxgroup component on the frame.
In this program
Job scheduling in Java
project, we have to develop a feature of Job scheduling.. for example i have to create... of all please explain me what is job scheduling in Java and how one can use this feature in their application.
Example of Java job scheduling will really work
Swing Button Example
Swing Button Example Hi,
How to create an example of Swing button in Java?
Thanks
Hi,
Check the example at How to Create Button on Frame?.
Java Frame/ Applet /swing/awt
Java Frame/ Applet /swing/awt I have produced a .exe file with the help of .jar file...................
Now How can I Protect my software( .exe ) file bulid in Java from being Copy and Paste....?????????
please reply
java job
java job How to get Java Job very easily in java
awt in java using awt in java gui programming how to false the maximization property of a frame
Java AWT
Java AWT How can the Checkbox class be used to create a radio button
job portal - Java Beginners
job portal 1)for creating the job portals which is better?(jsp/html).
2)how we done the validations?give me an example.
Hi friend,
This is JavaScript validation code.
registration form in jsp Dialogs - Swing AWT
/springlayout.html Dialogs a) I wish to design a frame whose layout mimics... visit the following links:
Button Pressing Example
Button Pressing Example
...
C:\newprgrm>java ButtonPressDemo
Good Morning clicked
Good Day clicked
C:\newprgrm>
Download this example
awt
Java AWT Applet example how to display data using JDBC in awt/applet
awt - Swing AWT
,
For solving the problem visit to :
Thanks... market chart this code made using "AWT" . in this chart one textbox when user - Swing AWT
java how can i link up these two interfaces ie CurrentAccount...
import java.awt.FlowLayout; // specifies how components are arranged... plainJButton; // button with just text
// TextFieldFrame constructor adds
Removing the Title Bar of a Frame
bar of a frame
or window in java. That means show the frame or window without... button, maximize button and close button with the title
of the frame...
Removing the Title Bar of a Frame
how to set image in button using swing? - Swing AWT
how to set image in button using swing? how to set the image in button using swing? Hi friend,
import java.awt.*;
import...://
Thanks
HOW TO BECOME A GOOD PROGRAMMER
HOW TO BECOME A GOOD PROGRAMMER I want to know how to become good programmer
Hi Friend,
Please go through the following link... learn java easily and make a command over core java to proceed further.
Good tutorials for beginners in Java
in details about good tutorials for beginners in Java with example?
Thanks.
Hi, want to be command over Java, you should go on the link and follow...Good tutorials for beginners in Java Hi, I am beginners in Java
creating browse button - Java Beginners
creating browse button how can we create a browse button along with a textfield in java swings. Hi friend,
import... on Java visit to :
Thanks
Job scheduling with Quartz - Java Server Faces Questions
Job scheduling with Quartz I have an JSF application deployed... to database. It works fine but when the Quartz scheduler fires a job it accquires... while initialization or while calling the job. Hi,How save data - Swing AWT
to :
Thanks...How to save data Hi,
I have a problem about how to save data...
then in jList or or Jtable many data viewer in one button,then another button must - Swing AWT
Java Implementing Swing with Servlet How can i implement the swing with servlet in Java? Can anyone give an Example??
Implementing... {
JFrame frame = new JFrame("Frame in Java Swing");
frame.setSize(400, 400
JList - Swing AWT
() {
//Create and set up the window.
JFrame frame = new JFrame("Single list...JList May i know how to add single items to JList. What is the method for that? You kindly explain with an example. Expecting solution as early
how to create frame in swings
how to create frame in swings how to create frame in swings
What is AWT in java
What is AWT in java
....
Button
This class used to create a label button
Convas.../api/java/awt/package-summary.html
button in java
button in java how can i compare names of two buttons after...) {
System.out.println("button clicked");
}
}
Thanks
Hi.... i haven't learned that part yet,just a beginner.I'm using simple awt components
another frame by using awt or swings
another frame by using awt or swings how to connect one frame to another frame by using awt or swings
java-swings - Swing AWT
java-swings How to move JLabel using Mouse?
Here the problem is i...://
Thanks.
Amardeep... frame = new JFrame("mouse motion event program
Java Swing Create LinkButton
Java Swing Create LinkButton
You all are aware of JButtons, JRadioButtons... are going to create a Link
Button that will allow you to move to another page...://");
JFrame frame = new JFrame("Link
Java - Swing AWT
("Paint example frame") ;
getContentPane().add(new JPaintPanel.... How can I run an application of Microsoft Windows like notepad
Create a JRadioButton Component in Java
Create a JRadioButton Component in Java
In this section, you will learn how to create a radio
button in java swing. Radio Button is like check box. Differences between check
Download Quartz Job Scheduler
project in Eclipse
Run the eclipse IDE and create new java project. From the file... and click on
the "Finish" button to create the project. A new project... Download Quartz Job Scheduler
java - Swing AWT
[]=new TextField [4];
Label l[]=new Label [4];
Button but=new Button("Create Account");
Button but1=new Button("Test Account...*;
import javax.swing.*;
class Maruge extends Frame implements ActionListener
java awt components - Java Beginners
java awt components how to make the the button being active at a time..?
ie two or more buttons gets activated by click at a time
how display jsp frame - Java Beginners
how display jsp frame Hi all,
I am creating two jsp in frame...
Create User
Manage User... in another frame,you have to use target attribute of tag in your footer.jsp.
java - Swing AWT
JPasswordField(15);
SUBMIT=new JButton("Login");
ADD=new JButton("Create Account...("FORM");
}
public static void main(String arg[]) {
LoginDemo frame=new...("Address");
label6=new JLabel("Phone No");
button=new JButton("Save
job
job i know siwing,and awt very well,and i also develop project in swing,can u suggest me any online job in swing,or and full time job in swing the Frame in Java
how to display the frame or window without title bar in
java. This type of the frame is mostly used to show the splash screen at starting of the application... Removing the title bar of the Frame in Java
Help Required - Swing AWT
createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("password example in java");
frame.setDefaultCloseOperation...();
}
});
}
}
-------------------------------
Read for more information.
To Create a Frame with Preferences
To Create a Frame with Preferences
In this section you will learn how to
use the preferences in frame. The example will make it easier to
understand to use the preferences
JFileChooser - Swing AWT
directory one by one...........can any one plzzzz assist me how to read the sub... ActionListener {
JButton button;
JFileChooser chooser;
String choosertitle;
public FileChooser(){
button = new JButton("Click me
How to create charts in Java?
How to create charts in Java? Is there any example of creating charts and graphs in Java?
thanks
Hi,
check the tutorial: Chart & Graphs Tutorials in Java
java-awt - Java Beginners
java-awt how to include picture stored on my machine to a java frame...());
JFrame frame = new JFrame();
frame.getContentPane().add(panel... information,
Thanks
AWT basics
good GUI for windows applications.
Here are the links to AWT Tutorials:
AWT
AWT
documentation
AWT example
AWT manual
AWT tutorial...AWT basics
Are you looking for the AWT Basics to help you learn AWT quickly
JTable - Cell selection - Swing AWT
information.
Thanks.
Amardeep...JTable - Cell selection How to select a cell of a JTable when I clicked a button? Hi friend,
import java.awt.*;
import
Drag and Drop components from one frame to another frame
button etc.) from one
frame to another frame. In this code we have used... Drag and Drop components from one frame to another frame
Java code given below shows
How to create LineDraw In Java
How to create LineDraw In Java
...
will learn how to create Line Drawing. This program implements a line Drawing
component. A java program explains the stroke line i.e. how to make thick
Java Frame
Java Frame What is the difference between a Window and a Frame with title free hand writing
frame with title free hand writing create frame with title free hand writing, when we drag the mouse the path of mouse pointer must draw line ao arc...:// how to use JTray in java
give the answer with demonstration or example
please | http://www.roseindia.net/tutorialhelp/comment/97786 | CC-MAIN-2014-52 | refinedweb | 1,585 | 65.01 |
You can click on the Google or Yahoo buttons to sign-in with these identity providers,
or you just type your identity uri and click on the little login button.
skip wrote...
given
class A(object):
def methA(self):
raise NotImplementedError("implement methA in subclass")
class B(A):
def methB(self):
raise NotImplementedError("implement methB in subclass")
class C(B):
def methA(self):
print "methA"
def methB(self):
print "methB"
pylint (v 0.14.0, astng 0.17.2, common 0.28.2) complains that B doesn't
provide a definition of methA even though it is itself both a base class for
other classes and defines an unimplemented methB class (both making it a
candidate abstract class). Seems that pylint should recognize on one count
or both that B doesn't need to provide a definition for methA.
version published
Ticket #5975 - latest update on 2010/08/26, created on 2008/09/12 by Sylvain Thenault | https://www.logilab.org/ticket/5975 | CC-MAIN-2021-43 | refinedweb | 157 | 60.35 |
Web service issue over GPRS
- lundi 23 mai 2005 07:50Hi,
I'm developing my first Pocket PC application in C# in VS 2003. It's a cut down version of a desktop application I've been developing in VB6 for a few years now. It makes a call to a web service which is out on the internet. It's all gone really well until now.
I'm running/testing the application on a HP IPAQ hx2400. If I access the internet over broadband via my office wireless network the application works perfectly. However if I access the internet over GPRS via the bluetooth modem and my mobile phone on Orange the following happens:
1. The first call to the web service, which returns a DataSet, works fine.
2. The next and all subsequent calls to the web service returns the following error:
"Server found request context type to be 'text/html', but expected 'text/xml'."
3. At this point if I call:
I get the following error:
"The remote server returned an error: (400) Bad Request."
4. At this point, if I repeat step 3 it succeeds and I can make one more successful web service call as in step 1. Then I go through step 2 and at step 3 and with all subsequent calls to the web service I get the following error:
"The operation has timed-out."
If I jump back to step 1 after step 3 I get the following error:
"The operation has timed-out."
It's as if my application "falls off" the internet, even though at all times I can still browse the internet from Pocket Internet Explorer, including the .asmx file for my web service, just fine.
If I restart the application the same pattern repeats. Needless to say I need some help.
Best Regards,
Craig Harrison
Toutes les réponses
- lundi 23 mai 2005 20:07Hi,
I don't know why this is happening but you can try manually setting the content type of the web request before you call GetResponse.
httpWebRequest.ContentType = "text/xml";
This forces the content type everytime a web service call is made.
I'll have to try to reproduce this issue on my on hardware.
Travis
- lundi 23 mai 2005 20:45Hi,
I'm calling the web service in the following way:
I'm only using 'httpWebRequest' as a means of hitting the internet in another way from my application to get a bit more information about the state of the connection, etc.
I've discovered that if I pause at step 2 for an hour or so, after calling the web service and then calling again and getting the error, I can make another successful call to the web service but then the error returns again on the next call.
I've spoken to the data people at my mobile network provider and they suggested it could be a 'caching' issue??? Whether that happens on the device or the web server I don't know.
Please let me know if you have any other ideas.
Best Regards,
Craig Harrison
- lundi 23 mai 2005 20:45
Hi Craig,
Can you get a network trace of the web service calls? As for the connectivity issues after the Abort/Timeout, it is a known issue that NETCF are not releasing the connection properly in cases of an abort/timeout. We have fixed this in V2. Can you try NETCF V2 Beta 2 to see if that resolves your issue? For V1, you can try setting ServicePointManager.DefaultConnectionLimit to a large value, although connection might still be lost when the limit has been reached.
Cheers,
Anthony
- mardi 24 mai 2005 05:52Hi Anthony,
I've looked into getting a network trace but I haven't been successful yet.
I have ordered VS 2005 Beta 2 so that I can try it out.
Can 'ServicePointManager' be used when calling a web service using the method shown in my last post?
Best Regards,
Craig Harrison
- mardi 24 mai 2005 15:16You can use SoapExtension to trace the SOAP calls. MSDN has an excellent trace extension example with source code. Just look for SoapExtension class. It's very powerful and allows you to get access to incoming and outgoing messages.
You will need to get to the reference.cs source code that was automatically generated for the webreference. Once it is generated, you can modify the code to your needs. Such as adding a SoapExtension or getting access to the HttpWebRequest.
To get access to the reference.cs in the IDE, go to the Solution Explorer, click on the Web References folder and select Show All Files icon at the top of Solution Explorer. Under reference.map you will find the reference.cs file. You can modify the web proxy, recompile and your changes will be used.
To add the TraceExtension class from MSDN to your web proxy, just add the attribute [TraceExtension] to the method you want to use the SoapExtension.
To get access to the underlying HttpWebRequest object in the reference.cs. You can use the example code below. Just override the GetWebRequest method from the SoapHttpClientProtocol class.
protected override System.Net.WebRequest GetWebRequest(System.Uri uri)
{
System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest) base.GetWebRequest(uri);
webRequest.ContentType = "text/xml";
return webRequest;
}Let me know if you want source code example and I can send you a CS project that uses the TraceExtension.
Travis
- mardi 24 mai 2005 18:05Hi Craig,
ServicePointManager.DefaultConnectionLimit is a static property so you can call it anywhere in your program. Just remember to set it before you make a web service call.
Cheers,
Anthony
- mardi 24 mai 2005 19:42Hi Travis,
I would like to implement your suggestion regarding 'GetWebRequest' but I've discovered that I have NETCF Version 1.0.2268.0 installed in 'D:\Program Files\Microsoft Visual Studio .NET 2003\CompactFrameworkSDK\v1.0.5000\Windows CE' on my development machine and I need SP 1 or later (Version 1.0.3111.0) to be able to override 'GetWebRequest'. The problem I have is I just can't work out how to install it (duh!). I have installed SP3 on my device but I don't know how to update my development machine. Can you help?
Regarding TraceExtension, I would like to see a code sample if you can send it to me.
Best Regards,
Craig Harrison
- mardi 24 mai 2005 19:44Hi Anthony,
I've tried setting 'ServicePointManager.DefaultConnectionLimit' to a high value (99999) before calling the web service but the problem persists.
Thanks,
Craig Harrison
- mardi 24 mai 2005 22:34Hi Craig,
No problem. VS uses reflection against the cf.NET assemblies in the ' \Program Files\Microsoft Visual Studio .NET 2003\CompactFrameworkSDK\v1.0.5000\Windows CE' directory to build your solution.
The hard way to get them is to pull the assemblies out of the .CAB files. Unfortunately they are named funky and not easy to determine the required names.
The easy way is to install the latest cf.NET CAB onto your device and then use ActiveSync to browse to the Windows directory on the device. You'll see the needed DLL files (12 files). They will all start with the name "GAC_" (the poor mans assembly cache :) Copy these files to your hard drive somewhere. Rename the files by removing the "GAC_", the version info, and the "cneutral" in the names. Just name them to their correct namespace. These files can then be dropped in the VS directory from above. Once VS is started up, it will use these new files when you build a Smart Device project.
One thing to remember, make sure Windows Explorer is set to show hidden files and show file extensions. These are system files and are not displayed by default.
If you want VS to deploy the correct cf.NET CAB file to the device you're using, put the new CAB file under the "C:\Program Files\Microsoft Visual Studio .NET 2003\CompactFrameworkSDK\v1.0.5000\Windows CE\wce400" directory using the correct processor folder for your device. i.e. \armv4 will deploy to my HP4705
Let me know where you want me to email the example project with the trace extension. Send me an email at info@travisfeirtag.com and I'll reply.
Hope this helps...
Travis
- mercredi 25 mai 2005 07:43Hi Travis,
I followed your instructions and got the latest NETCF files on to my development machine. I managed to override 'GetWebRequest' and set 'ContextType = "text/xml"' as per your code above, however the problem persists.
When you send me the trace extension project I'll see what the trace turns up.
Best Regards,
Craig Harrison
- samedi 6 août 2005 21:55Hi Craig,
I've spent fighting with gprs data sending issues more than one year, and found that you can be never sure in the result because of the gprs network.
As you want to send some data to the server and want to be sure it's there by waiting for the response that simply diappears somewhere on the way back, you simpliy need to send it again and again till you got the answer back.
As you use sql server on the server side that writes your data into a table, just let it write there more times, and simply extend your table with two fields:
- one filed a status bit that let's you sign the given row as 'expired'
- another field to store a unique id for the transaction, that can be generated on the pocketpc by using its id and the timestamp of your first trial.
A simple insert trigger can set the status flags of previously sent datarows, or can delete those that have been sent more times.
So:
Your pocketPC can be notified a later time by one of the trials you made and had luck.
On the other hand you surely have your data on server side and only once, so you can work with it safely.
A sending problem can be solved with this 'server side caching' - as you can implememt all important data sending communcation steps in one web service call's dataset.
Hope this helps you.
br
Attila
- vendredi 19 août 2005 14:20Hi,
I had almost exactly the same problem. 'ServicePointManager.DefaultConnectionLimit' seems to be set to 2 by default. I set it to 100 and my app works now. | http://social.msdn.microsoft.com/Forums/fr-FR/netfxcompact/thread/af16183e-d40c-4693-8ea8-1ef34fc52c42 | CC-MAIN-2013-20 | refinedweb | 1,738 | 64 |
You can subscribe to this list here.
Showing
9
results of 9
Użytkownik Stephen Evans napisał:
>.
>
>
I already modified VersionInfo.py and build_exe.py package source files,
just added 'languageid' parameter/attribute, and now I can pass
languageid="080904B0" with my target.
But I think, that package developers should do this for all of us.
I can publish patches for this feature if someone is interested in.
--
Regards
Jacek Kałucki
Python 2.7
py2exe0.6.9
Hello, I got this error message when I run this setup.py ():
The following modules appear to be missing
['demo', 'filepath']
Everything works fine if I run the same command in the package directory,
still I would like to know why exactly I get this message since the two
modules are loaded properly by __init__ and "seen" by py2exe if they are in
its same directory. I guess it looks for modules in ./ only, but is there a
way to kindly ask py2exe to look for modules in the package directory?
Would'nt that make more sense since distutils behaves exactly like this? I
also like to keep the setup and ddls outside the package, so this really
mess up my directory structure.
Thanks for reading.
On 31/10/2010 14:27, Jacek Kałucki wrote:
> Hi.
>
> Currently, VS_VERSIONINFO has hardcoded language information.
> Could developers to add 'language' parameter to the Version class, please?
>
Jacek,.
Stephen
n.b. 'internal_name' is also missing from add_versioninfo() in
build_exe.py for 0.6.9, easily added.
Hi.
Currently, VS_VERSIONINFO has hardcoded language information.
Could developers to add 'language' parameter to the Version class, please?
--
Regards
Jacek Kałucki
I should add that that I already have the Microsoft Visual C++ 2008
Redistributable Package (vcredist_x86.exe) installed on my system so
why is it crashing? :(
Zach
<>< ><>
On Sun, Oct 31, 2010 at 8:01 AM, Zachary Uram <netrek@...> wrote:
>
<>< ><>
The pygame app I am trying to convert with py2exe uses a script to
start the game:
start-game:
#!/usr/bin/python
import netrek
netrek.main()
So to run the app you type "python start-game".
The app's python source files are in the directory "netrek" and the
script is one level above it. So it goes into the netrek directory and
checks each .py source file
until it finds function main() then it runs it.
This is why it's been so confusing trying to get this app to work with
py2exe. I tried telling my py2exe setup script that my starting script
is "__init__.py" - this contains the function main() - but when I run
the .exe it builds nothing happens, no window opens and there is no
console output. I think py2exe is expecting that the app is started by
running __init__.pyc (it creates __init__.exe) but this is not the
case. If you run "python __init__.py" the app will not load. You must
run the script to get it working. So is it possible to get this app
working with py2exe and if so how?
You can download the source files here:
Just unpack and the Python source files will be in directory "netrek".
If anyone can get this working I'd really appreciate getting a copy of
the py2exe setup script you use. I've spent hours on this.
Zach
<>< ><>
I was able to build my pygame app using py2exe (Windows 7), but when I
go to run the .exe file in my dist directory it complains about not
finding my imports.
First it complains about socket, then pygame, then ctypes, then pygame.locals
For example the __init__.exe.log says:
Traceback (most recent call last):
File "__init__.py", line 131, in <module>
ImportError: No module named socket
Line 131 says: import sys, time, socket, errno, select, struct,
pygame, math, ctypes
My py2exe build script is in the same directory as my python source
files so I don't see what's the problem.
My main python module is __init__.py and when I run my python program
there are no errors and it works so the problem must be with the
py2exe build script.
Can someone take a look at my script and tell me what I'm doing wrong?
Here is thefile('freesansbold.ttf', 'dist/freesansbold.ttf')
from glob import glob
data_files = [("Microsoft.VC90.CRT", glob(r'c:\dev\ms-vc-runtime\*.*'))]
setup(
data_files=data_files
)
"""
Each entry in pv_modules corresponds to one of my Python source files
(__init__.py, cache.py, client.py etc...).
Zach
<>< ><>
Hi,
Running into some problems.
I'm using the following in Windows 7:
py2exe-0.6.9.win64-py2.6.amd64.exe
pygame-1.9.2pre.win-amd64-py2.6.exe
python-2.6.amd64.msi
Here is the relevant output from py2exe:
The following modules appear to be missing
['AppKit', 'Foundation', 'Numeric', 'OpenGL.GL', 'copyreg',
'dummy.Process', 'email.Generator', 'email.Iterators', 'numpy',
'pkg_resources', 'queue', 'winreg','pygame.sdlmain_os.
OLEAUT32.dll - C:\Windows\system32\OLEAUT32.dll
USER32.dll - C:\Windows\system32\USER32.dll
SHELL32.dll - C:\Windows\system32\SHELL32.dll
KERNEL32.dll - C:\Windows\system32\KERNEL32.dll
WINMM.dll - C:\Windows\system32\WINMM.dll
WSOCK32.dll - C:\Windows\system32\WSOCK32.dll
ADVAPI32.dll - C:\Windows\system32\ADVAPI32.dll
WS2_32.dll - C:\Windows\system32\WS2_32.dll
GDI32.dll - C:\Windows\system32\GDI32.dll
ole32.dll - C:\Windows\system32\ole32.dll
I notice it lists a bunch of modules it could not find. Is this normal
for a pygame app or do I need to add something to my py2exe build
script? I've pasted it at the bottom. Also there are a bunch of DLLs
it says are required. Do I just copy these over into the directory
where my python source files are and py2exe will automatically include
them? Also what is the legality of doing this?
Here is my py2exetree('data', 'dist/data')
shutil.copyfile('freesansbold.ttf', 'dist/freesansbold.ttf')
Zach
<>< ><> | http://sourceforge.net/p/py2exe/mailman/py2exe-users/?viewmonth=201010&viewday=31 | CC-MAIN-2016-07 | refinedweb | 974 | 67.86 |
Visual Studio for Devices.Virtual Machines. Search Engines.
Blogging from the India Development Center
I had known about the LINQ project for some time now but I hadn't really realized the true power that LINQ brings to .Net until I watched the PDC keynote where Anders and Don and the rest took a lap around LINQ and all the other cool new shiny stuff. What's not immediately evident is all the things that you can do with LINQ. One of the samples that ships with the techpreview has a Prolog
Being the nosey little parker I am, I *had* to find out how this thing worked on the inside, take it apart and look at its innards.
To side-track for a bit here, I see a lot of blogs talking about LINQ as if it is a C#-only thing - it isn't. It is a '.Net' thing and frankly, I'm thinking of calling myself a VB programmer now after looking at all the cool new things in Vb 9.0. Scott Swigart managed a scoop and has an awesome interview with Paul Vick and Amanda on Visual Basic and where it is headed.
Let's dig down and get dirty with LINQ. One disclaimer - I don't work on the C# team and this post comes from an evening spent looking for the IL generated for my newbie LINQ programs.
I'm going to take a modified version of the program that Don and Anders used in their keynote
var query = from p in Process.GetProcesses() where p.Threads.Count > 5 orderby p.Threads.Count descending select new { Name = p.ProcessName, Threads = p.Threads.Count };
foreach(var proc in query) Console.WriteLine(" {0} {1}", proc.Name, proc.Threads);
This spits out all processes which have greater than 5 threads and sorts them by threadcount. [1]
I disassembled this using Reflector. The IL generated (or rather, the amount of magic the compiler is doing) is enough to leave you mentally scarred if you're not Don Box, so I'll spare you the trauma and show you the equivalent C# code.
if (Program.<>9__CachedAnonymousMethodDelegate7 == null) { Program.<>9__CachedAnonymousMethodDelegate7 = new Func<Process, bool>(Program.<Main>b__0); }
if (Program.<>9__CachedAnonymousMethodDelegate8 == null) { Program.<>9__CachedAnonymousMethodDelegate8 = new Func<Process, int>(Program.<Main>b__2); }
if (Program.<>9__CachedAnonymousMethodDelegate9 == null) { Program.<>9__CachedAnonymousMethodDelegate9 = new Func<Process, Program.<Projection>f__4>(Program.<Main>b__3); }
IEnumerable<Program.<Projection>f__4> enumerable1 =
Sequence.Select<Process, Program.<Projection>f__4>( Sequence.OrderByDescending<Process, int> (Sequence.Where<Process>(Process.GetProcesses(), Program.<>9__CachedAnonymousMethodDelegate7) ,Program.<>9__CachedAnonymousMethodDelegate8), Program.<>9__CachedAnonymousMethodDelegate9);
using (IEnumerator<Program.<Projection>f__4> enumerator1 = ((IEnumerator<Program.<Projection>f__4>) enumerable1.GetEnumerator()))
{ while (enumerator1.MoveNext()) { Program.<Projection>f__4 f__1 = enumerator1.get_Current(); Console.WriteLine(" {0} {1}", f__1.Name, f__1.Threads); } }
Doesn't look very friendly, does it? But right of, you can notice several oddities. What are all those <Projection> and f__4s and b__2s that the compiler is sneaking in? There lies the true magic of Linq.
The C# compiler generating types for language features is not something new - in fact, that is how anonymous delegates are implemented in C# 2.0 (the gory details of which you can find out here).
First off, a few anonymous delegates are created. These correspond to the threads count check, the new object creation and the threads count property - and they're used inside the select query later.
We then run into the hero of the entire show - the Program.<Projection>f__4. This guy is nothing but an 'anonymous type'. When we said new {Name =...} , we created a new type without specifying the name of the type. This type has 2 properties - a Name and a ThreadsCount.
The first clause that executes is the 'where p.Threads.Count> 5'. In IL, this is actually represented through a compiler-generated static method of the Program class
[CompilerGenerated]
private static bool <Main>b__0(Process p)
{
return (p.Threads.Count > 5);
}
(Sequence.Where<Process>(Process.GetProcesses(), Program.<>9__CachedAnonymousMethodDelegate7) actually executes this function (the cached anonymous delegates just wraps around the static method above. We then orderby descending using another static function which tells us *what* to order by (in this case, the threads.Count property).
We now have a list of processes which meet our criteria - we now need to spin up a new object of type Program.<Projection>f__4 for each Process object. This f_4 type has only 2 properties - Name and Threads. To package each Process object into a f__4 object, we use a compiler generated static function
[CompilerGenerated]
private static Program.<Projection>f__4 <Main>b__3(Process p)
{
Program.<Projection>f__4 f__1 = new Program.<Projection>f__4();
f__1.Name = p.ProcessName;
f__1.Threads = p.Threads.Count;
return f__1;
}
Since Sequence.Select returns a handy-dandy enumerator, we can now use that to iterate over our f__4 objects and print them out to the console.
This just scratches the surface of what Linq can do and the contortions the C# compiler goes through to make this magic work. With lambda functions, anonymous types , type inference and a whole galaxy of mouth-watering features, querying is just one aspect of what's new in .Net land :-)
Notes:
1. In case you are curious, svchost had the most number of threads on my machine at 78
PingBack from
PingBack from
PingBack from | http://blogs.msdn.com/sriram/archive/2005/09/16/468927.aspx | crawl-002 | refinedweb | 875 | 51.24 |
sqlalchemy - not as difficult as I thought just to get started
I had tried using sqlalchemy before but found it hard just to get started. I watched a YouTube video today link that made it a lot easier just to get started. Below I posted some code to write the pytz time zone strings to a SQLite table. Then query to see if a particular tz string is in the table. Not saying this is complete or the best way to do it. But if you have had problems getting going as I have in the past, this may help to get past that feeling. The video basically follows the example in the documentation, but a little easy to follow in my mind.
Anyway, it seems like if you want to use a database ORM these days, sqlalchemy looks like it is at the top of the list for many developers. Just from what I read and listen to.
Also sqlalchemy is shipped with Pythonista
import sqlalchemy import pytz print('sqlalchemy Version {}'.format(sqlalchemy.__version__ )) cnn_str = 'sqlite:///:memory:' # uncomment the below to write a file instead of memory #cnn_str = 'sqlite:///pytz_strings.db' from sqlalchemy import create_engine # below can set echo to True, but a lot of console output engine = create_engine(cnn_str, echo=False) from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker class TzNames(Base): __tablename__ = 'tz' id = Column(Integer, primary_key=True) tz_name = Column(String) def __repr__(self): return "<TzNames(tz_name='%s'" % (self.tz_name) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() for tz in pytz.all_timezones: tz_names = TzNames(tz_name=tz) session.add(tz_names) session.commit() query_str = 'US/Pacific' if session.query(TzNames).filter(TzNames.tz_name == query_str).first(): print('{}, was found in database...'.format(query_str)) else: print('{}, was not found in database...'.format(query_str)) print('Number of tz records = {}'.format(session.query(TzNames).count())) | https://forum.omz-software.com/topic/4171/sqlalchemy-not-as-difficult-as-i-thought-just-to-get-started | CC-MAIN-2020-50 | refinedweb | 316 | 57.77 |
Format page
for printing
Andrew wrote:
> Yes it is allowed, but you should be aware of the
> implications of this:
> If the semaphore blocks, then none of the other epicsTimers
> that use the same epicsTimerQueue will be executed until the
semaphore is released
> and the callback/notify routine returns. It is not advisable for a
> timer on the system shared timer queue to block for any signficant
> period of time in its callback/notify routine. The use of
> printf() and similar functions is fine though because it should not
block for any
> significant period of time.
I don't think I agree with the statement that printf() should not block
for any significant period of time.
On vxWorks printf() does block, and since the I/O is often going to a
9600 baud console port, it can be very slow. In fact if the user types
^S to pause the output the task will hang until ^Q is typed.
Here's a little test program that measures how many clock ticks are
required to use printf() to print 100 output lines:
corvette> more printf_test.c
#include <tickLib.h>
#include <stdio.h>
void printf_test()
{
int i;
long int start;
start = tickGet();
for (i=0; i<100; i++) printf("This is line %d\n", i);
printf("Total ticks=%ld\n", tickGet()-start);
}
Here's the output under normal circumstances:
ioc13lab> printf_test
This is line 0
This is line 1
This is line 2
This is line 3
...
This is line 96
This is line 97
This is line 98
This is line 99
Total ticks=72
value = 15 = 0xf
So it took 72 clock ticks, or over 1 second.
If I press ^S for a while during the output, the task hangs while that
is going on, and I got 546 clock ticks while I waited about 10 seconds.
So I don't think it's a good idea to call printf in a callback routine.
epicsPrintf() is much better, since it just puts output in a buffer, and
does not wait for the actual I/O to complete.
Mark | http://www.aps.anl.gov/epics/tech-talk/2006/msg00044.php | CC-MAIN-2017-51 | refinedweb | 348 | 73.1 |
Gonzalo García takes a crack at why webpack (not capitalized like npm) exists at all. No particular disagreements here, but here’s my crack at it…
- We use webpack because we need to
import stuff from place;. This is a good pattern. We can use webpack to interpret those statements, as native support for them isn’t what it needs to be yet, and it’s not clear whether the native version will be smart for performance or not (probably not, at the scope of projects webpack is usually used for).
- We use webpack because we know we need to concatenate and compress our JavaScript anyway, and managing load order isn’t something you wanna handle manually.
- We use webpack because of npm. Powerful features are a
yarnor
npm iaway and so our projects are loaded with stuff to
import.
- We use webpack because we’re sure it performs fancy magic that results in good performance-related things for our websites. We cross our fingers we have that right, and we’ve done our part right.
- We use webpack because there is a hive mind in this industry and it leads to a lot of us hopping on the trains with the most people on them, and people are hanging out of the windows of the webpack train.
I’m very very (very) far from being a webpack expert, but I essentially get it, especially after the screencast Sean Larkin and I did right here, and I know enough my projects benefit from it. | https://css-tricks.com/why-would-i-use-a-webpack/ | CC-MAIN-2022-05 | refinedweb | 254 | 65.66 |
30 June 2010 13:31 [Source: ICIS news]
LONDON (ICIS news)--Neste Oil has sold its Portuguese unit, Neste Oil ?xml:namespace>
The divestment would have a minor positive impact on Neste Oil's second-quarter earnings, the company said.
Neste Oil
"This divestment allows Neste Oil to focus on its strategic priorities. Repsol is in a natural position to develop the ETBE site as an integrated part of their Sines petrochemical site," said Matti Lehmus, Neste Oil’s executive vice president, oil products.
Repsol Polimeros is owned by integrated global oil and gas company, Repsol YPF.
For more on Repsol YPF | http://www.icis.com/Articles/2010/06/30/9372606/neste-oil-sells-portugal-unit-to-repsol-polimeros.html | CC-MAIN-2015-22 | refinedweb | 102 | 63.7 |
Changelog for package gazebo_ros
2.5.19 (2019-06-04)
Add output arg to launch files, plus some small fixes (
#905
) * Add output arg to empty_world * add output arg to elevator_world * add output arg to range_world * don't set use_sim_time in range_world Instead parse it to empty world, where it will be set. * add xml prolog to all launch files * Remove unnecessary arg in range_world.launch
Contributors: Matthijs van der Burgh
2.5.18 (2019-01-23)
Fix typo exist -> exists (
#833
)
Fix issue
#198
(
#823
)
Contributors: Daniel Ingram, Jack Liu, Steven Peters
2.5.17 (2018-06-07)
2.5.16 (2018-06-04)
Use generic SIGINT parameter in kill command for gazebo script (kinetic-devel) (
#723
) * Use generic SIGINT parameter in kill command for gazebo script * redirect to kill command to std_err
strip comments from parsed urdf (
#695
) Remove comments from urdf before trying to find packages. Otherwise non-existant packages will produce a fatal error, even though they are not used.
Merge pull request
#672
from ros-simulation/gzclient_verbose Pass verbose argument to gzclient
Merge pull request
#670
from ros-simulation/add_ros_api_plugin_to_gzclient Load the libgazebo_ros_api_plugin when starting gzclient
Pass verbose argument to gzclient
Load the libgazebo_ros_api_plugin when starting gzclient so that the ROS event loop will turn over, which is required when you have a client-side Gazebo plugin that uses ROS.
Contributors: Brian Gerkey, Jose Luis Rivero, Steven Peters, azhural, chapulina
2.5.15 (2018-02-12)
Fix last gazebo8 warnings! (
#658
)
Fix for relative frame errors (
#605
)
Fix gazebo8 warnings part 10: ifdefs for GetModel, GetEntity, Light (
#656
)
gazebo8 warnings: ifdefs for Get.*Vel() (
#653
)
Prevents GAZEBO_MODEL_DATABASE_URI from being overwritten (
#644
)
Fix gazebo8 warnings part 7: ifdef's for Joint::GetAngle and some cleanup (
#642
)
Contributors: Hamza Merzić, R, Steven Peters
2.5.14 (2017-12-11)
for gazebo8+, call functions without Get (
#639
)
Fix gazebo8 warnings part 5: ignition math in gazebo_ros (
#635
)
Fix gazebo8 warnings part 4: convert remaining local variables in plugins to ign-math (
#633
)
gazebo_ros: fix support for python3 (
#622
)
gazebo_ros_api_plugin: improve plugin xml parsing (
#625
)
Replace Events::Disconnect* with pointer reset (
#623
)
Install spawn_model using catkin_install_python (
#621
)
[gazebo_ros] don't overwrite parameter "use_sim_time" (
#606
) * Parameter /use_sim_time is only set if not present on Parameter Server
Contributors: Jose Luis Rivero, Manuel Ilg, Mike Purvis, Nils Rokita, Steven Peters
2.5.13 (2017-06-24)
Quote arguments to echo in libcommon.sh (
#590
)
Add catkin package(s) to provide the default version of Gazebo (
#571
) * Added catkin package gazebo_dev which provides the cmake config of the installed Gazebo version
Contributors: Jose Luis Rivero, daewok
2.5.12 (2017-04-25)
2.5.11 (2017-04-18)
Changed the spawn model methods to spawn also lights. (
#5:
.
Use correct logerr method (
#557
)
Contributors: Alessandro Ambrosano, Dave Coleman, Gary Servin.
Contributors: Jose Luis Rivero
2.5.9 (2017-02-20)
Fix gazebo catkin warning, cleanup CMakeLists (
#537
)
Namespace console output (
#543
)
Removed all trailing whitespace
Contributors: Dave Coleman
2.5.8 (2016-12-06)
Workaround to support gazebo and ROS arguments in the command line
Fix ROS remapping by reverting "Remove ROS remapping arguments from gazebo_ros launch scripts.
Fixed getlinkstate service's angular velocity return
Honor GAZEBO_MASTER_URI in gzserver and gzclient
Contributors: Jared, Jon Binney, Jordan Liviero, Jose Luis Rivero, Martin Pecka
2.5.7 (2016-06-10)
2.5.6 (2016-04-28)
Remove deprecated spawn_gazebo_model service
Contributors: Steven Peters
2.5.5 (2016-04-27)
merge indigo, jade to kinetic-devel
Upgrade to gazebo 7 and remove deprecated driver_base dependency * Upgrade to gazebo 7 and remove deprecated driver_base dependency * disable gazebo_ros_control until dependencies are met * Remove stray backslash
spawn_model: adding -b option to bond to the model and delete it on sigint
Update maintainer for Kinetic release
Allow respawning gazebo node.
Contributors: Hugo Boyer, Isaac IY Saito, Jackie Kay, Jonathan Bohren, Jose Luis Rivero, Steven Peters
2.5.3 (2016-04-11)
Include binary in runtime
Remove ROS remapping arguments from gazebo_ros launch scripts.
Contributors: Jose Luis Rivero, Martin Pecka
2.5.2 (2016-02-25)
merging from indigo-devel
Merge pull request
#302
from maxbader/jade-devel-GetModelState Header for GetModelState service request for jade-devel
Fix invalid signal name on OS X scripts/gazebo: line 30: kill: SIGINT: invalid signal specification
Fix invalid signal name on OS X scripts/gazebo: line 30: kill: SIGINT: invalid signal specification
Restart package resolving from last position, do not start all over.
2.4.9
Generate changelog
Import changes from jade-branch
Add range world and launch file
fix crash
Set GAZEBO_CXX_FLAGS to fix c++11 compilation errors
GetModelState modification for jade
Contributors: Bence Magyar, Boris Gromov, Guillaume Walck, Ian Chen, John Hsu, Jose Luis Rivero, Markus Bader, Steven Peters, hsu
2.5.1 (2015-08-16)
Port of Pal Robotics range sensor plugin to Jade
Added a comment about the need of libgazebo5-dev in runtime
Added missing files
Added elevator plugin
Use c++11
run_depend on libgazebo5-dev (
#323
) Declare the dependency. It can be fixed later if we don't want it.
Contributors: Jose Luis Rivero, Nate Koenig, Steven Peters
Port of Pal Robotics range sensor plugin to Jade
Added a comment about the need of libgazebo5-dev in runtime
Added missing files
Added elevator plugin
Use c++11
run_depend on libgazebo5-dev.10 (2016-02-25)
Fix invalid signal name on OS X scripts/gazebo: line 30: kill: SIGINT: invalid signal specification
Restart package resolving from last position, do not start all over.
Contributors: Boris Gromov, Guillaume Walck
2.4.9 (2015-08-16)
Import changes from jade-branch
Add range world and launch file
fix crash
Set GAZEBO_CXX_FLAGS to fix c++11 compilation errors
Contributors: Bence Magyar, Ian Chen, Jose Luis Rivero, Steven Peters
2.4.8 (2015-03-17)
Specify physics engine in args to empty_world.launch
Contributors: Steven Peters
2.4.7 (2014-12-15)
temporary hack to
fix
the -J joint position option (issue
#93
), sleeping for 1 second to avoid race condition. this branch should only be used for debugging, merge only as a last resort.
Fixing set model state method and test
Extended the fix for
#246
also to debug, gazebo, gzclient and perf scripts.
Update Gazebo/ROS tutorial URL
[gazebo_ros] Fix for
#246
Fixing issue
#246
in gzserver.
Fixing handling of non-world frame velocities in setModelState.
update headers to apache 2.0 license
update headers to apache 2.0 license
Contributors: John Hsu, Jose Luis Rivero, Martin Pecka, Tom Moore, ayrton04
2.4.6 (2014-09-01)
Merge pull request
#232
from ros-simulation/fix_get_physics_properties_non_ode Fix get physics properties non ode
Merge pull request
#183
from ros-simulation/issue_182 Fix STL iterator errors, misc. cppcheck (
#182
)
check physics engine type before calling set_physics_properties and get_physics_properteis
check physics engine type before calling set_physics_properties and get_physics_properteis
Fixes for calling GetParam() with different physic engines.
2.3.6
Update changelogs for the upcoming release
Fixed boost any cast
Removed a few warnings
Update for hydro + gazebo 1.9
Fix build with gazebo4 and indigo
Fix STL iterator errors, misc. cppcheck (
#182
) There were some errors in STL iterators. Initialized values of member variables in constructor. Removed an unused variable (model_name).
Contributors: Carlos Aguero, John Hsu, Jose Luis Rivero, Nate Koenig, Steven Peters, hsu, osrf
2.4.5 (2014-08-18)
Port fix_build branch for indigo-devel See pull request
#221
Contributors: Jose Luis Rivero
2.4.4 (2014-07-18)
Fix repo names in package.xml's
fix issue
#198
Operator
==
is not recognized by sh scripts.
Add verbose parameter Add verbose parameter for --verbose gazebo flag
added osx support for gazebo start scripts
Contributors: Arn-O, Jon Binney, Markus Achtelik, Vincenzo Comito
2.4.3 (2014-05-12)
added osx support for gazebo start scripts
Remove gazebo_ros dependency on gazebo_plugins
Contributors: Markus Achtelik,)
gazebo_ros: [less-than-minor] fix newlines
gazebo_ros: remove assignment to self If this is needed for any twisted reason, it should be made clear anyway. Assuming this line is harmless and removing it because it generates cppcheck warnings.
Contributors: Paul Mathieu
2.3.4 (2013-11-13)
rerelease because sdformat became libsdformat, but we also based change on 2.3.4 in hydro-devel.
remove debug statement
fix sdf spawn with initial pose
fix sdf spawn with initial pose
Merge branch 'hydro-devel' into
spawn_model_pose_fix
fix indentation
Merge pull request
#142
from hsu/hydro-devel fix issue
#38
, gui segfault on model deletion
Merge pull request
#140
from
v4hn/spawn_model_sleep
replace time.sleep by rospy.Rate.sleep
fix spawn initial pose. When model has a non-zero initial pose and user specified initial model spawn pose, add the two.
fix issue
#38
, gui segfault on model deletion by removing an obsolete call to set selected object state to "normal".
replace time.sleep by rospy.Rate.sleep time was not even imported, so I don't know why this could ever have worked...
Add time import When using the -wait option the script fails because is missing the time import
Use pre-increment for iterators
Fix iterator erase() problems
2.4.0 (2013-10-14)
2.3.3 (2013-10-10)
Cleaned up unnecessary debug output that was recently added
Fixed issue where
catkin_find
returns more than one library if it is installed from both source and debian.
update gazebo includes
Fixed a minor typo in spawn_model error message when
-model
not specified
2.3.1 (2013-08-27)
Cleaned up template, fixes for header files
2.3.0 (2013-08-12)
gazebo_ros: fixed missing dependency on TinyXML
gazebo_plugins: replace deprecated boost function This is related to
this gazebo issue
2.2.1 (2013-07-29)
2.2.0 (2013-07-29)
Switched to pcl_conversions
Remove find_package(SDF) from CMakeLists.txt It is sufficient to find gazebo, which will export the information about the SDFormat package.
2.1.5 (2013-07-18)
gazebo_ros: fixed variable names in gazebo_ros_paths_plugin
2.1.4 (2013-07-14)
2.1.3 (2013-07-13)
2.1.2 (2013-07-12)
Added author
Tweak to make SDFConfig.cmake
Cleaned up CMakeLists.txt for all gazebo_ros_pkgs
Cleaned up gazebo_ros_paths_plugin
2.1.1
2.1.1 (2013-07-10 19:11)
Merge branch 'hydro-devel' of github.com:ros-simulation/gazebo_ros_pkgs into hydro-devel
Reduced number of debug msgs
Fixed physics dynamic reconfigure namespace
gazebo_ros_api_plugin: set
plugin_loaded_
flag to true in GazeboRosApiPlugin::Load() function
Actually we need
__init__.py
Cleaning up code
Moved gazebo_interface.py from gazebo/ folder to gazebo_ros/ folder
Removed searching for plugins under 'gazebo' pkg because of rospack warnings
Minor print modification
Added dependency to prevent missing msg header, cleaned up CMakeLists
2.1.0 (2013-06-27)
gazebo_ros: added deprecated warning for packages that use gazebo as package name for exported paths
Hiding some debug info
gazebo_ros: use rosrun in debug script, as rospack find gazebo_ros returns the wrong path in install space
Hide Model XML debut output to console
gazebo_ros_api_plugin.h is no longer exposed in the include folder
Added args to launch files, documentation
Merge pull request
#28
from osrf/no_roscore_handling Better handling of gazebo_ros run when no roscore started
gazebo_ros: also support gazebo instead of gazebo_ros as package name for plugin_path, gazebo_model_path or gazebo_media_path exports
gazebo_plugins/gazebo_ros: fixed install directories for include files and gazebo scripts
changed comment location
added block comments for walkChildAddRobotNamespace
SDF and URDF now set robotNamespace for plugins
Better handling of gazebo_ros run when no roscore started
2.0.2 (2013-06-20)
Added Gazebo dependency
changed the final kill to send a SIGINT and ensure only the last background process is killed.
modified script to work in bash correctly (tested on ubuntu 12.04 LTS)
2.0.1 (2013-06-19)
Incremented version to 2.0.1
Fixed circular dependency, removed deprecated pkgs since its a stand alone pkg
Shortened line lengths of function headers
Renamed Gazebo model to SDF model, added ability to spawn from online database
Fixed really obvious error checking bug
Deprecated -gazebo arg in favor of -sdf tag
Reordered services and messages to be organized and reflect documentation. No code change
Cleaned up file, addded debug info
Merged changes from Atlas ROS plugins, cleaned up headers
Small fixes per ffurrer's code review
Deprecated warnings fixes
Cleaned up comment blocks - removed from .cpp and added to .h
Merged branches and more small cleanups
Small compile error fix
Standardized function and variable naming convention, cleaned up function comments
Reduced debug output and refresh frequency of robot spawner
Converted all non-Gazebo pointers to boost shared_ptrs
Removed old Gazebo XML handling functions - has been replaced by SDF, various code cleanup
Removed the physics reconfigure node handle, switched to async ROS spinner, reduced required while loops
Fixed shutdown segfault, renamed
rosnode_
to
nh_
, made all member variables have
_
at end, formatted functions
Added small comment
adding install for gazebo_ros launchfiles
Formatted files to be double space indent per ROS standards
Started fixing thread issues
Fixing install script names and adding gzserver and gdbrun to install command
Fixed deprecated warnings, auto formatted file
Cleaned up status messages
Added -h -help --help arguemnts to spawn_model
Removed broken worlds
Removed deprecated namespace argument
Using pkg-config to find the script installation path. Corrected a bash typo with client_final variable in gazebo script.
Cleaning up world files
Deprecated fix
Moved from gazebo_worlds
Cleaning up launch files
Moved from gazebo_worlds
Fixing renaming errors
Updated launch and world files and moved to gazebo_ros
Combined gzclient and gzserver
Added finished loading msg
All packages building in Groovy/Catkin
Imported from bitbucket.org | http://docs.ros.org/kinetic/changelogs/gazebo_ros/changelog.html | CC-MAIN-2019-47 | refinedweb | 2,251 | 51.68 |
Well, since my last complaint was over two months ago, I guess I'm fairly happy. Now I'll give something of an anti-poka-yoke
Who among us has not started with a function like:
def munger(v): v = mungify(v) return doublemungify(v)
Then realized doublemungify goes too far, and changes it to:
def munger(v): v = mungify(v)
But, whoops, now the function returns None. There are many ways to encounter this common bug, to unintentionally return None by not returning anything at all. Maybe one of the execution paths doesn't have a return, or you just forgot about the return at some point. It happens to me often -- but the worst part is that it's not quickly detected. Often I'll collect the results of munger, and the None will only cause a problem sometime later when it's unclear where it came from. Python nit: functions return None when you don't want them to return anything -- None is a oft-used real value, not some this-function-returns-nothing value.
It would be better if functions didn't return any value when no return (or a bare return) when encountered. So using the second munger form in an expression would cause an immediate (and informative) exception. In other words, distinguishing functions from procedures.
It seems like there's some sort of elegance in not making that distinction, in keeping these objects uniform. Plus Pascal distinguishes the two forms, and we all hate Pascal. But really, what use can there be to the implicit returning of None?
Well, one use, usually in subclassing. Supposing munger is a method, we might do:
class SafeGrinder(Grinder): def munger(self, v): if not self.isSafe(v): raise ValueError, "Unsafe: %s" % v return Grinder.munger(self, v)
Because we can always treat functions as, well, functions, we can blindly pass values through. Without this we'd need some sort of special syntax to deal with no return value, or else a way to test whether the object was a function or procedure. The test would be annoying, and would require some static declaration (e.g., two kinds of def). The static declaration would make that pass-through function even harder, because it wouldn't be sufficient to just test whether the function returned a value, we'd also have to declare whether our pass-through code was a function or procedure.
Some other syntax might be better, like (Grinder.munger(self, v) ifprocedure None), which would evaluate to None if Grinder.munger was a procedure, or the return value if not. Then you might do something like:
class OneOff: pass class SafeGrinder(Grinder): def munger(self, v): if not self.isSafe(v): raise ValueError, "Unsafe: %s" % v result = Grinder.munger(self, v) ifprocedure OneOff if result is not OneOff: return result
Or maybe even better:
class SafeGrinder(Grinder): def munger(self, v): if not self.isSafe(v): raise ValueError, "Unsafe: %s" % v try: return Grinder.munger(self, v) except NoReturnValue: pass # and return no value
It can be a little complicated, though only for this one case, while other more common cases would be less error-prone. But it's not really going to happen in this late stage. Oh well.
Here it comes...wait for it...wait for it...unit tests would help here!
If the function which previously returned something meaningful but now returns None were being unit tested, the test would immediately fail. Then you'd only be out about 30 seconds of your life (time between test failing and realizing your mistake). Its a good start at the least.
But if we're going to take the syntactic route, perhaps requiring a return statement would be better. Again, hard to do this late in the game. Yep, once you ship a language you're screwed :)
might interest...
It strikes me that tests like this are possibly better added to a tool like pychecker, rather than to the language itself. | http://www.ianbicking.org/python-nit-chapter-2.html | CC-MAIN-2016-50 | refinedweb | 666 | 64.81 |
I just started C a few days ago in class and I've been working on a problem for well over 2 hours and still cannot figure it out. I am extremely noobish in this subject, so I was hoping someone can help me with this. I ran searches for about 30 minutes but I still did not understand the programs that some wrote because it is far more advance than I am right now.
The problem states:
Write a program that inputs three different integers from the keyboard, then prints the sum, the product, the average, the smallest and the largest of these numbers. Use only the single-selection form of the if statement.
I've gotten the sum, the product, and average to work but the smallest and the largest is making me go crazy. The teacher wants us to use the IF statements. something like this:
if ( num1 <= num2 ) {
printf( "%d is less than or equal to %d\n", num1, num2 );
This is what I got so far:
#include <stdio.h>
int main()
{
int x, y, z;
int sum;
int average;
int product;
printf( "Input 3 different integers: ");
scanf( "%d%d%d", &x, &y, &z );
sum = x + y + z;
average = (x + y + z)/3;
product = x * y * z;
printf( "Sum is %d\n", sum );
printf( "Average is %d\n", average);
printf( "Product is %d\n", product );
system ("pause");
return 0;
}
PLEASE HELP ME!!! This is one crazy labor day weekend. | http://cboard.cprogramming.com/c-programming/82558-find-largest-smallest-number.html | CC-MAIN-2016-36 | refinedweb | 243 | 73.31 |
At 21:15 +0000 12/10/06, Paul Vixie wrote:[color=blue]
>
>we know there won't be a new namespace. ever. but in addition to adding
>new kinds of names (idn) and securing the data (dnssec) we have sometimes
>tried to improve the protocol (edns). if i were to embark on dnsv2 it would
>be with the hope of completely forklift-upgrading the protocol while keeping
>the namespace as it is.
>[/color]
I agree with that. Where I see the discussion getting wrapped around
an axle is when we cross the divide between conveying the data in the
name space with regulating the data in the name space. I've trotted
this out before, there is a difference between talking about DNS and
talking about provisioning of domain names.
It may be hard to see, but every DNS zone is managed by some sort of
registry. Whether it is a formal one like the g/sTLDs of ICANN or a
ccTLD, or just a personal zone with three names in it, there is a
registry. The heart of the registry may be a distributed database or
a text file, the process of generating the zone file may be a
database difference report or the text file may already look like a
zone file.
Coming up with a new wire protocol for DNS would represent about as
much of a change as bring up servers on IPv6 to a registry. DNS is
just a publication mechanism, not what is regulated. Perhaps a new
protocol is more like the transition from LP's to CD's - the music
stayed the same but the cases got smaller. 'Course the analogy
breaks down when you get to MP3's and on-line stores, etc. And
DC-101 (local radio) had to change from "7 album sides at 7" to "7
CD-sides at 7" declaring each half of a CD to be a side.
A cleaned up DNS would present an issue to the regulators - a better
implementation of the CLASS concept. But that's their problem, not
ours. ;)
--
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Edward Lewis +1-571-434-5468
NeuStar
Dessert - aka Service Pack 1 for lunch.
--
to unsubscribe send a message to [email]namedroppers-request@ops.ietf.org[/email] with
the word 'unsubscribe' in a single line as the message text body.
archive: <> | http://fixunix.com/dns/59509-re-brain-cycles-wg-print.html | CC-MAIN-2015-32 | refinedweb | 387 | 69.01 |
Last year, we announced the sunset of Windows Azure Access Control Service (ACS) version 1.0 and the availability of the ACS 1.0 Migration Tool that helps customers to easily migrate their ACS 1.0 namespaces to ACS 2.0.
We’re excited to share that we are able to automatically migrate many customers to ACS 2.0 in June 2012. Details regarding this have been already sent to customers with ACS 1.0 namespaces via email last month.
If you have one or more ACS 1.0 namespaces, did not receive an email, and would like more information about automatic migration to ACS 2.0, please send an email to acsmigration@microsoft.com with your Windows Azure subscription ID and ACS 1.0 namespaces.
Click here to see a list of important differences between ACS 1.0 and ACS 2.0. | https://azure.microsoft.com/ru-ru/blog/automatic-migration-of-access-control-service-version-1-0/ | CC-MAIN-2021-21 | refinedweb | 143 | 79.06 |
Pankaj,
Thanks for the link and suggestion.
- Gopal
Pankaj Kumar wrote:-
>
> Hi,
>
> Few months ago I had written a program to measure Java XML parsing
> performance. May be it could be of some use here. You can find details at
>
>
> I am not aware of Xerces internals so whatever I say here may not make much
> sense but one area where I feel that optimization at parser level can
> improve performance in server based applications is use of same String
> objects across parse runs. Let me elaborate -- A server program that accepts
> XML documents with every request comes across instances of documents from a
> small subset of schema. These documents use the same element names,
> attrobutes and namespace URIs. If the same immutable String objects can be
> used for these then there could be significant saving in allocation and
> deallocations.
>
> The problem is slightly complicated as the identification of repeating
> Strings must happen at a much lower level, before a String object is created
> of a lookup. What could do the job is perhpas some smart lookup during
> lexical analysis.
>
> Regards,
> Pankaj Kumar
> Web Services Architect
> HP Middleware
>
> -----Original Message-----
> From: Gopal Sharma
> To: general@xml.apache.org; xerces-j-user@xml.apache.org
> Sent: 5/5/02 7:18 AM
> Subject: [Xerces2] Measuring performance and optimization
>
>
> FYI
>
> -------------
>
>
>
> ---------------------------------------------------------------------
> | http://mail-archives.apache.org/mod_mbox/xml-general/200205.mbox/%3C200205061403.g46E33m28568@blr-root.India.Sun.COM%3E | CC-MAIN-2017-09 | refinedweb | 218 | 60.85 |
Eclipse Community Forums - RDF feed Eclipse Community Forums WS-* <![CDATA[Hello,. Thank you in advance. Survey: anketa.informatika.uni-mb.si/index.php?r=survey/index&sid=863884&lang=en]]> Diana Matic 2018-03-10T20:00:09-00:00 Distributing apps via eclips <![CDATA[Is it possible to launch my executable with double click in eclipse after exporting ? import java.util.Scanner; public class S { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a: "); int a = scan.nextInt(); System.out.println("Enter b: "); int b = scan.nextInt(); int result = (a + b) / 2; System.out.println("(a+b)/2 is: " + result); } }]]> Nagesh Kumar 2017-09-14T08:04:34-00:00 BPMN2 Modeler Project : Definition of LoopMaximum in BPMN2 Metamodel <![CDATA[Hi All, As per the BPMN2.0 specification, the definition for 'StandardLoopCharacterisitcs' is as below: <xsd:complexType <xsd:complexContent> <xsd:extension <xsd:sequence> <xsd:element </xsd:sequence> <xsd:attribute <xsd:attribute </xsd:extension> </xsd:complexContent> </xsd:complexType> Here loopMaximum is an attribute of type Int, However in BPMN2 metamodel defined for BPMN2 Modeler, it is Expression. This difference creates an error when standard BPMN 2.0 file is opened with the BPMN2 Modeler. Please change the metamodel so that loopMaximum is an EAttribute of Integer type for 'StandardLoopCharacteristscs' Thanks & Regards, Kunal]]> Kunal Prasad 2013-03-08T11:11:38-00:00 Re: BPMN2 Modeler Project updates <![CDATA[hi i would like only the diagram part of the gmf editor . the project you specified is developed in graphiti . i have the ecore metamodel of bpmn2 could please tell me how to develop an gmf editor from it. ]]> karthick9686@gmail.com Missing name 2011-07-27T13:29:42-00:00 BPMN2 Modeler Project updates <![CDATA[Hi all, We've made progress with the BPMN2 Modeler project at eclipse. The project landing page is at but it's not much to look at just yet ( baby steps The update site is here: Note that the BPMN2 metamodel plug-ins are still not available from any eclipse update site, so I've created a temporary home for them here: These have to be installed in your eclipse workbench first, before installing the editor. If you want to build the editor from sources, you can clone the GIT repository thusly: git clone and then run "mvn -P platform-indigo clean install" on the project (there's also a helios profile). There's also a mailing list to which you can subscribe at Stay tuned...]]> Robert Brodt 2011-07-19T17:48:36-00:00 Re: Proposed Eclipse Process Manager (Stardust) sub-project <![CDATA[Sorry, 12th of July of course. Zsolt ]]> Zsolt Beothy-Elo 2011-06-29T12:55:25-00:00 Re: Proposed Eclipse Process Manager (Stardust) sub-project <![CDATA[Hi Marc, first of all congratulations for the successful creation review. I did not read any confirmation message from Wayne but as the records show you were approved I assume I just missed notice. As long as you are waiting to get provisioned I like to invite you to one of the next PMC calls of the SOA Top Level project, which you choosed as new home here at eclipse. It would be a good opportunity to discuss the state of the stardust project and where we from the PMC can support you. We would also like to get to know the stardust project better and to identfy where there are possible integration points with other projects within the SOA TLP, but also of course where there is potential overlap and how we handle it. We have our call every 4 weeks. Next one is 12th of June. If you want to know the exact dates for the next dates have a look to our wiki page [1] . It would be nice to just drop a short notice in our pmc mailing list [2], when you plan to join the call to make sure we are all present in the call. Zsolt Beothy-Elo PMC Lead of the SOA TLP [1] [2]]]> Zsolt Beothy-Elo 2011-06-29T12:53:04-00:00 Proposed Eclipse Process Manager (Stardust) sub-project <![CDATA[All, we (SunGard) have proposed the Eclipse Process Manager (Stardust) sub-project. The contribution is our entire Infinity Process Platform BPM Suite incluidng modeling, simulation, system integration, document management, workflow, process engine, end user portal, reporting etc. We have started first discussions with other projects (BPMN 2.0 Modeler, Eclipse Content Repository) on possible cooperation and are aiming at a creation review in the next 1-2 weeks. We have prepared the code for submission and will submit after the creation review. As long as the project is not alive, we will provide free access for everybody interested to the current SunGard version of the software (Infinity Process Platform 5.3) which is the one previous to the version we will be submitting the code for (Infinity Process Platform 6.0). Details will be posted on the project page once created. Looking forward for an intensive community work with you all and together building the best open source BPMS under the Eclipse umbrella. Marc]]> Marc Gille 2011-05-12T10:53:09-00:00 Proposed BPMN 2.0 editor sub-project <![CDATA[Hi all, We (Red Hat/JBoss) are proposing the creation of a BPMN 2.0-compliant graphical editor project as a sub-project of SOA. We currently have a working prototype based on graphiti and the MDT BPMN2 meta model which will comprise the initial code contribution. Until the proposal has been reviewed by the Eclipse Foundation, I'd like to use this news group to solicit feedback and involve interested parties in a discussion of this project. NOTE: I've recently been made aware that the STP news group, while still very active, has been deprecated in favor of this one. If anyone's interested, the code is currently being hosted at github - reply to this post for details if you can't find it. Regards, Bob Brodt]]> Robert Brodt 2011-03-31T23:55:04-00:00 Welcome to eclipse.soa <![CDATA[Welcome to the For general discussions related to SOA technologies at Eclipse.-01-15T05:01:01-00:00 | https://www.eclipse.org/forums/feed.php?mode=m&l=1&basic=1&frm=163&n=10 | CC-MAIN-2018-30 | refinedweb | 1,031 | 54.83 |
PKCS7_sign —
create a PKCS#7 signedData structure
#include
<openssl/pkcs7.h>
PKCS7 *
PKCS7_sign(X509 *signcert,
EVP_PKEY *pkey, STACK_OF(X509)
*certs, BIO *data, int
flags);.
Any of the following flags (OR'ed together) can be passed in the flags parameter., though the signer's
certificate must still be supplied in the signcert
parameter. This can reduce the size of the signature if the signer's
certificate can be obtained by other means: for example a previously signed
PKCS7_PARTIAL flag is set, a
partial PKCS7 structure is output to which additional
signers and capabilities can be added before finalization.().(3)
and attributes can be added using the functions described in
PKCS7_add_attribute(3).
PKCS7_final(3) must also be called
to finalize the structure if streaming is not enabled. Alternative signing
digests can also be specified using this method.
In OpenSSL 1.0.0, if signcert and
pkey are
NULL, then a
certificate-only PKCS#7 structure is output.
In versions of OpenSSL before 1.0.0 the
signcert and pkey parameters
must NOT be
NULL.
PKCS7_sign() returns either a valid
PKCS7 structure or
NULL if an
error occurred. The error can be obtained from
ERR_get_error(3).
PKCS7_add_attribute(3), PKCS7_encrypt(3), PKCS7_final(3), PKCS7_get_signer_info(3), PKCS7_new(3), PKCS7_sign_add_signer(3), PKCS7_verify(3)
PKCS7_sign() first appeared in OpenSSL
0.9.5 and have been available since OpenBSD 2.7.
The
PKCS7_PARTIAL and
PKCS7_STREAM flags were added in OpenSSL 1.0.0.
Some advanced attributes such as counter signatures are not supported. | https://man.openbsd.org/PKCS7_sign.3 | CC-MAIN-2022-27 | refinedweb | 245 | 50.94 |
XML in Flash is Easy because RSS Feeds are Free [AS2] · Dec 31, 02:34 AM
The previous article explained how to insert flash into a Textpattern-powered site, but failed to integrate the content so that there would be no duplication. Instead, the CMS was used to re-publish content from our flash movie for search-bot and non-flash-browser compatibility. Doing it this way doesn’t really make sense. In fact, a compelling reason to use a CMS is to eliminate the need to duplicate content. Our new approach should be simple: put all content in the CMS, and have the CMS automatically output two versions: XML for Flash, HTML for everyone else.
Download the source-code files for this article
There are two ways to use XML content from Textpattern
- Create a custom section, page, and form that ouputs XML.
- Use Textpattern’s automatically generated RSS feed (RSS feeds are valid XML)
This article will focus on the second method because it requires far less work. In fact, because RSS feeds are automatically generated with Textpattern’s default installation, there won’t be any setup in Textpattern. When you install Textpattern, a section named article is automatically created. By default, all articles in this section will be included in the RSS feed located at (assuming you installed TextPattern in the root web directory of the example.com domain). You can also set any section of your site to be included in the feed: goto the sections tab and set the Syndicate option to yes.
Reading an RSS Feed in Flash
Luckily, someone has made this easy for us: An ActionScript code package that downloads and parses an RSS feed and sticks the information inside of an ActionScript object.
Download the ActionScript RSS Parser Package released by Cybozu Labs, Inc.
Now available here: CybozuRssParser.zip
After you unzip the Cybozu file, copy the com folder to the folder with your flash file. Then you can use the following line of code to import the package into your Flash file:
import com.cybozuLab.rssParser.*;
This is the basic code structure for using the parser, follow the comments for explanation: ) {
// Do something with rssObj.getRssObject()
} else {
trace( errMsg );
}
}
-
// start loading
rssObj.load();
- Download this code: /files/code2.1.txt
Adding new Functionality to the Sample Code
The sample code for this article works off of the previous one. To add additional functionality, we will create a new movie called AFWRssViewer.swf and simply load this movie into home.swf using another instance of AFWLoader.
The screen-capture above shows home.fla with the changes applied. The selected movie is the new AFWLoader, called feedloader_mc, and it lives on the feedloader layer.
We also need to change a few lines of code inside the setPath() function of home.fla that will tell feedloader_mc to load the correct movie, or hide it when we navigate to a different link:
function setPath(path_arr) {
link = path_arr[0] eq "" ? "home" : path_arr[0] ;
url = "images/"+link+".jpg";
loader_mc.loadMovie(url, link);
-
// Load or Hide AFWRssViewer.swf
if (link eq "home") {
feedLoader_mc.loadMovie("AFWRssViewer.swf", "rss");
feedLoader_mc._visible = true;
} else {
feedLoader_mc._visible = false;
}
}
- Download this code: /files/code2.2.txt
Creating the AFWRssViewer.fla Movie
This movie is an RSS reader that displays one feed item at a time. The title and date of each item is displayed using some trippy text animation, and the body text fades in and out. There is also a non-functional button that would presumably take you to the link associated with the feed item.
Because the topic at hand is RSS, I won’t delve into a detailed explanation of the sample code. However, if you need clarification or additional detail, please post a comment. The following screenshot shows the timeline and stage of the completed AFWRssViewer.fla:
In the library, there are some components that I’ve thrown in to make the task simpler. First, AFWfx generates animated text: after it is instantiated, one call to setText(“my text”) starts the text animation. When placed on the stage, an instance of AFWfx looks like the letter W (see above image). Second, AFWTextSlider is used to display some text and also performs a fade-transition effect.
The code that follows ties together the aforementioned components. This code lives in frame 2 of AFWRssViewer.fla‘s main timeline:
import com.cybozuLab.rssParser.*;
stop();
-
var rssIntervalId = 0;
var index = 0;
var thisObj = this;
-
// We'll populate this array with information from the feed
var arr_XMLHash:Array = new Array();
-
// initialize feed
var rssObj = new FetchingRss( "" );
-
// Initialize the AFWTextSlider on the stage
// displays feed content
ts_mc.setBackgroundAlpha(0);
ts_mc.setSelectable(false);
ts_mc.setControlsEnabled(false);
ts_mc.loadStyle("afw.css");
ts_mc.startTimerScroll();
-
// define the function when loading is completed
rssObj.onLoad = function( successFL, errMsg ) {
if( successFL ) {
thisObj.readRss();
} else {
trace( errMsg );
}
}
// start loading
rssObj.load();
-
// onLoad calls this function to process the feed
function readRss() {
var rssData:Object = rssObj.getRssObject();
-
// process the rss data into arr_XMLHash
for( var i=0; i<rssData.channel.item.length; i++ ) {
var post:Object = rssData.channel.item[i];
var XMLHash:Object = {};
-
XMLHash.date = post.pubdate.value;
XMLHash.title = post.title.value;
XMLHash.link = post.link.value;
XMLHash.desc = post.description.value;
trace("XMLHash:"); for (var a in XMLHash) { trace(" "+a+": "+XMLHash[a]); }
-
arr_XMLHash.push(XMLHash);
}
-
// Display the first item in the feed
if (arr_XMLHash.length>0) {
fx2.setText(arr_XMLHash[0].title);
fx1.setText(arr_XMLHash[index].date);
ts_mc.fadeText(arr_XMLHash[0].desc);
rssIntervalId = setInterval(this, "rssIntervalCallback", 13000);
}
}
-
// This function displays the next feed
function rssIntervalCallback() {
if (arr_XMLHash.length == 0) return;
index++;
if (index >= arr_XMLHash.length) index = 0;
fx2.setText(arr_XMLHash[index].title);
fx1.setText(arr_XMLHash[index].date);
ts_mc.fadeText(arr_XMLHash[index].desc);
}
-
// this function should theoretically display the link somehow
feedButton.onRelease = function () {
trace("clicked");
}
- Download this code: /files/code2.3.txt
— Pickle
Comment
Basic Structure of a Flash Website [AS2] Content in Flash and Textpattern: Bridging the Gap with XML [AS2]
How would you parse special characters from the RSS feed?
— Jesper Johansen · Jul 8, 12:42 AM · #
The RSS feed generated by Textpattern is valid XML. An ampersand, for example is converted to &
Parsing the feed is not necessary: You’ll probably want to display the feed inside of a container that supports HTML rendering. Luckily, such a text area is included in Flash 8. I’ve added some entities to the demo (click the link at the beginning of the article to see it in action)
— Pickle · Jul 8, 05:27 PM · #
Hi,
thanx for the great code! Just one problem here: i can’t get the full text of the description item by any means. I always get truncated at some point with a […]. Any idea? about
— andrea · Nov 4, 04:01 AM · #
andrea, do you understand that the description will actually correspond to the article’s excerpt, and not the full body? If you need the full body I would recommend creating a custom section/page/form for this purpose (see Content in Flash and Textpattern: Bridging the Gap with XML [AS2])
— Pickle · Nov 4, 12:46 PM · #
Was really excited to read this post, until I realized that the RSS package referenced is no longer a working link. I don’t suppose you have a copy of that file?
— Raymond Brigleb · Mar 16, 10:13 AM · #
I’ve added a link under the original one :)
— Pickle · Mar 16, 06:07 PM · #
I am trying to trace the feed into a dynamic txt box i feel like i have the code all set up fine but for some reason all it traces is [object Object]
here is my code ) { txt_feed = rssObj; trace(rssObj) } else { trace( errMsg ); } }
// start loading
rssObj.load();
— Chris · Apr 28, 11:36 AM · #
Chris, you are trying to print the object that holds the result, not the result itself. Please take another look at the example code, specifically the readRss() function.
— Pickle · Apr 28, 12:49 PM · #
All is well, except for the misfortune that my RSS reader does fine in testing mode, but doesnt when published, or run as stand-alone SWF. No, System.security.allowDomain doesnt work. It simply gives a load error. Why?
— PJ · May 19, 08:50 AM · #
PJ — Via Email:
I asked:
Answer:
Solution:
— Pickle · May 23, 10:40 AM · # | http://www.allflashwebsite.com/article/xml-is-easy-because-rss-feeds-are-free | crawl-002 | refinedweb | 1,382 | 55.84 |
Created on 2010-06-11 20:26 by serprex, last changed 2010-06-12 16:53 by mark.dickinson. This issue is now closed.
A note on the patch, ste->ste_tmpname... lines, along with changes to Lambda_kind, were not added by me. The additional newlines prior to symtable_visit_stmt's declaration are accidental, apologies. I'll avoid patching a snapshot and then pull the old version from hg after realizing I need the old version to run diff on next time
This seems evil to me, when you consider the effect of this patch on immutable types:
>>> A = 3
>>> def f():
... A += 5
...
>>> f()
>>> A
8
I find the possibility that a function can implicitly (i.e., without any 'global' declarations) mutate my global module constants... disturbing.
Anyway, such a fundamental change would need proper discussion; the right place for that is the python-ideas mailing list rather than the tracker:
Note also that there's a moratorium on core language changes in effect at the moment, so the earliest this could change is Python 3.3.
I'm going to close this issue for now; if the idea gets a good reception on python-ideas it can be reopened.
It's not that much more evil than this:
A = []
def f(x):
A.append(x)
print(A) # []
f(4)
print(A) # [4]
I've always thought this is a borderline case.
True. I guess there's a mismatch either way around: currently,
"A += [4]" and "A.append(4)" behave differently for (e.g.,) a list A. With the proposed change, "n += 3" and "n = n + 3" behave differently for a integer n. I'm not sure why I find the latter idea more disturbing than the former.
Because the latter (n += 1) is more fundamental, since it uses integers (arguably the most fundamental type).
This is why we've never done it before.
I've modified the patch to be less aggressive, as suggested by Nick at
As an aside, runtests.sh should have executable permissions
> As an aside, runtests.sh should have executable permissions.
Doesn't it already? On my system (without having ever messed with any permissions as far as I can recall), I have:
newton:py3k dickinsm$ ls -l runtests.sh
-rwxr-xr-x 1 dickinsm staff 2168 28 Aug 2009 runtests.sh
newton:py3k dickinsm$ svn pl runtests.sh
Properties on 'runtests.sh':
svn:executable
svn:eol-style
And I get the same with a fresh hg checkout from | http://bugs.python.org/issue8977 | CC-MAIN-2014-15 | refinedweb | 413 | 75.1 |
Using Python for data science is usually a great experience, but if you’ve ever worked with pandas or GeoPandas, you may have noticed that they use only a single core of your processor. Especially on larger machines, that is a bit of a sad situation.
Developers came up with many solutions to scale pandas, but the one that seems to take the lead is Dask. Dask (specifically
dask.dataframe as Dask can do much more) creates a partitioned data frame, where each partition is a single
pandas.DataFrame. Each of them can be then processed in parallel and combined when necessary. On top of that, the whole pipeline can be scaled to a cluster of machines and can deal with out-of-core computation, i.e. with datasets that do not fit the memory.
Today, we announce the release of Dask-GeoPandas 0.1.0, a new Python package that extends
dask.dataframe in the same way GeoPandas extends pandas, bringing the support for geospatial data to Dask. That means geometry columns and spatial operations but also spatial partitioning, ensuring that geometries that are close in space are within the same partition, necessary for efficient spatial indexing.
The project has been in development for quite some time. The original exploration of bridging Dask and GeoPandas started almost 5 years ago by Matt Rocklin, the author of Dask. Later, in 2020, Julia Signell revised the idea and created the foundations of the current project. Since then, GeoPandas maintainers have taken over and led the recent development.
What is awesome about Dask-GeoPandas? First, you can do your spatial analysis in parallel, making sure all available resources are used (no more sad idle cores!), turning your workflow into faster and more efficient ones. You can also use Dask-GeoPandas to process data that do not fit your machine’s memory as Dask comes with a support of out-of-core computation. Finally, you can distribute the work across many machines in a cluster. And all that with almost the same familiar GeoPandas APIs.
The latest evolution of underlying libraries powering GeoPandas ensures that it is efficient in terms of utilisation of resources but also performant within each partition. For example, unlike GeoPandas, where the use of
pygeos, a new vectorised interface to GEOS is optional, Dask-GeoPandas requires it. Similarly, it depends on
pyogrio, a vectorised interface to GDAL, to read geospatial file formats.
At this moment, Dask-GeoPandas can do a lot of what GeoPandas can, with some limitations. When your code involves individual geometries, without assessing a relationship between them (like computing a centroid or area), you should be able to use it directly. When you need to work out some relationships, you can try (still a bit limited)
sjoin or make use of spatial partitions and spatial indexing.
But not everything is ready. For example, overlapping computation needed for use cases like accessibility or K-nearest neighbour analyses is not yet implemented, PostGIS IO is not done, and some overlay operations are implemented only partially (
sjoin) or not at all (
overlay,
sjoin_nearest). But the 0.1.0 release is just a start.
You can try it yourself, installing via conda (or mamba) or from PyPI (but see the instructions, GeoPandas can be tricky to install using pip).
mamba install dask-geopandas
pip install dask-geopandas
The best starting point to learn how Dask-GeoPandas works is the documentation, but this is the gist:
import geopandas import dask_geopandas df = geopandas.read_file( geopandas.datasets.get_path("naturalearth_lowres") ) dask_df = dask_geopandas.from_geopandas(df, npartitions=8) dask_df.geometry.area.compute()
The code creates a
dask_geopandas.GeoDataFrame with 8 partitions because I have 8 cores and compute each polygon’s area in parallel, giving almost 8x speedup compared to the vanilla GeoPandas.
You can also check my latest post comparing Dask-GeoPandas performance on a large spatial join with PostGIS and cuSpatial (GPU) implementations.
If you want to help, have questions or ideas, you are always welcome. Just head over to Github or Gitter and say hi! | https://martinfleischmann.net/category/geography/ | CC-MAIN-2022-27 | refinedweb | 672 | 55.74 |
Hello! I'm currently trying to develop a "Choose your own adventure" text game. This is a screenshot of the game:
It is going to have a lot of choices and branching stories depending on the choices you make. Something like this:
Is it possible to develop a game like this using only 1 scene? I tried in many different ways but can't seem to get it to work.
Hi.
This isn't overly complicated to achieve. I did kind of exactly the same for android once to experiment with android-oriented coding. For an absolute beginner however it can be a challenge.
"I tried in many different ways but can't seem to get it to work."Well, what have you tried? Let's start with that.
What doesn't "work" like you want it to?Would be a good information to give away if you want help. ;)
I suggest you take a good look at the UI tutorials as well as the beginner scripting tutorials. You can find them in the Learn Section.
To answer your initital question: "how to change text in a specific way with C#":
Text.text, This is asked and answered multiple times already and clearly described in tutorials and documentation.
To answer your second question, "Can it be achived in one single scene":
Yes it can. Theoretically there is no need to switch scenes, but it is much more efficient (especially for 3D games) to just discard the finished scene with it's assets and loading a new scene, rather than instantiating and destroying everything in one huge scene.
For simple and short games like your's or presentations, it is not neccessary to use multiple scenes.
Thanks for your suggestion! I'm currently following a Unity course, I just wanted to see if I could make a mini-game by myself, but I guess I'm not ready :)
As for what I tried, I tought about having an int that changed value based on what button you click, for example: I click on the first button and the int goes to 1, if I click on the second button it goes to -1, then an if statement checked the int's value and changed the text based on that. The choices in the game are going to be a lot so you can see that doesn't work.
I would recommend you use your UI canvas like you already have. You can keep it over the entire game. Read the documentation and scripting reference about buttons and everything else if you are unsure about a specific Unity component.
You will start with the main script, that holds all references you need, to the Question Text for example. It also keeps track of which level in your decision-tree you are currently in. Depending on the level and choice the player made you would then change the text of the question's text to the respective string in your database. I recommend having a seperate script with all your possible texts as a public static string in it, so you can quickly access them and change the question in your game manager script.
public static string
You could write a function that takes a boolean type for the player choices "yes" or "no". Then have the buttons execute that function in their onclick event and the no button feeds the function a false boolean and the yes button a true boolean.
What happens then is up to your wishes, I highly recommend you finish the Unity course, and watch the beginner scripting tutorials as I said earlier.
PS: This is starting to go beyond what Unity Answers is for. It's not for discussion and arguing about methods. There are many forums containing tutorials and discussion threads.
Your initial question is answered I guess. I hope your learning progress goes s$$anonymous$$dily upwards ;)
Answer by Jessespike
·
Mar 02, 2016 at 07:58 PM
Yeah, it's possible. I would create two scripts: One to store references of the UI components and another script that would act as a story node. The node would contain the text for the message and buttons. Clicking on a button would update the text on the UI components. Nodes would be linked to other nodes.
Example:
using UnityEngine.UI;
public class TextAdventureGui : MonoBehaviour {
public Text m_text;
public Button m_button1;
public Button m_button2;
public TextAdventureNode firstNode;
public void Start()
{
ShowNode(firstNode);
}
void ShowNode(TextAdventureNode node)
{
m_text.text = node.m_text;
m_button1.GetComponentInChildren<Text>().text = node.m_button1Text;
m_button2.GetComponentInChildren<Text>().text = node.m_button2Text;
m_button1.onClick.RemoveAllListeners();
m_button2.onClick.RemoveAllListeners();
m_button1.onClick.AddListener(()=>ShowNode(node.m_nextNode1));
m_button2.onClick.AddListener(()=>ShowNode(node.m_nextNode2));
}
}
.
using UnityEngine.UI;
public class TextAdventureNode : MonoBehaviour {
public string m_text;
public string m_button1Text;
public string m_button2Text;
public TextAdventureNode m_nextNode1;
public TextAdventureNode m_nextNode2;
}
So i need to make different scripts for every node? I'm going to end up with lots of scripts if I do that.
What? No. You just need these 2 scripts.
When providing whole scripts to beginners it would make sense to explain them properly. Either by //comments or a step by step guide. ;)
After some testing I managed to make a version of the game that works with a similar script. Thanks for the the name of a clicked button appears as text in another scene
1
Answer
How to implement voice overs linked with buttons?
0
Answers
How To pass from level to the next after winning, with one button ?
1
Answer
Making text appear by pressing a button, only when player is close to the object
1
Answer
Pick your path text adventure
0
Answers | https://answers.unity.com/questions/1149694/text-adventure-game-how-to-change-text-in-a-specif.html?sort=oldest | CC-MAIN-2020-45 | refinedweb | 943 | 62.58 |
A Node.js wrapper for the Windows.UI.Xaml.Hosting WinRT namespace, compatible with Windows 10 APIs.
Using this module, you'll be able to consume the Windows.UI.Xaml.Hosting API directly from Node.js.
This module was automatically generated by NodeRT. For more information on NodeRT and examples on how to use NodeRT modules, please visit the project page at:.
The API exposed by this module is (almost) the same as the API that is listed in:
The only difference in the API is in the way that asynchronous methods and events are used. (See for more details)
This module also contains TypeScript definition files for the API exposed by the module, as well as JavaScript intellisense support for Node.js tools for Visual Studio.
npm install -g npm
In order to install latest node-gyp run:
npm install -g node-gyp
In order to install this module, run npm install:
npm install @nodert-win | https://openbase.com/js/@nodert-win10-rs4/windows.ui.xaml.hosting | CC-MAIN-2022-27 | refinedweb | 157 | 56.86 |
Re: one-liner for characater replacement
- From: "James Giles" <jamesgiles@xxxxxxxxxxxxxxxx>
- Date: Tue, 03 Jun 2008 02:55:20 GMT
glen herrmannsfeldt wrote:
....
PL/I keeps no reserved words, using a free form semicolon
terminated statement syntax.
The latter known to be a bad idea (from direct productivity experiments).
PL/I uses () for bracketing delimiters, except for statement
groups which use PROC/END, BEGIN/END, or DO/END. It originally
only had one case, and has no reserved words (except in the
48 character source character set option).
Again, that kind of statement grouping has long been known to be
a bad idea. Well, PL/I gets it half right.
Data types may be the biggest complaint about PL/I. Floating
point and fixed point data precision may be specified in bits
or digits, as needed. An appropriate type will be supplied.
For fixed point, a scaling factor (number of digits after
the radix point.) (There is some suggestion that it also
specifies the base used in arithmetic. This isn't so
obvious as it seems.)
Yeah, I wouldn't recommend anyone immitate PL/I's types or
it's syntax, One *supporter* of PL/I recommended that you should
never use the divide operator (/) on fixed-point types: there were
too many "gotcha's". Instead, he recommended that people should
use the DIVIDE intrinsic (which has 4 arguments). Sounds real
natural to me.
4) Modules or COMMON? [...]
PL/I uses STATIC EXTERNAL structures, somewhat similar to
the way they work in C.
Too prolific in spreading things around the global namespace.
Using either COMMON or modules only adds the name of the
block or the module to the global namespace - not the name of
every object you decide to share.
Internal procedures complicate separate compilation, so
I don't believe they should be the only option.
A language intended only for small programs probably doesn't
need to worry about separate compilation. In any case, I already
excluded internal procedures. Module procedures require
dependent (but still separate) compilation (assuming the
implementation is a compiler). Either that, or you need the
modules to separate their definition part from their implementation
part (kind of an unnecessary complication for something that's
supposed to be a simple language).
[...] Having
COMPLEX as a predefined structure data type is an interesting
idea. PL/I uses it as an attribute to any numeric data type.
That is, fixed point or floating point data is either REAL
or COMPLEX.
Another thing I wouldn't recommend even for a complex language,
much less a simple one.
9) Operator precedence? C/C++ have 15 (or more, depends on
how you count). Fortran has 10 (or more, depends on how you count).
Pascal has 4. I think there should be 6 or 8 depending on whether
you allow user defined operators or not. User defined operators?
I could be convinced either way.
PL/I seems to have seven:
Yeah, right after I posted the last article, I realized that 7 are needed
(or nine - if user defined operators are permitted):
1) user defined prefix operators
2) exponentiation (I prefer to spell it ^)
3) multiply, divide (*,/)
4) unary + or -, infix + or -
5) concatenate (//)
6) relational operators (oh, you know the usual ones)
7) logical not (¬ is fine)
8) logical and (/\), logical or (\/), logical xor (><)
9) user defined infix operators.
1) **, prefix +, prefix -, not (¬)
This doesn't match normal mathematical usage (where unary
signs are lower precedence than exponentiation). Further, all
logical oparators really should be lower than the relational
operators.
6) boolean AND (&)
7) boolean OR (|)
Dijkstra recommended that those operators have the same
precedence and that parenthesis should always be used to
emphasize order (that is, the language processor should
insist on it). I have come to agree.
The four operators at the highest level seem a little
unusual, as languages go. PL/I will convert data where
needed, such that some combinations not allowed in other
languages are allowed in PL/I.
Probably another bad idea. Too many things that are often
(maybe even usually) errors cannot be detected or reported
by the compiler.
And of course there's the lexical issues: should user defined
operators be delimited by periods or something else? If something
else, should period be used as the component selector for derived
types? Should enumerated types be permitted? If so, shouldn't
LOGICAL be a built-in enumeration? Should enumeration literals
be spelled distinctively? Should *they* be spelled delimited by
periods (like .true. and .false.)? Etc.
....
One that I don't see mentioned is I/O. That may or may not
be important for any particular problem.
And I left out whole-array operations. Are they simple enough?
As I mentioned before, I probably left out a whole lot of important
stuff.
--
.
- Follow-Ups:
- Re: one-liner for characater replacement
- From: glen herrmannsfeldt
- Re: one-liner for characater replacement
- From: dpb
- References:
- Re: one-liner for characater replacement
- From: analyst41
- Re: one-liner for characater replacement
- From: James Giles
- Re: one-liner for characater replacement
- From: glen herrmannsfeldt
- Prev by Date: Re: optional assumed-shape array
- Next by Date: Re: one-liner for characater replacement
- Previous by thread: Re: one-liner for characater replacement
- Next by thread: Re: one-liner for characater replacement
- Index(es): | http://coding.derkeiler.com/Archive/Fortran/comp.lang.fortran/2008-06/msg00040.html | crawl-002 | refinedweb | 881 | 56.66 |
Programming from the Ground Up
Jonathan Bartlett
Edited by
Dominick Bruno, Jr.
Programming from the Ground Up by Jonathan Bartlett Edited by Dominick Bruno, Jr. Copyright Š 2003 by Jonathan Bartlett. All trademarks are property of their respective owners..
To receive a copy of this book in electronic form, please visit the website This site contains the instructions for downloading a transparent copy of this book as defined by the GNU Free Documentation License.
Table of Contents 1.
v Welcome’t know everything, but you will have a background for how everything fits together. At the end of this book, you should be able to do the following:
1
Chapter 1. Introduction •
Understand how a program works and interacts with other programs
•
Read other people’s programs and learn how they work
•
Learn new programming languages quickly
•’s almost too much to learn almost at once, but each piece depends on all the others.
2
Chapter 1. Introduction distributions for the Power Macintosh, the Alpha processor, or other processors will not work with this book.
3
Chapter 1. Introduction 3. The GNU Project is a project by the Free Software Foundation to produce a complete, free operating system.
4
Chapter 1. Introduction system (like Microsoft Windows® or the X Window System), then the windowing system reads the keypress from the kernel, and delivers it to whatever program is currently in focus on the user’s display. Example 1-1. How the computer processes keyboard sigals.
5
Chapter 1. Introduction.
6
Chapter 2. Computer Architecture Before learning how to program, you need to first understand how a computer interprets programs. You don’t need a degree in electrical engineering, but you need to understand some basics. Modern computer architecture is based off of an architecture called the Von Neumann architecture, named after its creator. The Von Neumann architecture divides the computer up into two main parts - the CPU (for Central Processing Unit) and the memory. This architecture is used in all modern computers, including personal computers, supercomputers, mainframes, and even cell phones.
Structure of Computer Memory To understand how the computer views memory, imagine your local post office. They usually have a room filled with PO Boxes. These boxes are similar to computer memory in that each are numbered sequences of fixed-size storage locations. For example, if you have 256 megabytes of computer memory, that means that your computer contains roughly 256 million fixed-size storage locations. Or, to use our analogy, 256 million PO Boxes. Each location has a number, and each location has the same, fixed-length size. The difference between a PO Box and computer memory is that you can store all different kinds of things in a PO Box, but you can only store a single number in a computer memory storage location.
7
Chapter 2. Computer Architecture difficult and expensive to implement. The computer’s memory is used for a number of different things. All of the results of any calculations are stored in memory. In fact, everything that is "stored" is stored in memory. Think of your computer at home, and imagine what all is stored in your computer’s memory. •
The location of your cursor on the screen
•
The size of each window on the screen
•
The shape of each letter of each font being used
•
The layout of all of the controls on each window
•
The graphics for all of the toolbar icons
8
Chapter 2. Computer Architecture •
The text for each error message and dialog box
•
The list goes on and on...
In addition to all of this, the Von Neumann architecture specifies that not only computer data should live in memory, but the programs that control the computer’s operation should live there, too. In fact, in a computer, there is no difference between a program and a program’s data except how it is used by the computer. They are both stored and accessed the same way.
The CPU So how does the computer function? Obviously, simply storing data doesn’t do much help - you need to be able to access, manipulate, and move it. That’s where the CPU comes in. The CPU reads in instructions from memory one at a time and executes them. This is known as the fetch-execute cycle. The CPU contains the following elements to accomplish this: •
Program Counter
•
Instruction Decoder
•
Data bus
•
General-purpose registers
•
Arithmetic and logic unit
The program counter is used to tell the computer where to fetch the next instruction from. We mentioned earlier that there is no difference between the way data and programs are stored, they are just interpreted differently by the CPU. The program counter holds the memory address of the next instruction to be executed. The CPU begins by looking at the program counter, and fetching whatever number is stored in memory at the location specified. It is then passed on to the instruction
9
Chapter 2. Computer Architecture decoder which figures out what the instruction means. This includes what process needs to take place (addition, subtraction, multiplication, data movement, etc.) and what memory locations are going to be involved in this process. Computer instructions usually consist of both the actual instruction and the list of memory locations that are used to carry it out. Now the computer uses the data bus to fetch the memory locations to be used in the calculation. The data bus is the connection between the CPU and memory. It is the actual wire that connects them. If you look at the motherboard of the computer, the wires that go out from the memory are your data bus. In addition to the memory on the outside of the processor, the processor itself has some special, high-speed memory locations called registers. There are two kinds of registers - general registers and special-purpose registers. General-purpose registers are where the main action happens. Addition, subtraction, multiplication, comparisions, and other operations generally use general-purpose registers for processing. However, computers have very few general-purpose registers. Most information is stored in main memory, brought in to the registers for processing, and then put back into memory when the processing is completed. special-purpose registers are registers which have very specific purposes. We will discuss these as we come to them. Now that the CPU has retrieved all of the data it needs, it passes on the data and the decoded instruction to the arithmetic and logic unit for further processing. Here the instruction is actually executed. After the results of the computation have been calculated, the results are then placed on the data bus and sent to the appropriate location in memory or in a register, as specified by the instruction. This is a very simplified explanation. Processors have advanced quite a bit in recent years, and are now much more complex. Although the basic operation is still the same, it is complicated by the use of cache hierarchies, superscalar processors, pipelining, branch prediction, out-of-order execution, microcode translation, coprocessors, and other optimizations. Don’t worry if you don’t know what those words mean, you can just use them as Internet search terms if you want
10
Chapter 2. Computer Architecture to learn more about the CPU.
Some Terms Computer memory is a numbered sequence of fixed-size storage locations. The number attached to each storage location is called it’s address. The size of a single storage location is called a byte. On x86 processors, a byte is a number between 0 and 255. You may be wondering how computers can display and use text, graphics, and even large numbers when all they can do is store numbers between 0 and 255. First of all, specialized hardware like graphics cards have special interpretations of each number. When displaying to the screen, the computer uses ASCII code tables to translate the numbers you are sending it into letters to display on the screen, with each number translating to exactly one letter or numeral.1 For example, the capital letter A is represented by the number 65. The numeral 1 is represented by the number 49. So, to print out "HELLO", you would actually give the computer the sequence of numbers 72, 69, 76, 76, 79. To print out the number 100, you would give the computer the sequence of numbers 49, 48, 48. A list of ASCII characters and their numeric codes is found in Appendix D. In addition to using numbers to represent ASCII characters, you as the programmer get to make the numbers mean anything you want them to, as well. For example, if I am running a store, I would use a number to represent each item I was selling. Each number would be linked to a series of other numbers which would be the ASCII codes for what I wanted to display when the items were scanned in. I would have more numbers for the price, how many I have in inventory, and so difficult to write programs to stick bytes together to increase the size of your numbers, and requires a bit of math. Luckily, the computer will do it for us for numbers up to 4 bytes long. In fact, four-byte numbers are what we will work with by default. We mentioned earlier that in addition to the regular memory that the computer has, it also has special-purpose storage locations called registers. Registers are what the computer uses for computation. Think of a register as a place on your desk - it holds things you are currently working on. You may have lots of information tucked away in folders and drawers, but the stuff you are working on right now is on the desk. Registers keep the contents of numbers that you are currently manipulating. On the computers we are using, registers are each four bytes long. The size of a typical register is called a computer’s word size. x86 processors have four-byte words. This means that it is most natural on these computers to do computations four bytes at a time. This gives us roughly 4 billion values. Addresses are also four bytes (1 word) long, and therefore also fit into a register. x86 processors can access up to 4294967296 bytes if enough memory is installed. Notice that this means that we can store addresses the same way we store any other number. In fact, the computer can’t tell the difference between a value that is an address, a value that is a number, a value that is an ASCII code, or a value that you have decided to use for another purpose. A number becomes an ASCII code when you attempt to display it. A number becomes an address when you try to look up the byte it points to. Take a moment to think about this, because it is crucial to understanding how computer programs work. Addresses which are stored in memory are also called pointers, because instead of having a regular value in them, they point you to a different location in memory. As we’ve mentioned, computer instructions are also stored in memory. In fact,
12
Chapter 2. Computer Architecture they are stored exactly the same way that other data is stored. The only way the computer knows that a memory location is an instruction is that a special-purpose register called the instruction pointer points to them at one point or another. If the instruction pointer points to a memory word, it is loaded as an instruction. Other than that, the computer has no way of knowing the difference between programs and other types of data.2
Interpreting Memory Computers are very exact. Because they are exact, programmers have to be equally exact. A computer has no idea what your program is supposed to do. Therefore, it will only do exactly what you tell it to do. If you accidentally print out a regular number instead of the ASCII codes that make up the number’s digits, the computer will let you - and you will wind up with jibberish on your screen (it will try to look up what your number represents in ASCII and print that). If you tell the computer to start executing instructions at a location containing data instead of program instructions, who knows how the computer will interpret that but it will certainly try. The computer will execute your instructions in the exact order you specify, even if it doesn’t make sense. The point is, the computer will do exactly what you tell it, no matter how little sense it makes. Therefore, as a programmer, you need to know exactly how you have your data arranged in memory. Remember, computers can only store numbers, so letters, pictures, music, web pages, documents, and anything else are just long sequences of numbers in the computer, which particular programs know how to interpret. For example, say that you wanted to store customer information in memory. One way to do so would be to set a maximum size for the customer’s name and address - say 50 ASCII characters for each, which would be 50 bytes for each. Then, after 2. Note that here we are talking about general computer theory. Some processors and operating systems actually mark the regions of memory that can be executed with a special marker that indicates this.
13
Chapter 2. Computer Architecture that, have a number for the customer’s age and their customer id. In this case, you would have a block of memory that would look like this:
Start of Record: Customer’s name (50 bytes) - start of record Customer’s address (50 bytes) - start of record + 50 bytes Customer’s age (1 word - 4 bytes) - start of record + 100 bytes Customer’s id number (1 word - 4 bytes) - start of record + 104 byte
This way, given the address of a customer record, you know where the rest of the data lies. However, it does limit the customer’s name and address to only 50 ASCII characters each. What if we didn’t want to specify a limit? Another way to do this would be to have in our record pointers to this information. For example, instead of the customer’s name, we would have a pointer to their name. In this case, the memory would look like this: Start of Record: Customer’s name pointer (1 word) - start of record Customer’s address pointer (1 word) - start of record + 4 Customer’s age (1 word) - start of record + 8 Customer’s id number (1 word) - start of record + 12
The actual name and address would be stored elsewhere in memory. This way, it is easy to tell where each part of the data is from the start of the record, without explicitly limitting the size of the name and address. If the length of the fields within our records could change, we would have no idea where the next field started. Because records would be different sizes, it would also be hard to find where the next record began. Therefore, almost all records are of fixed lengths. Variable-length data is usually store separately from the rest of the record.
14
Chapter 2. Computer Architecture
Data Accessing Methods Processors have a number of different ways of accessing data, known as addressing modes. The simplest mode is immediate mode, in which the data to access is embedded in the instruction itself. For example, if we want to initialize a register to 0, instead of giving the computer an address to read the 0 from, we would specify immediate mode, and give it the number 0. In the register addressing mode, the instruction contains a register to access, rather than a memory location. The rest of the modes will deal with addresses. In the direct addressing mode, the instruction contains the memory address to access. For example, I could say, please load this register with the data at address 2002. The computer would go directly to byte number 2002 and copy the contents into our register. In the indexed addressing mode, the instruction contains a memory address to access, and also specifies an index register to offset that address. For example, we could specify address 2002 and an index register. If the index register contains the number 4, the actual address the data is loaded from would be 2006. This way, if you have a set of numbers starting at location 2002, you can cycle between each of them using an index register. On x86 processors, you can also specify a multiplier for the index. This allows you to access memory a byte at a time or a word at a time (4 bytes). If you are accessing an entire word, your index will need to be multiplied by 4 to get the exact location of the fourth element from your address. For example, if you wanted to access the fourth byte from location 2002, you would load your index register with 3 (remember, we start counting at 0) and set the multiplier to 1 since you are going a byte at a time. This would get you location 2005. However, if you wanted to access the fourth word from location 2002, you would load your index register with 3 and set the multiplier to 4. This would load from location 2014 - the fourth word. Take the time to calculate these yourself to make sure you understand how it works. In the indirect addressing mode, the instruction contains a register that contains a pointer to where the data should be accessed. For example, if we used indirect
15
Chapter 2. Computer Architecture addressing mode and specified the %eax register, and the %eax register contained the value 4, whatever value was at memory location 4 would be used. In direct addressing, we would just load the value 4, but in indirect addressing, we use 4 as the address to use to find the data we want. Finally, there is the base pointer addressing mode. This is similar to indirect addressing, but you also include a number called the offset to add to the register’s value before using it for lookup. We will use this mode quite a bit in this book. In the Section called Interpreting Memory we discussed having a structure in memory holding customer information. Let’s say we wanted to access the customer’s age, which was the eighth byte of the data, and we had the address of the start of the structure in a register. We could use base pointer addressing and specify the register as the base pointer, and 8 as our offset. This is a lot like indexed addressing, with the difference that the offset is constant and the pointer is held in a register, and in indexed addressing the offset is in a register and the pointer is constant. There are other forms of addressing, but these are the most important ones.
Review Know the Concepts?
16
Chapter 2. Computer Architecture.
17
Chapter 2. Computer Architecture •
Research and then describe the tradeoffs between fixed-length instructions and variable-length instructions.
18
Chapter 3. Your First Programs. #PURPOSE: # #
Simple program that exits and returns a status code back to the Linux kernel
#INPUT: #
none
#OUTPUT: # # # #
returns a status code. by typing
This can be viewed
echo $?
19
Chapter 3. Your First Programs # #
after running the program
#VARIABLES: # %eax holds the system call number # file into a machine-readable one. To assembly the program type in the command as exit.s -o exit.o as is the command which runs the assembler, exit.s is the source file, and -o exit.o tells the assemble to put it’s2. You’ll notice when you type this command, the only thing that happens is that you’ll go to the next line..
21
Chapter 3. Your First Programs: •
The purpose of the code
•
An overview of the processing involved
•
Anything strange your program does and why it does it3
After the comments, the next line says.
22
Chapter 3. Your First Programs it’s.
23
Chapter 3. Your First Programs
24
Chapter 3. Your First Programs4 (all of which can be used with movl):.5 Some of these registers,’s help. Normal programs can’t8,.
27
Chapter 3. Your First Programs?
28
Chapter 3. Your First Programs: • %edi
will hold the current position in the list.
• %ebx
will hold the current highest value in the list.
• :
29
Chapter 3. Your First Programs 1. Check the current list element (%eax) to see if it’s zero (the terminating element). 2. If it is zero, exit. 3. Increase the current position (%edi). 4. Load the next value in the list into the current value register (%eax). What addressing mode might we use here? Why? 5. Compare the current value (%eax) with the current highest value (%ebx). 6. If the current value is greater than the current highest value, replace the current highest value with the current value. 7. Repeat. That is the procedure. Many times in that procedure I made use of the word "if". These places are where decisions are to be made. You see, the computer doesn’t compute
30
Chapter 3. Your First Programs’t’s.
31
Chapter 3. Your First Programs #VARIABLES: The registers have the following uses: # # %edi - Holds the index of the data item being examined # %ebx - Largest data item found # %eax - Current data item # # The following memory locations are used: # # data_items - contains the item data. A 0 is used # to terminate the data # .section .data data_items: #These are the data items .long 3,67,34,222,45,75,54,34,44,33,22,11,66,0 .section .text .globl _start _start: movl $0, %edi # move 0 into the index register movl data_items(,%edi,4), %eax # load the first byte of data movl %eax, %ebx # since this is the first item, %eax is # the biggest start_loop: cmpl $0, %eax je loop_exit incl %edi movl data_items(,%edi,4), cmpl %ebx, %eax jle start_loop movl %eax, %ebx
32
# start loop # check to see if we’ve hit the end # load next value %eax # compare values # jump to loop beginning if the new # one isn’t bigger # move the value as the largest
Chapter 3. Your First Programs jmp start_loop
loop_exit: # %ebx is the status code for the exit system call # and it already has the maximum number movl $1, %eax #1 is the exit() syscall int $0x80
Now, assemble and link it with these commands: as maximum.s -o maximum.o ld maximum.o -o maximum
Now run it, and check it’s’s the end of the characters). Letters and numbers that start with a backslash represent characters that are not typeable on the keyboard or easily viewable on the screen. For example, \n refers to the "newline" character which causes the 9. Note that no numbers in assembly language (or any other computer language I’
35
Chapter 3. Your First Programs given a distinct name by the programmer. We talked about these in the previous section, but didn’t give them a name. In this program, we have several variables: •
a variable for the current maximum number found
•
a variable for which number of the list we are currently examining, called the index
•:
36
Chapter 3. Your First Programs • data_items •
is the location number of the start of our number list.
Each number is stored across 4 storage locations (because we declared it using .long)
• : movl %eax, %ebx.
37
Chapter 3. Your First Programs: •
Check to see if the current value being looked at is zero. If so, that means we are at the end of our data and should exit the loop.
•
We have to load the next value of our list.
•
We have to see if the next value is bigger than our current biggest value.
•
If it is, we have to copy it to the location we are holding the largest value in.
• end_loop location if the values that were just compared are equal (that’s what the e of je means). It uses the status register to hold the value of the last comparison. We used je, but there are many jump statements that you can use: je
Jump if the values were equal jg
Jump if the second value was greater than the first value12’ll just have to memorize such things and go on.’s test it! cmpl %ebx, %eax jle start_loop
Here we compare our current value, stored in %eax to our biggest value so far, stored in %ebx. If the current value is less or equal to our biggest value so far, we don’t 13. The names of these symbols can be anything you want them to be, as long as they only contain letters and the underscore character(_). The only one that is forced is _start, and possibly others that you declare with .globl. However, if its a symbol you define and only you use, feel free to call it anything you want that is adequately descriptive (remember that others will have to modify your code later, and will have to figure out what your symbols mean).
40
Chapter 3. Your First Programs:
41
Chapter 3. Your First Programs’s.
44
Chapter 3. Your First Programs
Layout of the %eax register For a more comprehensive list of instructions, see Appendix B.
Review Know the Concepts •
What does if mean if a line in the program starts with the ’#’ character?
•
What is the difference between an assembly language file and an object code file?
•
What does the linker do?
•
How do you check the result status code of the last program you ran?
•
What is the difference between movl $1, %eax and movl 1, %eax?
45
Chapter 3. Your First Programs •
Which register holds the system call number?
•
What are indexes used for?
•
Why do indexes usually start at 0?
•
If I issued the command movl data_items(,%edi,4), %eax and data_items was address 3634 and %edi held the value 13, what address would you be using to move into %eax?
•
List the general-purpose registers.
•
What is the difference between movl and movb?
•
What is flow control?
•
What does a conditional jump do?
•
What things do you have to plan for when writing a program?
•
Go through every instruction and list what addressing mode is being used for each operand.
Use the Concepts •
Modify the first program to return the value 3.
•
Modify the maximum program to find the minimum instead.
•
Modify the maximum program to use the number 255 to end the list rather than the number 0
•
Modify the maximum program to use an ending address rather than the number 0 to know when to stop.
•
Modify the maximum program to use a length count rather than the number 0 to know when to stop.
46
Chapter 3. Your First Programs •
What would the instruction movl _start, %eax do? Be specific, based on your knowledge of both addressing modes and the meaning of _start. How would this differ from the instruction movl $_start, %eax?
Going Further •
Modify the first program to leave off the int instruction line. Assemble, link, and execute the new program. What error message do you get. Why do you think this might be?
•
So far, we have discussed three approaches to finding the end of the list - using a special number, using the ending address, and using the length count. Which approach do you think is best? Why? Which approach would you use if you knew that the list was sorted? Why?
47
Chapter 3. Your First Programs
48
Chapter 4. All About Functions Dealing with Complexity In Chapter 3, the programs we wrote only consisted of one section of code. However, if we wrote real programs like that, it would be impossible to maintain them. It would be really difficult to get multiple people working on the project, as any change in one part might adversely affect another part that another developer is working on. To assist programmers in working together in groups, it is necessary to break programs apart into separate pieces, which communicate with each other through well-defined interfaces. This way, each piece can be developed and tested independently of the others, making it easier for multiple programmers to work on the project. Programmers use functions to break their programs into pieces which can be independently developed and tested. Functions are units of code that do a defined piece of work on specified types of data. For example, in a word processor program, I may have a function called handle_typed_character which is activated whenever a user types in a key. The data the function uses would probably be the keypress itself and the document the user currently has open. The function would then modify the document according to the keypress it was told about. The data items a function is given to process are called it’s parameters. In the word processing example, the key which was pressed and the document would be considered parameters to the handle_typed_characters function. The parameter list and the processing expectations of a function (what it is expected to do with the parameters) are called the function’s interface. Much care goes into designing function interfaces, because if they are called from many places within a project, it is difficult to change them if necessary. A typical program is composed of hundreds or thousands of functions, each with a
49
Chapter 4. All About Functions small, well-defined task to perform. However, ultimately there are things that you cannot write functions for which must be provided by the system. Those are called primitive functions (or just primitives) - they are the basics which everything else is built off of. For example, imagine a program that draws a graphical user interface. There has to be a function to create the menus. That function probably calls other functions to write text, to write icons, to paint the background, calculate where the mouse pointer is, etc. However, ultimately, they will reach a set of primitives provided by the operating system to do basic line or point drawing. Programming can either be viewed as breaking a large program down into smaller pieces until you get to the primitive functions, or incrementally building functions on top of primitives until you get the large picture in focus. In assembly language, the primitives are usually the same thing as the system calls, even though system calls aren’t true functions as we will talk about in this chapter.
How Functions Work Functions are composed of several different pieces: function name A function’s name is a symbol that represents the address where the function’s code starts. In assembly language, the symbol is defined by typing the the function’s name as a label before the function’s code. This is just like labels you have used for jumping. function parameters A function’s parameters are the data items that are explicitly given to the function for processing. For example, in mathematics, there is a sine function. If you were to ask a computer to find the sine of 2, sine would be the function’s name, and 2 would be the parameter. Some functions have
50
Chapter 4. All About Functions many parameters, others have none.1 local variables Local variables are data storage that a function uses while processing that is thrown away when it returns. It’s kind of like a scratch pad of paper. Functions get a new piece of paper every time they are activated, and they have to throw it away when they are finished processing. Local variables of a function are not accessible to any other function within a program. static variables Static variables are data storage that a function uses while processing that is not thrown away afterwards, but is reused for every time the function’s file it is working on in a global variable so it doesn’t have to be passed to every function that operates on it.2 Configuration values are also often stored in global variables. return address The return address is an "invisible" parameter in that it isn’t directly used during the function. The return address is a parameter which tells the function 1. files. Each function would then have to be modified so that the file that was being manipulated would be passed as a parameter. If you had simply passed it as a parameter to begin with, most of your functions could have survived your upgrade unchanged.
51
Chapter 4. All About Functions where to resume executing after the function is completed. This is needed because functions can be called to do processing from many different parts of your program, and the function needs to be able to get back to wherever it was called from. In most programming languages, this parameter is passed automatically when the function is called. In assembly language, the language’s calling convention, because it describes how functions expect to get and receive data when they are called.3 Assembly language can use any calling convention it wants to. You can even make one up yourself. However, if you want to interoperate with functions written in other languages, you have to obey their calling conventions. We will use the calling convention of the C programming language for our examples because it is the most widely used, and because it is the standard for Linux platforms. 3. A convention is a way of doing things that is standardized, but not forcibly so. For example, it is a convention for people to shake hands when they meet. If I refuse to shake hands with you, you may think I don’t like you. Following conventions is important because it makes it easier for others to understand what you are doing, and makes it easier for programs written by multiple independent authors to work together.
52
Chapter 4. All About Functions
Assembly-Language Functions using the C Calling Convention You cannot write assembly-language functions without understanding how the computer’s stack works. Each computer program that runs uses a region of memory called the stack to enable functions to work properly. Think of a stack as a pile of papers on your desk which can be added to indefinitely. You generally keep the things that you are working on toward the top, and you take things off as you are finished working with them. Your computer has a stack, too. The computer’s stack lives at the very top addresses of memory. You can push values onto the top of the stack through an instruction called pushl, which pushes either a register or memory value onto the top of the stack. Well, we say it’s the top, but the "top" of the stack is actually the bottom of the stack’s memory. Although this is confusing, the reason for it is that when we think of a stack of anything - dishes, papers, etc. - we think of adding and removing to the top of it. However, in memory the stack starts at the top of memory and grows downward due to architectural considerations. Therefore, when we refer to the "top of the stack" remember it’s at the bottom of the stack’s memory. You can also pop values off the top using an instruction called popl. This removes the top value from the stack and places it into a register or memory location of your choosing.. When we push a value onto the stack, the top of the stack moves to accomodate the additional value. We can actually continually push values onto the stack and it will keep growing further and further down in memory until we hit our code or data. So how do we know where the current "top" of the stack is? The stack register, %esp, always contains a pointer to the current top of the stack, wherever it is. Every time we push something onto the stack with pushl, %esp gets subtracted by 4 so that it points to the new top of the stack (remember, each word is four bytes long, and the stack grows downward). If we want to remove something from the stack, we simply use the popl instruction, which adds 4 to %esp and puts the previous top value in whatever register you specified. pushl and popl each take
If we were to just do this: function’s local variables, parameters, and return address. Before executing a function, a program pushes all of the parameters for the function onto the stack in the reverse order that they are documented. Then the program issues a call instruction indicating which function it wishes to start. The call instruction does two things. First it pushes the address of the next instruction, which is the return address, onto the stack. Then it modifies the instruction pointer (%eip) to point to the start of the function. So, at the time the function starts, the stack looks like this (the "top" of the stack is at the bottom on
54
Chapter 4. All About Functions this example): Parameter #N ... Parameter 2 Parameter 1 Return Address <--- (%esp)
Each of the parameters of the function have been pushed onto the stack, and finally the return address is there. Now the function itself has some work to do. The first fixed. Let’s This way, we can use the stack for variable storage without worring about clobbering them with pushes that we may make for function calls. Also, since it is allocated on the stack frame for this function call, the variable will only be alive during this function. When we return, the stack frame will go away, and so will these variables. That’s specifically it’s wouldn it’s don’t need the values of the parameters anymore).5
Destruction of Registers When function’s paramters. You can then pop them back off in reverse order after popping off the parameters. Even if you know a function does not overwrite a register you should save it, because future versions of that function may. Other languages’ calling conventions may be different. For example, other calling conventions may place the burden on the function to save any registers it uses. Be sure to check to make sure the calling conventions of your languages are compatible before trying to mix languages. Or in the case of assembly language, be sure you know how to call the other language’s functions. them.
Extended Specification: Details of the C language calling convention (also known as the ABI, or Application Binary Interface) is available online. We have oversimplified and left out several important pieces to make this simpler for new programmers. For full details, you should check out the documents available at Specifically, you should 5. This is not always strictly needed unless you are saving registers on the stack before a function call. The base pointer keeps the stack frame in a reasonably consistent state. However, it is still a good idea, and is absolutely necessary if you are temporarily saving registers on the stack..
58
Chapter 4. All About Functions look for the System V Application Binary Interface - Intel386 Architecture Processor Supplement.
A Function Example Let’s file power.s. #PURPOSE: # # #
Program to illustrate how functions work This program will compute the value of 2^3 + 5^2
#Everything in the main program is stored in registers, #so the data section doesn’t have anything. .section .data .section .text .globl _start _start: pushl $3 pushl $2 call power addl $8, %esp
#push #push #call #move
second argument first argument the function the stack pointer back
59
Chapter 4. All About Functions pushl %eax
#save the first answer before #calling the next function
pushl pushl call addl
$2 $5 power $8, %esp
#push #push #call #move
popl
%ebx
#The second answer is already #in %eax. We saved the #first answer onto the stack, #so now we can just pop it #out into %ebx
addl
%eax, %ebx
#add them together #the result is in %ebx
movl int
$1, %eax $0x80
#exit (%ebx is returned)
second argument first argument the function the stack pointer back
60
Chapter 4. All About Functions # # # # # .type power: pushl movl subl
-4(%ebp) - holds the current result %eax is used for temporary storage power, @function %ebp %esp, %ebp $4, %esp
#save old base pointer #make stack pointer the base pointer #get room for our local storage
movl movl
8(%ebp), %ebx #put first argument in %eax 12(%ebp), %ecx #put second argument in %ecx
movl
%ebx, -4(%ebp) #store current result
power_loop_start: cmpl $1, %ecx #if the power is 1, we are done je end_power movl -4(%ebp), %eax #move the current result into %eax imull %ebx, %eax #multiply the current result by #the base number movl %eax, -4(%ebp) #store the current result decl Type in the program, assemble it, and run it. Try calling power for different values, but remember that the result has to be less than 256 when it is passed back to the operating system. Also try subtracting the results of the two computations. Try adding a third call to the power function, and add it’s result back in. The main program code is pretty simple. You push the arguments onto the stack, call the function, and then move the stack pointer back. The result is stored in %eax. Note that between the two calls to power, we save the first value onto the stack. This is because the only register that is guaranteed to be saved is %ebp. Therefore we push the value onto the stack, and pop the value back off after the second function call is complete. Let’s look at how the function itself is written. Notice that before the function, there is documentation as to what the function does, what it’s arguments are, and what it gives as a return value. This is useful for programmers who use this function. This is the function’s file, it would work just the same with this left out. However, it is good practice. After that, we define the value of the power label: power:
As mentioned previously, this defines
At this point, our stack looks like this: Base Number Power Return Address Old %ebp Current result
<--<--<--<--<---
12(%ebp) 8(%ebp) 4(%ebp) (%ebp) -4(%ebp) and (%esp)
Although we could use a register for temporary storage, this program uses a local variable in order to show how to set it up. Often times there just aren’t enough registers to store everything, so you have to offload them into local variables. Other times, your function will need to call another function and send it a pointer to some of your data. You can’t doesn’t work at first, try going through your program by hand with a
63
Chapter 4. All About Functions scrap of paper, keeping track of where %ebp and %esp are pointing, what is on the stack, and what the values are in each register.
Recursive Functions The next program will stretch your brains even more. The program will compute the factorial of a number. A factorial is the product of a number and all the numbers between it and one. For example, the factorial of 7 is 7*6*5*4*3*2*1, and the factorial of 4 is 4*3*2*1. Now, one thing you might notice is that the factorial of a number is the same as the product of a number and the factorial just below it. For example, the factorial of 4 is 4 times the factorial of 3. The factorial of 3 is 3 times the factorial of 2. 2 is 2 times the factorial of 1. The factorial of 1 is 1. This type of definition is called a recursive definition. That means, the definition of the factorial function includes the factorial funtion itself. However, since all functions need to end, a recursive definition must include a base case. The base case is the point where recursion will stop. Without a base case, the function would go on forever calling itself until it eventually ran out of stack space. In the case of the factorial, the base case is the number 1. When we hit the number 1, we don’t run the factorial again, we just say that the factorial of 1 is 1. So, let’s didn’t have local variables. In other programs, storing values in global variables worked fine.. Let’s look at the code to see how this works: #PURPOSE - Given a number, this program computes the # factorial. For example, the factorial of # 3 is 3 * 2 * 1, or 6. The factorial of # 4 is 4 * 3 * 2 * 1, or 24, and so on. # #This program shows how to call a function recursively. .section .data #This program has no global data .section .text .globl _start .globl factorial #this is unneeded unless we want to share #this function among other programs _start: pushl $4 #The factorial takes one argument - the #number we want a factorial of. So, it #gets pushed call factorial #run the factorial function addl $4, %esp #Scrubs the parameter that was pushed on #the stack movl %eax, %ebx #factorial returns the answer in %eax, but #we want it in %ebx to send it as our exit #status 6. By "running at the same time" I am talking about the fact that one will not have finished before a new one is activated. I am not implying that their instructions are running at the same time.
65
Chapter 4. All About Functions movl int
$1, %eax $0x80
#call the kernel’s exit function
is our base #case, and we simply return (1 is #already in %eax as the return value) je end_factorial decl %eax #otherwise, decrease the value pushl %eax #push it for our call to factorial call factorial #call factorial movl 8(%ebp), %ebx #%eax has the return value, so we #reload our parameter into %ebx imull %ebx, %eax #multiply that by the result of the #last call to factorial (in %eax) #the answer is stored in %eax, which #is good since that’s where return #values go. end_factorial: movl %ebp, %esp #standard function return stuff - we popl %ebp #have to restore %ebp and %esp to where #they were before the function started ret #return to the function (this pops the
66
Chapter 4. All About Functions #return value, too)
Assemble, link, and run it with these commands: as factorial.s -o factorial.o ld factorial.o -o factorial ./factorial echo $?
This should give you the value 24. 24 is the factorial of 4, you can test it out yourself with a calculator: 4 * 3 * 2 * 1 = 24. I’m guessing you didn’t understand the whole code listing. Let’s function’s
Chapter 4. All About Functions int
$0x80
This takes place after factorial has finished. What’s in %eax? It is factorial’s program’s exit status be stored in %ebx, not %eax, so we have to move it. Then we do the standard exit system call. The nice thing about function calls is that: •
Other programmers don’t have to know anything about them except it’s arguments to use them.
•
They provide standardized building blocks from which you can form a program.
•. Let’s now take a look at how the factorial function itself is implemented. Before the function starts, we have this directive: .type factorial,@function factorial:
68
Chapter 4. All About Functions The .type directive tells the linker that factorial is a function. This isn’t really needed unless we were using factorial in other programs. We have included it for completeness. The line that says factorial: gives the symbol factorial the storage location of the next instruction. That’s how call knew where to go when we said call factorial. The first first parameter of the function into %eax. Remember, (%ebp) has the old %ebp, 4(%ebp) has the return address, and 8(%ebp) is the location of the first parameter to the function. If you think back, this will be the value 4 on the first call, since that was what we pushed on the stack before calling the function (with pushl $4). parameter into %eax. As this function calls itself, it will have other values, too. Next, we check to see if we’ve hit our base case (a parameter of 1). If so, we jump to the instruction at the label end_factorial, where it will be returned. Et’s already in %eax which we mentioned earlier is where you put return values. That is accomplished by these lines: cmpl $1, %eax je end_factorial
If it’s not our base case, what did we say we would do? We would call the factorial function again with our parameter minus one. So, first we decrease %eax by one:
69
Chapter 4. All About Functions decl %eax decl stands for decrement. It subtracts 1 from the given register or memory location (%eax in our case). incl is the inverse - it adds 1. After decrementing %eax we push it onto the stack since it’s going to be the parameter of the next function call. And then we call factorial again! pushl %eax call factorial
Okay, now we’ve called factorial. One thing to remember is that after a function call, we can never know what the registers are (except %esp and %ebp). So even though we had the value we were called with in %eax, it’s not there any more. Therefore, we need pull it off the stack from the same place we got it the first
Now we’re already to return, so we issue the following command
70
Chapter 4. All About Functions ret
This pops the top value off of the stack, and then jumps to it. If you remember our discussion about call, we said that call first don’t understand. Then, take a piece of paper, and go through the program step-by-step, keeping track of what the values of the registers are at each step, and what values are on the stack. Doing this should deepen your understanding of what is going on.
Review Know the Concepts •
What are primitives?
•
What are calling conventions?
•
What is the stack?
•
How do pushl and popl affect the stack? What special-purpose register do they affect?
•
What are local variables and what are they used for?
•
Why are local variables so necessary in recursive functions?
•
What are %ebp and %esp used for?
•
What is a stack frame?
71
Chapter 4. All About Functions
Use the Concepts •
Write a function called square which receives one argument and returns the square of that argument.
•
Write a program to test your square function.
• program’s exit status code.
•
Explain the problems that would arise without a standard calling convention.
Going Further •
Do you think it’s better for a system to have a large set of primitives or a small one, assuming that the larger set can be written in terms of the smaller one?
•
The factorial function can be written non-recursively. Do so.
•
Find an application on the computer you use regularly. Try to locate a specific feature, and practice breaking that feature out into functions. Define the function interfaces between that feature and the rest of the program.
•.
•
Can you build a calling convention without using the stack? What limitations might it have?
72
Chapter 4. All About Functions •
What test cases should we use in our example program to check to see if it is working properly?
73
Chapter 4. All About Functions
74
Chapter 5. Dealing with Files A lot of computer programming deals with files. After all, when we reboot our computers, the only thing that remains from previous sessions are the things that have been put on disk. Data which is stored in files is called persistent data, because it persists in files that remain on the disk even when the program isn’t running..
The UNIX File Concept Each operating system has it’s own way of dealing with files. However, the UNIX method, which is used on Linux, is the simplest and most universal. UNIX files, no matter what program created them, can all be accessed as a sequential stream of bytes. When you access a file, you start by opening it by name. The operating system then gives you a number, called a file descriptor, which you use to refer to the file until you are through with it. You can then read and write to the file using its file descriptor. When you are done reading and writing, you then close the file, which then makes the file descriptor useless. In our programs we will deal with files in the following ways: 1. Tell Linux the name of the file to open, and in what mode you want it opened (read, write, both read and write, create it if it doesn’t exist, etc.). This is handled with the open system call, which takes a filename, a number representing the mode, and a permission set as its parameters. %eax will hold the system call number, which is 5. The address of the first character of the filename should be stored in %ebx. The read/write intentions, represented as a number, should be stored in %ecx. For now, use 0 for files you want to read from, and 03101 for files you want to write to (you must include the leading zero).1 Finally, the permission set should be stored as a number in %edx. If 1. This will be explained in more detail in the Section called Truth, Falsehood, and Binary Numbers in Chapter 10.
75
Chapter 5. Dealing with Files you are unfamiliar with UNIX permissions, just use 0666 for the permissions (again, you must include the leading zero). 2. Linux will then return to you a file descriptor in %eax. Remember, this is a number that you use to refer to this file throughout your program. 3. Next you will operate on the file doing reads and/or writes, each time giving Linux the file descriptor you want to use. read is system call 3, and to call it you need to have the file descriptor in %ebx, the address of a buffer for storing the data that is read in %ecx, and the size of the buffer in %edx. Buffers will be explained in the Section called Buffers and .bss. read will return with either the number of characters read from the file, or an error code. Error codes can be distinguished because they are always negative numbers (more information on negative numbers can be found in Chapter 10). write is system call 4, and it requires the same parameters as the read system call, except that the buffer should already be filled with the data to write out. The write system call will give back the number of bytes written in %eax or an error code. 4. When you are through with your files, you can then tell Linux to close them. Afterwards, your file descriptor is no longer valid. This is done using close, system call 6. The only parameter to close is the file descriptor, which is placed in %ebx
Buffers and .bss In the previous section we mentioned buffers without explaining what they were. A buffer is a continuous block of bytes used for bulk data transfer. When you request to read a file, the operating system needs to have a place to store the data it reads. That place is called a buffer. Usually buffers are only used to store data temporarily, and it is then read from the buffers and converted to a form that is easier for the programs to handle. Our programs won’t be complicated enough to need that done. For an example, let’s say that you want to read in a single line of text from a file but you do not know how long that line is. You would then simply
76
Chapter 5. Dealing with Files read a large number of bytes/characters from the file into a buffer, look for the end-of-line character, and copy all of the characters to that end-of-line character to another location. If you didn’t find and end-of-line character, you would allocate another buffer and continue reading. You would probably wind up with some characters left over in your buffer in this case, which you would use as the starting point when you next need data from the file.2 Another thing to note is that buffers are a fixed size, set by the programmer. So, if you want to read in data 500 bytes at a time, you send the read system call the address of a 500-byte unused location, and send it the number 500 so it knows how big it is. You can make it smaller or bigger, depending on your application’s needs. To create a buffer, you need to either reserve static or dynamic storage. Static storage is what we have talked about so far, storage locations declared using .long or .byte directives. Dynamic storage will be discussed in the Section called Getting More Memory in Chapter 9. There are problems, though, with declaring buffers using .byte. First, it is tedious to type. You would have to type 500 numbers after the .byte declaration, and they wouldn’t be used for anything but to take up space. Second, it uses up space in the executable. In the examples we’ve used so far, it doesn’t use up too much, but that can change in larger programs. If you want 500 bytes you have to type in 500 numbers and it wastes 500 bytes in the executable. There is a solution to both of these. So far, we have discussed two program sections, the .text and the .data sections. There is another section called the .bss. This section is like the data section, except that it doesn’t take up space in the executable. This section can reserve storage, but it can’t initialize it. In the .data section, you could reserve storage and set it to an initial value. In the .bss section, you can’t set an initial value. This is useful for buffers because we don’t need to initialize them anyway, we just need to reserve storage. In order to do this, we do the following commands: .section .bss 2. While this sounds complicated, most of the time in programming you will not need to deal directly with buffers and file descriptors. In Chapter 8 you will learn how to use existing code present in Linux to handle most of the complications of file input/output for you.
77
Chapter 5. Dealing with Files .lcomm my_buffer, 500
This directive, .lcomm, will create a symbol, my_buffer, that refers to a 500-byte storage location that we can use as a buffer. We can then do the following, assuming we have opened a file for reading and have placed the file descriptor in %ebx: movl movl movl int
$my_buffer, %ecx 500, %edx 3, %eax $0x80
This will read up to 500 bytes into our buffer. In this example, I placed a dollar sign in front of my_buffer. Remember that the reason for this is that without the dollar sign, my_buffer is treated as a memory location, and is accessed in direct addressing mode. The dollar sign switches it to immediate mode addressing, which actually loads the number represented by my_buffer (i.e. - the address of the start of our buffer). (which is the address of my_buffer) itself into %ecx.
Standard and Special Files You might think that programs start without any files open by default. This is not true. Linux programs usually have at least three open file descriptors when they begin. They are: STDIN This is the standard input. It is a read-only file, and usually represents your keyboard.3 This is always file descriptor 0. 3. As we mentioned earlier, in Linux, almost everything is a "file". Your keyboard input is considered a file, and so is your screen display.
78
Chapter 5. Dealing with Files STDOUT This is the standard output. It is a write-only file, and usually represents your screen display. This is always file descriptor 1. STDERR This is your standard error. It is a write-only file, and usually represents your screen display. Most regular processing output goes to STDOUT, but any error messages that come up in the process go to STDERR. This way, if you want to, you can split them up into separate places. This is always file descriptor 2. Any of these "files" can be redirected from or to a real file, rather than a screen or a keyboard. This is outside the scope of this book, but any good book on the UNIX command-line will describe it in detail. The program itself does not even need to be aware of this indirection - it can just use the standard file descriptors as usual. Notice that many of the files you write to aren’t files at all. UNIX-based operating systems treat all input/output systems as files. Network connections are treated as files, your serial port is treated like a file, even your audio devices are treated as files. Communication between processes is usually done through special files called pipes. Some of these files have different methods of opening and creating them than regular files (i.e. - they don’t use the open system call), but they can all be read from and written to using the standard read and write system calls.
Using Files in a Program We are going to write a simple program to illustrate these concepts. The program will take two files, and read from one, convert all of its lower-case letters to upper-case, and write to the other file. Before we do so, let’s think about what we need to do to get the job done: •
Have a function that takes a block of memory and converts it to upper-case. This function would need an address of a block of memory and its size as
79
Chapter 5. Dealing with Files parameters. Have a section of code that repeatedly reads in to a buffer, calls our conversion function on the buffer, and then writes the buffer back out to the other file.
•
•
Begin the program by opening the necessary files.
Notice that I’ve specified things in reverse order that they will be done. That’s a useful trick in writing complex programs - first decide the meat of what is being done. In this case, it’s converting blocks of characters to upper-case. Then, you think about what all needs to be setup and processed to get that to happen. In this case, you have to open files, and continually read and write blocks to disk. One of the keys of programming is continually breaking down problems into smaller and smaller chunks until it’s small enough that you can easily solve the problem. Then you can build these chunks back up until you have a working program.4 You may have been thinking that you will never remember all of these numbers being thrown at you - the system call numbers, the interrupt number, etc. In this program we will also introduce a new directive, .equ which should help out. .equ allows you to assign names to numbers. For example, if you did .equ LINUX_SYSCALL, 0x80, any time after that you wrote LINUX_SYSCALL, the assembler would substitue 0x80 for that. So now, you can write int $LINUX_SYSCALL
which is much easier to read, and much easier to remember. Coding is complex, but there are a lot of things we can do like this to make it easier. Here is the program. Note that we have more labels than we actually use for jumps, because some of them are just there for clarity. Try to trace through the program and see what happens in various cases. An in-depth explanation of the program will follow. #PURPOSE:
This program converts an input file
4. Maureen Sprankle’s Problem Solving and Programming Concepts is an excellent book on the problem-solving process applied to computer programming.
80
Chapter 5. Dealing with Files # # # #PROCESSING: # # # # # # #
to an output file with all letters converted to uppercase. 1) Open the input file 2) Open the output file 4) While we’re not at the end of the input file a) read part of file into our memory buffer b) go through each byte of memory if the byte is a lower-case letter, convert it to uppercase c) write the memory buffer to output file
.section .data #######CONSTANTS######## #system call numbers .equ SYS_OPEN, 5 .equ SYS_WRITE, 4 .equ SYS_READ, 3 .equ SYS_CLOSE, 6 .equ SYS_EXIT, 1 #options for open (look at #/usr/include/asm/fcntl.h for #various values. You can combine them #by adding them or ORing them) #This is discussed at greater length #in "Counting Like a Computer" .equ O_RDONLY, 0 .equ O_CREAT_WRONLY_TRUNC, 03101 #standard file descriptors .equ STDIN, 0 .equ STDOUT, 1
81
Chapter 5. Dealing with Files .equ STDERR, 2 #system call interrupt .equ LINUX_SYSCALL, 0x80 .equ END_OF_FILE, 0
#This is the return value #of read which means we’ve #hit the end of the file
.equ NUMBER_ARGUMENTS, 2 .section .bss #Buffer - this is where the data is loaded into # from the data file and written from # into the output file. This should # never exceed 16,000 for various # reasons. .equ BUFFER_SIZE, 500 .lcomm BUFFER_DATA, BUFFER_SIZE .section .text #STACK POSITIONS .equ ST_SIZE_RESERVE, 8 .equ ST_FD_IN, -4 .equ ST_FD_OUT, -8 .equ ST_ARGC, 0 #Number of arguments .equ ST_ARGV_0, 4 #Name of program .equ ST_ARGV_1, 8 #Input file name .equ ST_ARGV_2, 12 #Output file name .globl _start _start: ###INITIALIZE PROGRAM### #save the stack pointer
82
Chapter 5. Dealing with Files movl
%esp, %ebp
#Allocate space for our file descriptors #on the stack subl $ST_SIZE_RESERVE, %esp open_files: open_fd_in: ###OPEN INPUT FILE### #open syscall movl $SYS_OPEN, %eax #input filename into %ebx movl ST_ARGV_1(%ebp), %ebx #read-only flag movl $O_RDONLY, %ecx #this doesn’t really matter for reading movl $0666, %edx #call Linux int $LINUX_SYSCALL store_fd_in: #save the given file descriptor movl %eax, ST_FD_IN(%ebp) open_fd_out: ###OPEN OUTPUT FILE### #open the file movl $SYS_OPEN, %eax #output filename into %ebx movl ST_ARGV_2(%ebp), %ebx #flags for writing to the file movl $O_CREAT_WRONLY_TRUNC, %ecx #mode for new file (if it’s created) movl $0666, %edx #call Linux
83
Chapter 5. Dealing with Files int
$LINUX_SYSCALL
store_fd_out: #store the file descriptor here movl %eax, ST_FD_OUT(%ebp) ###BEGIN MAIN LOOP### read_loop_begin: ###READ IN A BLOCK FROM THE INPUT FILE### movl $SYS_READ, %eax #get the input file descriptor movl ST_FD_IN(%ebp), %ebx #the location to read into movl $BUFFER_DATA, %ecx #the size of the buffer movl $BUFFER_SIZE, %edx #Size of buffer read is returned in %eax int $LINUX_SYSCALL ###EXIT IF WE’VE REACHED THE END### #check for end of file marker cmpl $END_OF_FILE, %eax #if found or on error, go to the end jle end_loop continue_read_loop: ###CONVERT THE BLOCK TO UPPER CASE### pushl $BUFFER_DATA #location of buffer pushl %eax #size of the buffer call convert_to_upper popl %eax #get the size back addl $4, %esp #restore %esp ###WRITE THE BLOCK OUT TO THE OUTPUT FILE###
84
Chapter 5. Dealing with Files #size of the buffer movl %eax, %edx movl $SYS_WRITE, %eax #file to use movl ST_FD_OUT(%ebp), %ebx #location of the buffer movl $BUFFER_DATA, %ecx int $LINUX_SYSCALL ###CONTINUE THE LOOP### jmp read_loop_begin end_loop: ###CLOSE THE FILES### #NOTE - we don’t need to do error checking # on these, because error conditions # don’t signify anything special here movl $SYS_CLOSE, %eax movl ST_FD_OUT(%ebp), %ebx int $LINUX_SYSCALL movl movl int
$SYS_CLOSE, %eax ST_FD_IN(%ebp), %ebx $LINUX_SYSCALL
###EXIT### movl $SYS_EXIT, %eax movl $0, %ebx int $LINUX_SYSCALL
#PURPOSE: # # #INPUT:
This function actually does the conversion to upper case for a block The first parameter is the location
85
Chapter 5. Dealing with Files # # # # #OUTPUT: # # #VARIABLES: # # # # # #
of the block of memory to convert The second parameter is the length of that buffer This function overwrites the current buffer with the upper-casified version.
%eax - beginning of buffer %ebx - length of buffer %edi - current buffer offset %cl - current byte being examined (first part of %ecx)
###CONSTANTS## #The lower boundary of our search .equ LOWERCASE_A, ’a’ #The upper boundary of our search .equ LOWERCASE_Z, ’z’ #Conversion between upper and lower case .equ UPPER_CONVERSION, ’A’ - ’a’ ###STACK STUFF### .equ ST_BUFFER_LEN, 8 #Length of buffer .equ ST_BUFFER, 12 #actual buffer convert_to_upper: pushl %ebp movl %esp, %ebp ###SET UP VARIABLES### movl ST_BUFFER(%ebp), %eax movl ST_BUFFER_LEN(%ebp), %ebx movl $0, %edi
86
Chapter 5. Dealing with Files #if a buffer with zero length was given #to us, just leave cmpl $0, %ebx je end_convert_loop convert_loop: #get the current byte movb (%eax,%edi,1), %cl #go to the next byte unless it is between #’a’ and ’z’ cmpb $LOWERCASE_A, %cl jl next_byte cmpb $LOWERCASE_Z, %cl jg next_byte #otherwise convert the byte to uppercase addb $UPPER_CONVERSION, %cl #and store it back movb %cl, (%eax,%edi,1) next_byte: incl %edi #next byte cmpl %edi, %ebx #continue unless #we’ve reached the #end jne convert_loop end_convert_loop: #no return value, just leave movl %ebp, %esp popl %ebp ret
Type in this program as toupper.s, and then enter in the following commands:
87
Chapter 5. Dealing with Files as toupper.s -o toupper.o ld toupper.o -o toupper
This builds a program called toupper, which converts all of the lowercase characters in a file to uppercase. For example, to convert the file toupper.s to uppercase, type in the following command: ./toupper toupper.s toupper.uppercase
You will now find in the file toupper.uppercase an uppercase version of your original file. Let’s examine how the program works. The first section of the program is marked CONSTANTS. In programming, a constant is a value that is assigned when a program assembles or compiles, and is never changed. I make a habit of placing all of my constants together at the beginning of the program. It’s only necessary to declare them before you use them, but putting them all at the beginning makes them easy to find. Making them all upper-case makes it obvious in your program which values are constants and where to find them.5 In assembly language, we declare constants with the .equ directive as mentioned before. Here, we simply give names to all of the standard numbers we’ve used so far, like system call numbers, the syscall interrupt number, and file open options. The next section is marked BUFFERS. We only use one buffer in this program, which we call BUFFER_DATA. We also define a constant, BUFFER_SIZE, which holds the size of the buffer. If we always refer to this constant rather than typing out the number 500 whenever we need to use the size of the buffer, if it later changes, we only need to modify this value, rather than having to go through the entire program and changing all of the values individually. Instead of going on the the _start section of the program, go to the end where we define the convert_to_upper function. This is the part that actually does the 5.
88
This is fairly standard practice among programmers in all languages.
Chapter 5. Dealing with Files conversion. This section begins with a list of constants that we will use The reason these are put here rather than at the top is that they only deal with this one function. We have these definitions: .equ .equ .equ
LOWERCASE_A, ’a’ LOWERCASE_Z, ’z’ UPPER_CONVERSION, ’A’ - ’a’
The first two simply define the letters that are the boundaries of what we are searching for. Remember that in the computer, letters are represented as numbers. Therefore, we can use LOWERCASE_A in comparisons, additions, subtractions, or anything else we can use numbers in. Also, notice we define the constant UPPER_CONVERSION. Since letters are represented as numbers, we can subtract them. Subtracting an upper-case letter from the same lower-case letter gives us how much we need to add to a lower-case letter to make it upper case. If that doesn’t make sense, look at the ASCII code tables themselves (see Appendix D). You’ll notice that the number for the character A is 65 and the character a is 97. The conversion factor is then -32. For any lowercase letter if you add -32, you will get it’s capital equivalent. After this, we have some constants labelled STACK POSITIONS. Remember that function parameters are pushed onto the stack before function calls. These constants (prefixed with ST for clarity) define where in the stack we should expect to find each piece of data. The return address is at position 4 + %esp, the length of the buffer is at position 8 + %esp, and the address of the buffer is at position 12 + %esp. Using symbols for these numbers instead of the numbers themselves makes it easier to see what data is being used and moved. Next comes the label convert_to_upper. This is the entry point of the function. The first two lines are our standard function lines to save the stack pointer. The next two lines movl
ST_BUFFER(%ebp), %eax
89
Chapter 5. Dealing with Files movl
ST_BUFFER_LEN(%ebp), %ebx
move the function parameters into the appropriate registers for use. Then, we load zero into %edi. What we are going to do is iterate through each byte of the buffer by loading from the location %eax + %edi, incrementing %edi, and repeating until %edi is equal to the buffer length stored in %ebx. The lines cmpl je
$0, %ebx end_convert_loop
are just a sanity check to make sure that noone gave us a buffer of zero size. If they did, we just clean up and leave. Guarding against potential user and programming errors is an important task of a programmer. You can always specify that your function should not take a buffer of zero size, but it’s even better to have the function check and have a reliable exit plan if it happens. Now we start our loop. First, it moves a byte into %cl. The code for this is movb
(%eax,%edi,1), %cl
It is using an indexed indirect addressing mode. It says to start at %eax and go %edi locations forward, with each location being 1 byte big. It takes the value found there, and put it in %cl. After this it checks to see if that value is in the range of lower-case a to lower-case z. To check the range, it simply checks to see if the letter is smaller than a. If it is, it can’t be a lower-case letter. Likewise, if it is larger than z, it can’t be a lower-case letter. So, in each of these cases, it simply moves on. If it is in the proper range, it then adds the uppercase conversion, and stores it back into the buffer. Either way, it then goes to the next value by incrementing %cl;. Next it checks to see if we are at the end of the buffer. If we are not at the end, we jump back to the beginning of the loop (the convert_loop label). If we are at the end, it simply continues on to the end of the function. Because we are modifying the buffer directly, we don’t need to return anything to the calling program - the changes are
90
Chapter 5. Dealing with Files already in the buffer. The label end_convert_loop is not needed, but it’s there so it’s easy to see where the parts of the program are. Now we know how the conversion process works. Now we need to figure out how to get the data in and out of the files. Before reading and writing the files we must open them. The UNIX open system call is what handles this. It takes the following parameters: •
%eax contains the system call number as usual - 5 in this case.
•
%ebx contains a pointer to a string that is the name of the file to open. The
string must be terminated with the null character. •
%ecx contains the options used for opening the file. These tell Linux how to
open the file. They can indicate things such as open for reading, open for writing, open for reading and writing, create if it doesn’t exist, delete the file if it already exists, etc. We will not go into how to create the numbers for the options until the Section called Truth, Falsehood, and Binary Numbers in Chapter 10. For now, just trust the numbers we come up with. •
%edx contains the permissions that are used to open the file. This is used in
case the file has to be created first, so Linux knows what permissions to create the file with. These are expressed in octal, just like regular UNIX permissions.6 After making the system call, the file descriptor of the newly-opened file is stored in %eax. So, what files are we opening? In this example, we will be opening the files specified aren’t familiar with UNIX permissions, just put $0666 here. Don’t forget the leading zero, as it means that the number is an octal number.
91
Chapter 5. Dealing with Files In the C Programming language, this is referred to as the argv array, so we will refer to it that way in our program. The first thing our program does is save the current stack position in %ebp and then reserve some space on the stack to store the file descriptors. After this, it starts opening files. The first file the program opens is the input file, which is the first command-line argument. We do this by setting up the system call. We put the file name into %ebx, the read-only mode number into %ecx, the default mode of $0666 into %edx, and the system call number into %eax After the system call, the file is open and the file descriptor is stored in %eax.7 The file descriptor is then transferred to it’s appropriate place on the stack. The same is then done for the output file, except that it is created with a write-only, create-if-doesn’t-exist, truncate-if-does-exist mode. Its file descriptor is stored as well. Now we get to the main part - the read/write loop. Basically, we will read fixed-size chunks of data from the input file, call our conversion function on it, and write it back to the output file. Although we are reading fixed-size chunks, the size of the chunks don’t matter for this program - we are just operating on straight sequences of characters. We could read it in with as little or as large of chunks as we want, and it still would work properly. The first part of the loop is to read the data. This uses the read system call. This call just takes a file descriptor to read from, a buffer to write into, and the size of the buffer (i.e. - the maximum number of bytes that could be written). The system call returns the number of bytes actually read, or end-of-file (the number 0). 7. Notice that we don’t do any error checking on this. That is done just to keep the program simple. In normal programs, every system call should normally be checked for success or failure. In failure cases, %eax will hold an error code instead of a return value. Error codes are negative, so they can be detected by comparing %eax to zero and jumping if it is less than zero.
92
Chapter 5. Dealing with Files After reading a block, we check %eax for an end-of-file marker. If found, it exits the loop. Otherwise we keep on going. After the data is read, the convert_to_upper function is called with the buffer we just read in and the number of characters read in the previous system call. After this function executes, the buffer should be capitalized and ready to write out. The registers are then restored with what they had before. Finally, we issue a write system call, which is exactly like the read system call, except that it moves the data from the buffer out to the file. Now we just go back to the beginning of the loop. After the loop exits (remember, it exits if, after a read, it detects the end of the file), it simply closes its file descriptors and exits. The close system call just takes the file descriptor to close in %ebx. The program is then finished!
Review Know the Concepts •
Describe the lifecycle of a file descriptor.
•
What are the standard file descriptors and what are they used for?
•
What is a buffer?
•
What is the difference between the .data section and the .bss section?
•
What are the system calls related to reading and writing files?
93
Chapter 5. Dealing with Files
Use the Concepts •
Modify the toupper program so that it reads from STDIN and writes to STDOUT instead of using the files on the command-line.
•
Change the size of the buffer.
•
Rewrite the program so that it uses storage in the .bss section rather than the stack to store the file descriptors.
•
Write a program that will create a file called heynow.txt and write the words "Hey diddle diddle!" into it.
Going Further •
What difference does the size of the buffer make?
•
What error results can be returned by each of these system calls?
•
Make the program able to either operate on command-line arguments or use STDIN or STDOUT based on the number of command-line arguments specified by ARGC.
•
Modify the program so that it checks the results of each system call, and prints out an error message to STDOUT when it occurs.
94
Chapter 6. Reading and Writing Simple Records As mentioned in Chapter 5, many applications deal with data that is persistent meaning that the data lives longer than the program by being stored on disk inf files. You can shut down the program and open it back up, and you are back where you started. Now, there are two basic kinds of persistent data - structured and unstructured. Unstructured data is like what we dealt with in the toupper program. It just dealt with text files that were entered by a person. The contents of the files weren’t usable by a program because a program can’t interpret what the user is trying to say in random text. Structured data, on the other hand, is what computers excel at handling. Structured data is data that is divided up into fields and records. For the most part, the fields and records are fixed-length. Because the data is divided into fixed-length records and fixed-format fields, the computer can interpret the data. Structured data can contain variable-length fields, but at that point you are usually better off with a database. 1 This chapter deals with reading and writing simple fixed-length records. Let’s say we wanted to store some basic information about people we know. We could imagine the following example fixed-length record about people: •
Firstname - 40 bytes
•
Lastname - 40 bytes
•
Address - 240 bytes
•
Age - 4 bytes
1. A database is a program which handles persistent structured data for you. You don’t have to write the programs to read and write the data to disk, to do lookups, or even to do basic processing. It is a very high-level interface to structured data which, although it adds some overhead and additional complexity, is very useful for complex data processing tasks. References for learning how databases work are listed in Chapter 13.
95
Chapter 6. Reading and Writing Simple Records In this, everything is character data except for the age, which is simply a numeric field, using a standard 4-byte word (we could just use a single byte for this, but keeping it at a word makes it easier to process). In programming, you often have certain definitions that you will use over and over again within the program, or perhaps within several programs. It is good to separate these out into files that are simply included into the assembly language files as needed. For example, in our next programs we will need to access the different parts of the record above. This means we need to know the offsets of each field from the beginning of the record in order to access them using base pointer addressing. The following constants describe the offsets to the above structure. Put them in a file named record-def.s: .equ .equ .equ .equ
RECORD_FIRSTNAME, 0 RECORD_LASTNAME, 40 RECORD_ADDRESS, 80 RECORD_AGE, 320
.equ RECORD_SIZE, 324
In addition, there are several constants that we have been defining over and over in our programs, and it is useful to put them in a file, so that we don’t have to keep entering them. Put the following constants in a file called linux.s: #Common Linux Definitions #System Call Numbers .equ SYS_EXIT, 1 .equ SYS_READ, 3 .equ SYS_WRITE, 4 .equ SYS_OPEN, 5 .equ SYS_CLOSE, 6 .equ SYS_BRK, 45
96
Chapter 6. Reading and Writing Simple Records #System Call Interrupt Number .equ LINUX_SYSCALL, 0x80 #Standard File Descriptors .equ STDIN, 0 .equ STDOUT, 1 .equ STDERR, 2 #Common Status Codes .equ END_OF_FILE, 0
We will write three programs in this chapter using the structure defined in record-def.s. The first program will build a file containing several records as defined above. The second program will display the records in the file. The third program will add 1 year to the age of every record. In addition to the standard constants we will be using throughout the programs, there are also two functions that we will be using in several of the programs - one which reads a record and one which writes a record. What parameters do these functions need in order to operate? We basically need: •
The location of a buffer that we can read a record into
•
The file descriptor that we want to read from or write to
Let’s look at our reading function first:
.include "record-def.s" .include "linux.s" #PURPOSE:
This function reads a record from the file
97
Chapter 6. Reading and Writing Simple Records # descriptor # #INPUT: The file descriptor and a buffer # #OUTPUT: This function writes the data to the buffer # and returns a status code. # #STACK LOCAL VARIABLES .equ ST_READ_BUFFER, 8 .equ ST_FILEDES, 12 .section .text .globl read_record .type read_record, @function read_record: pushl %ebp movl %esp, %ebp pushl movl movl movl movl int
%ebx ST_FILEDES(%ebp), %ebx ST_READ_BUFFER(%ebp), %ecx $RECORD_SIZE, %edx $SYS_READ, %eax $LINUX_SYSCALL
#NOTE - %eax has the return value, which we will # give back to our calling program popl %ebx movl popl ret
%ebp, %esp %ebp
It’s a pretty simply function. It just reads data the size of our structure into an appropriately sized buffer from the given file descriptor. The writing one is similar:
98
Chapter 6. Reading and Writing Simple Records .include "linux.s" .include "record-def.s" #PURPOSE: This function writes a record to # the given file descriptor # #INPUT: The file descriptor and a buffer # #OUTPUT: This function produces a status code # #STACK LOCAL VARIABLES .equ ST_WRITE_BUFFER, 8 .equ ST_FILEDES, 12 .section .text .globl write_record .type write_record, @function write_record: pushl %ebp movl %esp, %ebp pushl movl movl movl movl int
%ebx $SYS_WRITE, %eax ST_FILEDES(%ebp), %ebx ST_WRITE_BUFFER(%ebp), %ecx $RECORD_SIZE, %edx $LINUX_SYSCALL
#NOTE - %eax has the return value, which we will # give back to our calling program popl %ebx movl popl ret
%ebp, %esp %ebp
99
Chapter 6. Reading and Writing Simple Records Now that we have our basic definitions down, we are ready to write our programs.
Writing Records This program will simply write some hardcoded records to disk. It will: •
Open the file
•
Write three records
•
Close the file
Type the following code into a file called write-records.s: .include "linux.s" .include "record-def.s" .section .data #Constant data of the records we want to write #Each text data item is padded to the proper #length with null (i.e. 0) bytes. #.rept is used to pad each item. .rept tells #the assembler to repeat the section between #.rept and .endr the number of times specified. #This is used in this program to add extra null #characters at the end of each field to fill #it up record1: .ascii "Fredrick\0" .rept 31 #Padding to 40 bytes .byte 0 .endr .ascii "Bartlett\0"
100
Chapter 6. Reading and Writing Simple Records .rept 31 #Padding to 40 bytes .byte 0 .endr .ascii "4242 S Prairie\nTulsa, OK 55555\0" .rept 209 #Padding to 240 bytes .byte 0 .endr .long 45 record2: .ascii "Marilyn\0" .rept 32 #Padding to 40 bytes .byte 0 .endr .ascii "Taylor\0" .rept 33 #Padding to 40 bytes .byte 0 .endr .ascii "2224 S Johannan St\nChicago, IL 12345\0" .rept 203 #Padding to 240 bytes .byte 0 .endr .long 29 record3: .ascii "Derrick\0" .rept 32 #Padding to 40 bytes .byte 0 .endr
101
Chapter 6. Reading and Writing Simple Records .ascii "McIntire\0" .rept 31 #Padding to 40 bytes .byte 0 .endr .ascii "500 W Oakland\nSan Diego, CA 54321\0" .rept 206 #Padding to 240 bytes .byte 0 .endr .long 36 #This is the name of the file we will write to file_name: .ascii "test.dat\0" .equ ST_FILE_DESCRIPTOR, -4 .globl _start _start: #Copy the stack pointer to %ebp movl %esp, %ebp #Allocate space to hold the file descriptor subl $4, %esp #Open movl movl movl
movl int
the file $SYS_OPEN, %eax $file_name, %ebx $0101, %ecx #This says to create if it #doesn’t exist, and open for #writing $0666, %edx $LINUX_SYSCALL
#Store the file descriptor away movl %eax, ST_FILE_DESCRIPTOR(%ebp)
102
Chapter 6. Reading and Writing Simple Records #Write the first record pushl ST_FILE_DESCRIPTOR(%ebp) pushl $record1 call write_record addl $8, %esp #Write the second record pushl ST_FILE_DESCRIPTOR(%ebp) pushl $record2 call write_record addl $8, %esp #Write the third record pushl ST_FILE_DESCRIPTOR(%ebp) pushl $record3 call write_record addl $8, %esp #Close the file descriptor movl $SYS_CLOSE, %eax movl ST_FILE_DESCRIPTOR(%ebp), %ebx int $LINUX_SYSCALL #Exit movl movl int
the program $SYS_EXIT, %eax $0, %ebx $LINUX_SYSCALL
This is a fairly simple program. It merely consists of defining files to basically be pasted right there in the code. You don’t need to do this with functions, because the linker can take care of combining functions exported with .globl. However, constants defined in another file do need to be imported in this way. Also, you may have noticed the use of a new assembler directive, .rept. This directive repeats the contents of the file between the .rept and the .endr directives the number of times specified after .rept. This is usually used the way we used it - to pad values in the .data section. In our case, we are adding null characters to the end of each field until they are their defined lengths. To build the application, run the commands: as write-records.s -o write-record.o as write-record.s -o write-record.o ld write-record.o write-records.o -o write-records
Here we are assembling two files separately, and then combining them together using the linker. To run the program, just type the following: ./write-records
This will cause a file called test.dat to be created containing the records. However, since they contain non-printable characters (the null character, specifically), they may not be viewable by a text editor. Therefore we need the next program to read them for us.
104
Chapter 6. Reading and Writing Simple Records
Reading Records Now we will consider the process of reading records. In this program, we will read each record and display the first name listed with each record. Since each person’s name is a different length, we will need a function to count the number of characters we want to write. Since we pad each field with null characters, we can simply count characters until we reach a null character.2 Note that this means our records must contain at least one null character each. Here is the code. Put it in a file called count-chars.s: #PURPOSE: Count the characters until a null byte is reached. # #INPUT: The address of the character string # #OUTPUT: Returns the count in %eax # #PROCESS: # Registers used: # %ecx - character count # %al - current character # %edx - current character address .type count_chars, @function .globl count_chars #This is where our one parameter is on the stack .equ ST_STRING_START_ADDRESS, 8 count_chars: pushl %ebp movl %esp, %ebp #Counter starts at zero movl $0, %ecx 2.
If you have used C, this is what the strlen function does.
105
Chapter 6. Reading and Writing Simple Records #Starting address of data movl ST_STRING_START_ADDRESS(%ebp), %edx count_loop_begin: #Grab the current character movb (%edx), %al #Is it null? cmpb $0, %al #If yes, we’re done je count_loop_end #Otherwise, increment the counter and the pointer incl %ecx incl %edx #Go back to the beginning of the loop jmp count_loop_begin count_loop_end: #We’re done. Move the count into %eax #and return. movl %ecx, %eax popl ret
%ebp
As you can see, it’s a fairly straightforward function. It simply loops through the bytes, counting as it goes, until it hits a null character. Then it returns the count. Our record-reading program will be fairly straightforward, too. It will do the following: •
Open the file
•
Attempt to read a record
106
Chapter 6. Reading and Writing Simple Records •
If we are at the end of the file, exit
•
Otherwise, count the characters of the first name
•
Write the first name to STDOUT
•
Write a newline to STDOUT
•
Go back to read another record
To write this, we need one more simple function - a function to write out a newline to STDOUT. Put the following code into write-newline.s:
.include "linux.s" .globl write_newline .type write_newline, @function .section .data newline: .ascii "\n" .section .text .equ ST_FILEDES, 8 write_newline: pushl %ebp movl %esp, %ebp movl movl movl movl int movl popl ret
$SYS_WRITE, %eax ST_FILEDES(%ebp), %ebx $newline, %ecx $1, %edx $LINUX_SYSCALL %ebp, %esp %ebp
107
Chapter 6. Reading and Writing Simple Records Now we are ready to write the main program. Here is the code to read-records.s:
.include "linux.s" .include "record-def.s" .section .data file_name: .ascii "test.dat\0" .section .bss .lcomm record_buffer, RECORD_SIZE
.section .text #Main program .globl _start _start: #These are the locations on the stack where #we will store the input and output descriptors #(FYI - we could have used memory addresses in #a .data section instead) .equ ST_INPUT_DESCRIPTOR, -4 .equ ST_OUTPUT_DESCRIPTOR, -8 #Copy the stack pointer to %ebp movl %esp, %ebp #Allocate space to hold the file descriptors subl $8, %esp #Open movl movl movl
108
the file $SYS_OPEN, %eax $file_name, %ebx $0, %ecx #This says to open read-only
Chapter 6. Reading and Writing Simple Records movl int
$0666, %edx $LINUX_SYSCALL
#Save file descriptor movl
%eax, ST_INPUT_DESCRIPTOR(%ebp)
#Even though it’s a constant, we are #saving the output file descriptor in #a local variable so that if we later #decide that it isn’t always going to #be STDOUT, we can change it easily. movl $STDOUT, ST_OUTPUT_DESCRIPTOR(%ebp)
record_read_loop: finished_reading #Otherwise, print out the first name #but first, we must know it’s size pushl $RECORD_FIRSTNAME + record_buffer call count_chars addl $4, %esp
109
Chapter 6. Reading and Writing Simple Records movl movl movl movl int
%eax, %edx ST_OUTPUT_DESCRIPTOR(%ebp), %ebx $SYS_WRITE, %eax $RECORD_FIRSTNAME + record_buffer, %ecx $LINUX_SYSCALL
pushl call addl
ST_OUTPUT_DESCRIPTOR(%ebp) write_newline $4, %esp
jmp
record_read_loop
finished_reading: movl $SYS_EXIT, %eax movl $0, %ebx int $LINUX_SYSCALL first line simply means that the command continues on the next line. You can run your program by doing ./read-records. As you can see, this program opens the file and then runs a loop of reading, checking for the end of file, and writing the firstname. The one construct that might be new is the line that says: pushl
110
$RECORD_FIRSTNAME + record_buffer
Chapter 6. Reading and Writing Simple Records It looks like we are combining and add instruction with a push instruction, but we are not. You see, both RECORD_FIRSTNAME and record_buffer are constants. The first is a direct constant, created through the use of a .equ directive, while the latter is defined automatically by the assembler through its use as a label (it’s value being the address that the data that follows it will start at). Since they are both constants that the assembler knows, it is able to add them together while it is assembling your program, so the whole instruction is a single immediate-mode push of a single constant. The RECORD_FIRSTNAME constant is the number of bytes after the beginning of a record before we hit the first name. record_buffer is the name of our buffer for holding records. Adding them together gets us the address of the first name member of the record stored in record_buffer.
Modifying the Records In this section, we will write a program that: •
Opens an input and output file
•
Reads records from the input
•
Increments the age
•
Writes the new record to the output file
Like most programs we’ve encountered recently, this program is pretty straightforward.3 .include "linux.s" .include "record-def.s" 3. You will find that after learning the mechanics of programming, most programs are pretty straightforward once you know exactly what it is you want to do. Most of them initialize data, do some processing in a loop, and then clean everything up.
111
Chapter 6. Reading and Writing Simple Records .section .data input_file_name: .ascii "test.dat\0" output_file_name: .ascii "testout.dat\0"
file for reading $SYS_OPEN, %eax $input_file_name, %ebx $0, %ecx $0666, %edx $LINUX_SYSCALL
movl
%eax, ST_INPUT_DESCRIPTOR(%ebp)
#Open movl movl movl
file for writing $SYS_OPEN, %eax $output_file_name, %ebx $0101, %ecx
112
Chapter 6. Reading and Writing Simple Records movl int
$0666, %edx $LINUX_SYSCALL
movl
%eax, ST_OUTPUT_DESCRIPTOR(%ebp)
loop_begin: loop_end #Increment the age incl record_buffer + RECORD_AGE #Write the record out pushl ST_OUTPUT_DESCRIPTOR(%ebp) pushl $record_buffer call write_record addl $8, %esp jmp
loop_begin
loop_end: movl $SYS_EXIT, %eax movl $0, %ebx int $LINUX_SYSCALL
113
Chapter 6. Reading and Writing Simple Records You can type it in as add-year.s. To build it, type the following4: as add-year.s -o add-year.o ld add-year.o read-record.o write-record.o -o add-year
To run the program, just type in the following5: ./add-year
This will add a year to every record listed in test.dat and write the new records to the file testout.dat. As you can see, writing fixed-length records is pretty simple. You only have to read in blocks of data to a buffer, process them, and write them back out. Unfortunately, this program doesn’t write the new ages out to the screen so you can verify your program’s effectiveness. This is because we won’t get to displaying numbers until Chapter 8 and Chapter 10. After reading those you may want to come back and rewrite this program to display the numeric data that we are modifying.
Review Know the Concepts •
What is a record?
•
What is the advantage of fixed-length records over variable-length records?
•
How do you include constants in multiple assembly source files?
4. This assumes that you have already built the object files read-record.o and writerecord.o in the previous examples. If not, you will have to do so. 5. This is assuming you created the file in a previous run of write-records. If not, you need to run write-records first before running this program.
114
Chapter 6. Reading and Writing Simple Records •
Why might you want to split up a project into multiple source files?
•
What does the instruction incl record_buffer + RECORD_AGE do? What addressing mode is it using? How many operands does the incl instructions have in this case? Which parts are being handled by the assembler and which parts are being handled when the program is run?
Use the Concepts •
Add another data member to the person structure defined in this chapter, and rewrite the reading and writing functions and programs to take them into account. Remember to reassemble and relink your files before running your programs.
•
Create a program that uses a loop to write 30 identical records to a file.
•
Create a program to find the largest age in the file and return that age as the status code of the program.
•
Create a program to find the smallest age in the file and return that age as the status code of the program.
Going Further •
Rewrite the programs in this chapter to use command-line arguments to specify the filesnames.
•
Research the lseek system call. Rewrite the add-year program to open the source file for both reading and writing (use $2 for the read/write mode), and write the modified records back to the same file they were read from.
•. •
Write a program that will add a single record to the file by reading the data from the keyboard. Remember, you will have to make sure that the data has at least one null character at the end, and you need to have a way for the user to indicate they are done typing. Because we have not gotten into characters to numbers conversion, you will not be able to read the age in from the keyboard, so you’ll have to have a default age.
•
Write a function called compare-strings that will compare two strings up to 5 characters. Then write a program that allows the user to enter 5 characters, and have the program return all records whose first name starts with those 5 characters.
116
Chapter 7. Developing Robust Programs This: •
Programmers don’t always schedule time for meetings or other non-coding activities that make up every day.
•
Programmers often underestimate feedback times (how long it takes to pass change requests and approvals back and forth) for projects.
•
Programmers don’t always understand the full scope of what they are producing.
•
Programmers often have to estimate a schedule on a totally different kind of project than they are used to, and thus are unable to schedule accurately.
•
118
Chapter 7. Developing Robust Programs: •
The number 0
•
The number 1
119
Chapter 7. Developing Robust Programs •
A number within the expected range
•
A number outside the expected range
•
The first number in the expected range
•
The last number in the expected range
•
The first number below the expected range
• unfinished program. Since you can’t’t
123
Chapter 7. Developing Robust Programs movl movl int
with status 1 $SYS_EXIT, %eax $1, %ebx .
124
Chapter 7. Developing Robust Programs Linux returns its status code in %eax, so we need to check and see if there is an error. #Open movl movl movl movl int
file for reading $SYS_OPEN, %eax $input_file_name, %ebx $0, %ecx $0666, %edx ’t Open Input File\0" .section .text pushl $no_open_file_msg pushl $no_open_file_code call error_exit continue_processing:
125
Chapter 7. Developing Robust Programs files. It now exits cleanly and gracefully!
Review Know the Concepts •
What are the reasons programmer’s have trouble with scheduling?
•
Find your favorite program, and try to use it in a completely wrong manner. Open up files of the wrong type, choose invalid options, close windows that are supposed to be open, etc. Count how many different error scenarios they had to account for.
•
What are corner cases? Can you list examples of numeric corner cases?
•
Why is user testing so important?
•
What are stubs and drivers used for? What’s the difference between the two?
126
Chapter 7. Developing Robust Programs •
What are recovery points used for?
•
How many different error codes should a program have?
Use the Concepts •
Go through the add-year.s program and add error-checking code after every system call.
•
Find one other program we have done so far, and add error-checking to that program.
•
Add a recovery mechanism for add-year.s that allows it to read from STDIN if it cannot open the standard file.
Going Further •
What, if anything, should you do if your error-reporting function fails? Why?
•
Try to find bugs in at least one open-source program. File a bug report for it.
•
Try to fix the bug you found in the previous exercise.
127
Chapter 7. Developing Robust Programs
128
Chapter 8. Sharing Functions with Code Libraries By now you should realize that the computer has to do a lot of work even for simple tasks. Because of that, you have to do a lot of work to write the code for a computer to even do simple tasks. In addition, programming tasks are usually not very simple. Therefore, we neeed a way to make this process easier on ourselves. There are several ways to do this, including:
•
Write code in a high-level language instead of assembly language
•
Have lots of pre-written code that you can cut and paste into your own programs
•
Have a set of functions on the system that are shared among any program that wishes to use it
All three of these are usually used to some degree in any given project. The first option will be explored further in Chapter 11. The second option is useful but it suffers from some drawbacks, including: •
Code that is copied often has to be majorly modified to fit the surrounding code.
•
Every program containing the copied code has the same code in it, thus wasting a lot of space.
•
If a bug is found in any of the copied code it has to be fixed in every application program.
Therefore, the second option is usually used sparingly. It is usually only used in cases where you copy and paste skeleton code for a specific type of task, and add in your program-specific fixed within the single function library file, and all applications which use it are automatically updated. The main drawback with this approach is that it creates some dependency problems, including: •
If multiple applications are all using the shared file, how do we know when it is safe to delete the file? For example, if three applications are sharing a file of functions and 2 of the programs are deleted, how does the system know that there still exists an application that uses that code, and therefore it shouldn’t be deleted?
•
Some programs inadvertantly rely on bugs within shared functions. Therefore, if upgrading the shared program fixes a bug that a program depended on, it could cause that application to cease functioning.
These problems are what lead to what is known as "DLL hell". However, it is generally assumed that the advantages outweigh the disadvantages. In programming, these shared code files are referred to as shared libraries, shared objects, dynamic-link libraries, DLLs, or .so files. We will refer to them as shared libraries.
Using a Shared Library The program we will examine here is simple - it writes the characters hello world to the screen and exits. The regular program, helloworld-nolib.s, looks like this:
#PURPOSE: # #
This program writes the message "hello world" and exits
.include "linux.s"
130
Chapter 8. Sharing Functions with Code Libraries .section .data
helloworld: .ascii "hello world\n" helloworld_end: .equ helloworld_len, helloworld_end - helloworld .section .text .globl _start _start: movl $STDOUT, %ebx movl $helloworld, %ecx movl $helloworld_len, %edx movl $SYS_WRITE, %eax int $LINUX_SYSCALL movl movl int
$0, %ebx $SYS_EXIT, %eax $LINUX_SYSCALL
That’s not too long. However, take a look at how short helloworld-lib is which uses a library:
#PURPOSE: # #
This program writes the message "hello world" and exits
.section .data helloworld:
131
Chapter 8. Sharing Functions with Code Libraries .ascii "hello world\n\0" .section .text .globl _start _start: pushl $helloworld call printf pushl $0 call exit
It’s even shorter! Now, building programs which use shared libraries is a little different than normal. You can build the first program normally by doing this: as helloworld-nolib.s -o helloworld-nolib.o ld helloworld-nolib.o -o helloworld-nolib
However, in order to build the second program, you have to do this: as helloworld-lib.s -o helloworld-lib.o ld -dynamic-linker /lib/ld-linux.so.2 \ -o helloworld-lib helloworld-lib.o -lc
Remember, the backslash in the first line simply means that the command continues on the next line. The option -dynamic-linker /lib/ld-linux.so.2 allows our program to be linked to libraries. This builds the executable so that before executing, the operating system will load the program /lib/ld-linux.so.2 to load in external libraries and link them with the program. This program is known as a dynamic linker. The -lc option says to link to the c library, named libc.so on GNU/Linux systems. Given a library name, c in this case (usually library names are longer than a single letter), the GNU/Linux linker prepends the string lib to the beginning of
132
Chapter 8. Sharing Functions with Code Libraries the library name and appends .so to the end of it to form the library’s filename. This library contains many functions to automate all types of tasks. The two we are using are printf, which prints strings, and exit, which exits the program. Notice that the symbols printf and exit are simply referred to by name within the program. In previous chapters, the linker would resolve all of the names to physical memory addresses, and the names would be thrown away. When using dynamic linking, the name itself resides within the executable, and is resolved by the dynamic linker when it is run. When the program is run by the user, the dynamic linker loads the shared libraries listed in our link statement, and then finds all of the function and variable names that were named by our program but not found at link time, and matches them up with corresponding entries in the shared libraries it loads. It then replaces all of the names with the addresses which they are loaded at. This sounds time-consuming. It is to a small degree, but it only happens once - at program startup time.
How Shared Libraries Work In our first programs, all of the code was contained within the source file. Such programs are called statically-linked executables, because they contained all of the necessary functionality for the program that wasn’t handled by the kernel. In the programs we wrote in Chapter 6, we used both our main program file and files containing routines used by multiple programs. In these cases, we combined all of the code together using the linker at link-time, so it was still statically-linked. However, in the helloworld-lib program, we started using shared libraries. When you use shared libraries, your program is then dynamically-linked, which means that not all of the code needed to run the program is actually contained within the program file itself, but in external libraries. When we put the -lc on the command to link the helloworld program, it told the linker to use the c library (libc.so) to look up any symbols that weren’t already defined in helloworld.o. However, it doesn’t actually add any code to
133
Chapter 8. Sharing Functions with Code Libraries our program, it just notes in the program where to look. When the helloworld program begins, the file /lib/ld-linux.so.2 is loaded first. This is the dynamic linker. This looks at our helloworld program and sees that it needs the c library to run. So, it searches for a file called libc.so in the standard places (listed in /etc/ld.so.conf and in the contents of the LD_LIBRARY_PATH environment variable), then looks in it for all the needed symbols (printf and exit in this case), and then loads the library into the program’s virtual memory. Finally, it replaces all instances of printf in the program with the actual location of printf in the library. Run the following command: ldd ./helloworld-nolib
It should report back not a dynamic executable. This is just like we said helloworld-nolib is a statically-linked executable. However, try this: ldd ./helloworld-lib
It will report back something like libc.so.6 => /lib/libc.so.6 (0x4001d000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x400000000)
The numbers in parenthesis may be different on your system. This means that the program helloworld is linked to libc.so.6 (the .6 is the version number), which is found at /lib/libc.so.6, and /lib/ld-linux.so.2 is found at /lib/ld-linux.so.2. These libraries have to be loaded before the program can be run. If you are interested, run the ldd program on various programs that are on your Linux distribution, and see what libraries they rely on.
Finding Information about Libraries Okay, so now that you know about libraries, the question is, how do you find out
134
Chapter 8. Sharing Functions with Code Libraries what libraries you have on your system and what they do? Well, let’s skip that question for a minute and ask another question: How do programmers describe functions to each other in their documentation? Let’s take a look at the function printf. It’s calling interface (usually referred to as a prototype) looks like this: int printf(char *string, ...);
In Linux, functions are described in the C programming language. In fact, most Linux programs are written in C. That is why most documentation and binary compatibility is defined using the C language. The interface to the printf function above is described using the C programming language. This definition means that there is a function printf. The things inside the parenthesis are the function’s parameters or arguments. The first parameter here is char *string. This means there is a parameter named string (the name isn’t important, except to use for talking about it), which has a type char *. char means that it wants a single-byte character. The * after it means that it doesn’t actually want a character as an argument, but instead it wants the address of a character or sequence of characters. If you look back at our helloworld program, you will notice that the function call looked like this: pushl $hello call printf
So, we pushed the address of the hello string, rather than the actual characters. You might notice that we didn’t push the length of the string. The way that printf found the end of the string was because we ended it with a null character (\0). Many functions work that way, especially C language functions. The int before the function definition tell what type of value the function will return in %eax when it returns. printf will return an int when it’s through. Now, after the char *string, we have a series of periods, .... This means that it can take an indefinite number of additional arguments after the string. Most functions can only take a specified number of arguments. printf, however, can take many. It will look into the string parameter, and everywhere it sees the characters %s, it will
135
Chapter 8. Sharing Functions with Code Libraries look for another string from the stack to insert, and everywhere it sees %d it will look for a number from the stack to insert. This is best described using an example: #PURPOSE: #
This program is to demonstrate how to call printf
.section .data #This string is called the format string. It’s the first #parameter, and printf uses it to find out how many parameters #it was given, and what kind they are. firststring: .ascii "Hello! %s is a %s who loves the number %d\n\0" name: .ascii "Jonathan\0" personstring: .ascii "person\0" #This could also have been an .equ, but we decided to give it #a real memory location just for kicks numberloved: .long 3 .section .text .globl _start _start: #note that the parameters are passed in the #reverse order that they are listed in the #function’s prototype. pushl numberloved #This is the %d pushl $personstring #This is the second %s pushl $name #This is the first %s pushl $firststring #This is the format string #in the prototype call printf
136
Chapter 8. Sharing Functions with Code Libraries pushl $0 call exit
Type it in with the filename printf-example.s, and then do the following commands: as printf-example.s -o printf-example.o ld printf-example.o -o printf-example -lc \ -dynamic-linker /lib/ld-linux.so.2
Then run the program with ./printf-example, and it should say this: Hello! Jonathan is a person who loves the number 3
Now, if you look at the code, you’ll see that we actually push the format string last, even though it’s the first parameter listed. You always push a functions parameters in reverse order.1 You may be wondering how the printf function knows how many parameters there are. Well, it searches through your string, and counts how many %ds and %ss it finds, and then grabs that number of parameters from the stack. If the parameter matches a %d, it treats it as a number, and if it matches a %s, it treats it as a pointer to a null-terminated string. printf has many more features than this, but these are the most-used ones. So, as you can see, printf can make output a lot easier, but it also has a lot of overhead, because it has to count the number of characters in the string, look through it for all of the control characters it needs to replace, pull them off the stack, convert them to a 1. The reason that parameters are pushed in the reverse order is because of functions which take a variable number of parameters like printf. The parameters pushed in last will be in a known position relative to the top of the stack. The program can then use these parameters to determine where on the stack the additional arguments are, and what type they are. For example, printf uses the format string to determine how many other parameters are being sent. If we pushed the known arguments first, you wouldn’t be able to tell where they were on the stack.
137
Chapter 8. Sharing Functions with Code Libraries suitable representation (numbers have to be converted to strings, etc), and stick them all together appropriately. We’ve seen how to use the C programming language prototypes to call library functions. To use them effectively, however, you need to know several more of the possible data types for reading functions. Here are the main ones: int
An int is an integer number (4 bytes on x86 processor). long
A long is also an integer number (4 bytes on an x86 processor). long long
A long long is an integer number that’s larger than a long (8 bytes on an x86 processor). short
A short is an integer number that’s shorter than an int (2 bytes on an x86 processor). char
A char is a single-byte integer number. This is mostly used for storing character data, since ASCII strings usually are represented with one byte per character. float
A float is a floating-point number (4 bytes on an x86 processor). Floating-point numbers will be explained in more depth in the Section called Floating-point Numbers in Chapter 10.
138
Chapter 8. Sharing Functions with Code Libraries double
A double is a floating-point number that is larger than a float (8 bytes on an x86 processor). unsigned unsigned is a modifier used for any of the above types which keeps them from being used as signed quantities. The difference between signed and unsigned numbers will be discussed in Chapter 10. *
An asterisk (*) is used to denote that the data isn’t an actual value, but instead is a pointer to a location holding the given value (4 bytes on an x86 processor). So, let’s say in memory location my_location you have the number 20 stored. If the prototype said to pass an int, you would use direct addressing mode and do pushl my_location. However, if the prototype said to pass an int *, you would do pushl $my_location - an immediate mode push of the address that the value resides in. In addition to indicating the address of a single value, pointers can also be used to pass a sequence of consecutive locations, starting with the one pointed to by the given value. This is called an array. struct
A struct is a set of data items that have been put together under a name. For example you could declare: struct teststruct { int a; char *b; };
and any time you ran into struct teststruct you would know that it is actually two words right next to each other, the first being an integer, and the second a pointer to a character or group of characters. You never see structs
139
Chapter 8. Sharing Functions with Code Libraries passed as arguments to functions. Instead, you usually see pointers to structs passed as arguments. This is because passing structs to functions is fairly complicated, since they can take up so many storage locations. typedef
A typedef basically allows you to rename a type. For example, I can do typedef int myowntype; in a C program, and any time I typed myowntype, it would be just as if I typed int. This can get kind of annoying, because you have to look up what all of the typedefs and structs in a function prototype really mean. However, typedefs are useful for giving types more meaningful and descriptive names. Compatibility Note: The listed sizes are for intel-compatible (x86) machines. Other machines will have different sizes. Also, even when parameters shorter than a word are passed to functions, they are passed as longs on the stack.
That’s how to read function documentation. Now, let’s get back to the question of how to find out about libraries. Most of your system libraries are in /usr/lib or /lib. If you want to just see what symbols they define, just run objdump -R FILENAME where FILENAME is the full path to the library. The output of that isn’t too helpful, though, for finding an interface that you might need. Usually, you have to know what library you want at the beginning, and then just read the documentation. Most libraries have manuals or man pages for their functions. The web is the best source of documentation for libraries. Most libraries from the GNU project also have info pages on them, which are a little more thorough than man pages.
140
Chapter 8. Sharing Functions with Code Libraries
Useful Functions Several useful functions you will want to be aware of from the c library include: • size_t strlen (const char *s)
calculates the size of null-terminated
strings. • int strcmp (const char *s1, const char *s2)
compares two strings
alphabetically. takes the pointer to a string, and creates a new copy in a new location, and returns the new location.
• char * strdup (const char *s)
• FILE * fopen (const char *filename, const char *opentype)
opens a managed, buffered file (allows easier reading and writing than using file descriptors directly).23 • int fclose (FILE *stream)
closes a file opened with fopen.
• char * fgets (char *s, int count, FILE *stream)
fetches a line of
characters into string s. • int fputs (const char *s, FILE *stream)
writes a string to the given
open file. is just like printf, but it uses an open file rather than defaulting to using standard output.
• int fprintf (FILE *stream, const char *template, ...)
You can find the complete manual on this library by going to 2. stdin, stdout, and stderr (all lower case) can be used in these programs to refer to the files of their corresponding file descriptors. 3. FILE is a struct. You don’t need to know it’s contents to use it. You only have to store the pointer and pass it to the relevant other functions.
141
Chapter 8. Sharing Functions with Code Libraries
Building a Shared Library Let’s say that we wanted to take all of our shared code from Chapter 6 and build it into a shared library to use in our programs. The first thing we would do is assemble them like normal: as write-record.s -o write-record.o as read-record.s -o read-record.o
Now, instead of linking them into a program, we want to link them into a shared library. This changes our linker command to this: ld -shared write-record.o read-record.o -o librecord.so
This links both of these files together into a shared library called librecord.so. This file can now be used for multiple programs. If we need to update the functions contained within it, we can just update this one file and not have to worry about which programs use it. Let’s look at how we would link against this library. To link the write-records program, we would do the following: as write-records.s -o write-records ld -L . -dynamic-linker /lib/ld-linux.so.2 \ -o write-records -lrecord write-records.o
In this command, -L . told the linker to look for libraries in the current directory (it usually only searches /lib directory, /usr/lib directory, and a few others). As we’ve seen, the option -dynamic-linker /lib/ld-linux.so.2 specified the dynamic linker. The option -lrecord tells the linker to search for functions in the file named librecord.so. Now the write-records program is built, but it will not run. If we try it, we will get an error like the following: ./write-records: error while loading shared libraries:
142
Chapter 8. Sharing Functions with Code Libraries librecord.so: cannot open shared object file: No such file or directory
This is because, by default, the dynamic linker only searches /lib, /usr/lib, and whatever directories are listed in /etc/ld.so.conf for libraries. In order to run the program, you either need to move the library to one of these directories, or execute the following command: LD_LIBRARY_PATH=. export LD_LIBRARY_PATH
Alternatively, if that gives you an error, do this instead: setenv LD_LIBRARY_PATH .
Now, you can run write-records normally by typing ./write-records. Setting LD_LIBRARY_PATH tells the linker to add whatever paths you give it to the library search path for dynamic libraries For further information about dynamic linking, see the following sources on the Internet: •
The man page for ld.so contains a lot of information about how the Linux dynamic linker works.
• is a great presentation on dynamic linking in Linux.
• and provide a good introduction to the ELF file format, with more detail available at
• contains a great description of how dynamic linking works with ELF files.
143
Chapter 8. Sharing Functions with Code Libraries
Review Know the Concepts •
What are the advantages and disadvantages of shared libraries?
•
Given a library named ’foo’, what would the library’s filename be?
•
What does the ldd command do?
•
Let’s say we had the files foo.o and bar.o, and you wanted to link them together, and dynamically link them to the library ’kramer’. What would the linking command be to generate the final executable?
•
What is typedef for?
•
What are structs for?
•
What is the difference between a data element of type int and int *? How would you access them differently in your program?
•
If you had a object file called foo.o, what would be the command to create a shared library called ’bar’?
•
What is the purpose of LD_LIBRARY_PATH?
Use the Concepts •
Rewrite one or more of the programs from the previous chapters to print their results to the screen using printf rather than returning the result as the exit status code. Also, make the exit status code be 0.
•
Use the factorial function you developed in the Section called Recursive Functions in Chapter 4 to make a shared library. Then re-write the main program so that it links with the library dynamically.
144
Chapter 8. Sharing Functions with Code Libraries •
Rewrite the program above so that it also links with the ’c’ library. Use the ’c’ library’s printf function to display the result of the factorial call.
•
Rewrite the toupper program so that it uses the c library functions for files rather than system calls.
Going Further •
Make a list of all the environment variables used by the GNU/Linux dynamic linker.
•
Research the different types of executable file formats in use today and in the history of computing. Tell the strengths and weaknesses of each.
•
What kinds of programming are you interested in (graphics, databbases, science, etc.)? Find a library for working in that area, and write a program that makes some basic use of that library.
•
Research the use of LD_PRELOAD. What is it used for? Try building a shared library that contained the exit function, and have it write a message to STDERR before exitting. Use LD_PRELOAD and run various programs with it. What are the results?
145
Chapter 8. Sharing Functions with Code Libraries
146
Chapter 9. Intermediate Memory Topics How a Computer Views Memory Let’s review how memory within a computer works. You may also want to re-read Chapter 2. A computer looks at memory as a long sequence of numbered storage locations. A sequence of millions of numbered storage locations. Everything is stored in these locations. Your programs are stored there, your data is stored there, everything. Each storage location looks like every other one. The locations holding your program are just like the ones holding your data. In fact, the computer has no idea which are which, except that the executable file tells it where to start executing. These storage locations are called bytes. The computer can combine up to four of them together into a single word. Normally numeric data is operated on a word at a time. As we mentioned, instructions are also stored in this same memory. Each instruction is a different length. Most instructions take up one or two storage locations for the instruction itself, and then storage locations for the instruction’s arguments. For example, the instruction movl data_items(,%edi,4), %ebx
takes up 7 storage locations. The first two hold the instruction, the third one tells which registers to use, and the next four hold the storage location of data_items. In memory, instructions look just like all the other numbers, and the instructions themselves can be moved into and out of registers just like numbers, because that’s what they are. This chapter is focused on the details of computer memory. To get started let’s review some basic terms that we will be using in this chapter:
147
Chapter 9. Intermediate Memory Topics Byte This is the size of a storage location. On x86 processors, a byte can hold numbers between 0 and 255. Word This is the size of a normal register. On x86 processors, a word is four bytes long. Most computer operations handle a word at a time. Address An address is a number that refers to a byte in memory. For example, the first byte on a computer has an address of 0, the second has an address of 1, and so on.1 Every piece of data on the computer not in a register has an address. The address of data which spans several bytes is the same as the address of its first byte. Normally, we don’t ever type the numeric address of anything, but we let the assembler do it for us. When we use labels in code, the symbol used in the label will be equivalent to the address it is labelling. The assembler will then replace that symbol with its address wherever you use it in your program. For example, say you have the following code: .section .data my_data: .long 2, 3, 4
Now, any time in the program that my_data is used, it will be replaced by the address of the first value of the .long directive.
Pointer A pointer is a register or memory word whose value is an address. In our programs we use %ebp as a pointer to the current stack frame. All base 1.
148
You actually never use addresses this low, but it works for discussion.
Chapter 9. Intermediate Memory Topics pointer addressing involves pointers. Programming uses a lot of pointers, so it’s an important concept to grasp.
The Memory Layout of a Linux Program When you program is loaded into memory, each .section is loaded into its own region of memory. All of the code and data declared in each section is brought together, even if they were separated in your source code. The actual instructions (the .text section) are loaded at the address 0x08048000 (numbers starting with 0x are in hexadecimal, which will be discussed in Chapter 10). The .data section is loaded immediately after that, followed by the .bss section. The last byte that can be addressed on Linux is location 0xbfffffff. Linux starts the stack here and grows it downward toward the other sections. Between them is a huge gap. The initial layout of the stack is as follows: At the bottom of the stack (the bottom of the stack is the top address of memory - see Chapter 4), there is a word of memory that is zero. After that comes the null-terminated name of the program using ASCII characters. After the program name comes the program’s environment variables (these are not important to us in this book). Then come the program’s command-line arguments. These are the values that the user typed in on the command line to run this program. When we run as, for example, we give it several arguments - as, sourcefile.s, -o, and objectfile.o. After these, we have the number of arguments that were used. When the program begins, this is where the stack pointer, %esp, is pointing. Further pushes on the stack move %esp down in memory. For example, the instruction pushl %eax
is equivalent to movl %eax, (%esp)
149
Chapter 9. Intermediate Memory Topics subl $4, %esp
Likewise, the instruction popl %eax
is the same as movl (%esp), %eax addl $4, %esp
Your program’s data region starts at the bottom of memory and goes up. The stack starts at the top of memory, and moves downward with each push. This middle part between the stack and your program’s data sections is inaccessible memory you are not allowed to access it until you tell the kernel that you need it.2 If you try, you will get an error (the error message is usually "segmentation fault"). The same will happen if you try to access data before the beginning of your program, 0x08048000. The last accessible memory address to your program is called the system break (also called the current break or just the break). 2. The stack can access it as it grows downward, and you can access the stack regions through %esp. However, your program’s data section doesn’t grow that way. The way to grow that will be explained shortly.
150
Chapter 9. Intermediate Memory Topics
Memory Layout of a Linux Program at Startup
Every Memory Address is a Lie So, why does the computer not allow you to access memory in the break area? To answer this question, we will have to delve into the depths of how your computer really handles memory. You may have wondered, since every program gets loaded into the same place in
151
Chapter 9. Intermediate Memory Topics memory, don’t they step on each other, or overwrite each other? It would seem so. However, as a program writer, you only access virtual memory. Physical memory refers to the actual RAM chips inside your computer and what they contain. It’s usually between 16 and 512 Megabytes on modern computers. If we talk about a physical memory address, we are talking about where exactly on these chips a piece of memory is located. Virtual memory is the way your program thinks about memory. Before loading your program, Linux finds an empty physical memory space large enough to fit your program, and then tells the processor to pretend that this memory is actually at the address 0x0804800 to load your program into. Confused yet? Let me explain further. Each program gets its own sandbox to play in. Every program running on your computer thinks that it was loaded at memory address 0x0804800, and that it’s stack starts at 0xbffffff. When Linux loads a program, it finds a section of unused memory, and then tells the processor to use that section of memory as the address 0x0804800 for this program. The address that a program believes it uses is called the virtual address, while the actual address on the chips that it refers to is called the physical address. The process of assigning virtual addresses to physical addresses is called mapping. Earlier we talked about the inaccessible memory between the .bss and the stack, but we didn’t talk about why it was there. The reason is that this region of virtual memory addresses hasn’t been mapped onto physical memory addresses. The mapping process takes up considerable time and space, so if every possible virtual address of every possible program were mapped, you would not have enough physical memory to even run one program. So, the break is the beginning of the area that contains unmapped memory. With the stack, however, Linux will automatically map in memory that is accessed from stack pushes. Of course, this is a very simplified view of virtual memory. The full concept is much more advanced. For example, Virtual memory can be mapped to more than just physical memory; it can be mapped to disk as well. Swap partitions on Linux allow Linux’s virtual memory system to map memory not only to physical RAM,
152
Chapter 9. Intermediate Memory Topics but also to disk blocks as well. For example, let’s say you only have 16 Megabytes of physical memory. Let’s also say that 8 Megabytes are being used by Linux and some basic applications, and you want to run a program that requires 20 Megabytes of memory. Can you? The answer is yes, but only if you have set up a swap partition. What happens is that after all of your remaining 8 Megabytes of physical memory have been mapped into virtual memory, Linux starts mapping parts of your application’s virtual memory to disk blocks. So, if you access a "memory" location in your program, that location may not actually be in memory at all, but on disk. As the programmer you won’t know the difference, though, because it is all handled behind the scenes by Linux. Now, x86 processors cannot run instructions directly from disk, nor can they access data directly from disk. This requires the help of the operating system. When you try to access memory that is mapped to disk, the processor notices that it can’t service your memory request directly. It then asks Linux to step in. Linux notices that the memory is actually on disk. Therefore, it moves some data that is currently in memory onto disk to make room, and then moves the memory being accessed from the disk back into physical memory. It then adjusts the processor’s virtual-to-physical memory lookup tables so that it can find the memory in the new location. Finally, Linux returns control to the program and restarts it at the instruction which was trying to access the data in the first place. This instruction can now be completed successfully, because the memory is now in physical RAM.3 Here is an overview of the way memory accesses are handled under Linux: •
The program tries to load memory from a virtual address.
•
The processor, using tables supplied by Linux, transforms the virtual memory address into a physical memory address on the fly.
3. Note that not only can Linux have a virtual address map to a different physical address, it can also move those mappings around as needed.
153
Chapter 9. Intermediate Memory Topics •
If the processor does not have a physical address listed for the memory address, it sends a request to Linux to load it.
•
Linux looks at the address. If it is mapped to a disk location, it continues on to the next step. Otherwise, it terminates the program with a segmentation fault error.
•
If there is not enough room to load the memory from disk, Linux will move another part of the program or another program onto disk to make room.
•
Linux then moves the data into a free physical memory address.
•
Linux updates the processor’s virtual-to-physical memory mapping tables to reflect the changes.
•
Linux restores control to the program, causing it to re-issue the instruction which caused this process to happen.
•
The processor can now handle the instruction using the newly-loaded memory and translation tables.
It’s a lot of work for the operating system, but it gives the user and the programmer great flexibility when it comes to memory management. Now, in order to make the process more efficient, memory is separated out into groups called pages. When running Linux on x86 processors, a page is 4096 bytes of memory. All of the memory mappings are done a page at a time. Physical memory assignment, swapping, mapping, etc. are all done to memory pages instead of individual memory addresses. What this means to you as a programmer is that whenever you are programming, you should try to keep most memory accesses within the same basic range of memory, so you will only need a page or two of memory at a time. Otherwise, Linux may have to keep moving pages on and off of disk to satisfy your memory needs. Disk access is slow, so this can really slow down your program. Sometimes so many programs can be loaded that there is hardly enough physical memory for them. They wind up spending more time just swapping memory on
154
Chapter 9. Intermediate Memory Topics and off of disk than they do actually processing it. This leads to a condition called swap death which leads to your system being unresponsive and unproductive. It’s usually usually recoverable if you start terminating your memory-hungry programs, but it’s a pain. Resident Set Size: The amount of memory that your program currently has in physical memory is called it’s resident set size, and can be viewed by using the program top. The resident set size is listed under the column labelled "RSS".
Getting More Memory We now know that Linux maps all of our virtual memory into physical memory or swap. If you try to access a piece of virtual memory that hasn’t been mapped yet, it triggers an error known as a segmentation fault, which will terminate your program. The program break point, if you remember, is the last valid address you can use. Now, this is all great if you know beforehand how much storage you will need. You can just add all the memory you need to your .data or .bss sections, and it will all be there. However, let’s say you don’t know how much memory you will need. For example, with a text editor, you don’t know how long the person’s file will be. You could try to find a maximum file size, and just tell the user that they can’t go beyond that, but that’s a waste if the file is small. Therefore Linux has a facility to move the break point to accomodate an application’s memory needs. If you need more memory, you can just tell Linux where you want the new break point to be, and Linux will map all the memory you need between the current and new break point, and then move the break point to the spot you specify. That memory is now available for your program to use. The way we tell Linux to move the break point is through the brk system call. The brk system call is call number
155
Chapter 9. Intermediate Memory Topics 45 (which will be in %eax). %ebx should be loaded with the requested breakpoint. Then you call int $0x80 to signal Linux to do its work. After mapping in your memory, Linux will return the new break point in %eax. The new break point might actually be larger than what you asked for, because Linux rounds up to the nearest page. If there is not enough physical memory or swap to fulfill your request, Linux will return a zero in %eax. Also, if you call brk with a zero in %ebx, it will simply return the last usable memory address. The problem with this method is keeping track of the memory we request. Let’s say I need to move the break to have room to load a file, and then need to move a break again to load another file. Let’s say I then get rid of the first file. You now have a giant gap in memory that’s mapped, but that you aren’t using. If you continue to move the break in this way for each file you load, you can easily run out of memory. So, what is needed is a memory manager. A memory manager is a set of routines that takes care of the dirty work of getting your program memory for you. Most memory managers have two basic functions - allocate and deallocate.4 Whenever you need a certain amount of memory, you can simply tell allocate how much you need, and it will give you back an address to the memory. When you’re done with it, you tell deallocate that you are through with it. allocate will then be able to reuse the memory. This pattern of memory management is called dynamic memory allocation. This minimizes the number of "holes" in your memory, making sure that you are making the best use of it you can. The pool of memory used by memory managers is commonly referred to as the heap. The way memory managers work is that they keep track of where the system break is, and where the memory that you have allocated is. They mark each block of memory in the heap as being used or unused. When you request memory, the memory manager checks to see if there are any unused blocks of the appropriate size. If not, it calls the brk system call to request more memory. When you free 4. The function names usually aren.
A Simple Memory Manager Here I will show you a simple memory manager. It is very primitive but it shows the principles quite well. As usual, I will give you the program first for you to look through. Afterwards will follow an in-depth explanation. It looks long, but it is mostly comments. #PURPOSE: Program to manage memory usage - allocates # and deallocates memory as requested # #NOTES: The programs using these routines will ask # for a certain size of memory. We actually # use more than that size, but we put it # at the beginning, before the pointer # we hand back. We add a size field and # an AVAILABLE/UNAVAILABLE marker. So, the # memory looks like this # # ######################################################### # #Available Marker#Size of memory#Actual memory locations# # ######################################################### # ^--Returned pointer # points here # The pointer we return only points to the actual # locations requested to make it easier for the # calling program. It also allows us to change our # structure without the calling program having to # change at all. .section .data
157
Chapter 9. Intermediate Memory Topics #######GLOBAL VARIABLES######## #This points to the beginning of the memory we are managing heap_begin: .long 0 #This points to one location past the memory we are managing current_break: .long 0
######STRUCTURE INFORMATION#### #size of space for memory region header .equ HEADER_SIZE, 8 #Location of the "available" flag in the header .equ HDR_AVAIL_OFFSET, 0 #Location of the size field in the header .equ HDR_SIZE_OFFSET, 4
###########CONSTANTS########### .equ UNAVAILABLE, 0 #This is the number we will use to mark #space that has been given out .equ AVAILABLE, 1 #This is the number we will use to mark #space that has been returned, and is #available for giving .equ SYS_BRK, 45 #system call number for the break #system call .equ LINUX_SYSCALL, 0x80 #make system calls easier to read
.section .text
158
Chapter 9. Intermediate Memory Topics
##########FUNCTIONS############ ##allocate_init## #PURPOSE: call this function to initialize the # functions (specifically, this sets heap_begin and # current_break). This has no parameters and no # return value. .globl allocate_init .type allocate_init,@function allocate_init: pushl %ebp #standard function stuff movl %esp, %ebp #If the brk system call is called with 0 in %ebx, it #returns the last valid usable address movl $SYS_BRK, %eax #find out where the break is movl $0, %ebx int $LINUX_SYSCALL incl
%eax
#%eax now has the last valid #address, and we want the #memory location after that
movl
%eax, current_break
#store the current break
movl
%eax, heap_begin
#store the current break as our #first address. This will cause #the allocate function to get #more memory from Linux the #first time it is run
movl popl
%ebp, %esp %ebp
#exit the function
159
Chapter 9. Intermediate Memory Topics ret #####END OF FUNCTION#######
##allocate## #PURPOSE: This function is used to grab a section of # memory. It checks to see if there are any # free blocks, and, if not, it asks Linux # for a new one. # #PARAMETERS: This function has one parameter - the size # of the memory block we want to allocate # #RETURN VALUE: # This function returns the address of the # allocated memory in %eax. If there is no # memory available, it will return 0 in %eax # ######PROCESSING######## #Variables used: # # %ecx - hold the size of the requested memory # (first/only parameter) # %eax - current memory region being examined # %ebx - current break position # %edx - size of current memory region # #We scan through each memory region starting with #heap_begin. We look at the size of each one, and if #it has been allocated. If it’s big enough for the #requested size, and its available, it grabs that one. #If it does not find a region large enough, it asks #Linux for more memory. In that case, it moves #current_break up
160
Chapter 9. Intermediate Memory Topics .globl allocate .type allocate,@function .equ ST_MEM_SIZE, 8 #stack position of the memory size #to allocate allocate: pushl %ebp #standard function stuff movl %esp, %ebp movl
ST_MEM_SIZE(%ebp), %ecx #%ecx will hold the size #we are looking for (which is the first #and only parameter)
movl
heap_begin, %eax
#%eax will hold the current #search location
movl
current_break, %ebx
#%ebx will hold the current #break
alloc_loop_begin:
cmpl je
%ebx, %eax move_break
#here we iterate through each #memory region #need more memory if these are equal
Chapter 9. Intermediate Memory Topics next_location: addl $HEADER_SIZE, %eax #The total size of the memory addl %edx, %eax #region is the sum of the size #requested (currently stored #in %edx), plus another 8 bytes #for the header (4 for the #AVAILABLE/UNAVAILABLE flag, #and 4 for the size of the #region). So, adding %edx and $8 #to %eax will get the address #of the next memory region jmp
alloc_loop_begin
allocate_here:
#go look at the next location #if we’ve made it here, #that means that the #region header of the region #to allocate is in %eax
#mark space as unavailable movl $UNAVAILABLE, HDR_AVAIL_OFFSET(%eax) addl $HEADER_SIZE, %eax #move %eax past the header to #the usable memory (since #that’s what we return) movl popl ret
%ebp, %esp %ebp
move_break:
162
#return from the function
#if we’ve made it here, that #means that we have exhausted #all addressable memory, and #we need to ask for more. #%ebx holds the current
Chapter 9. Intermediate Memory Topics #endpoint of the data, #and %ecx holds its size
addl addl
#we need to increase %ebx to #where we _want_ memory #to end, so we $HEADER_SIZE, %ebx #add space for the headers #structure %ecx, %ebx #add space to the break for #the data requested #now its time to ask Linux #for more memory
pushl %eax pushl %ecx pushl %ebx
#save needed registers
movl
$SYS_BRK, %eax
#reset the break (%ebx has #the requested break point)
int
$LINUX_SYSCALL #under normal conditions, this should #return the new break in %eax, which #will be either 0 if it fails, or #it will be equal to or larger than #we asked for. We don’t care #in this program where it actually #sets the break, so as long as %eax #isn’t 0, we don’t care what it is
cmpl je
$0, %eax error
#check for error conditions
popl popl
%ebx %ecx
#restore saved registers
163
Chapter 9. Intermediate Memory Topics popl
%eax
#set this memory as unavailable, since we’re about to #give it away movl $UNAVAILABLE, HDR_AVAIL_OFFSET(%eax) #set the size of the memory movl %ecx, HDR_SIZE_OFFSET(%eax) #move %eax to the actual start of usable memory. #%eax now holds the return value addl $HEADER_SIZE, %eax movl
%ebx, current_break
#save the new break
movl popl ret
%ebp, %esp %ebp
#return the function
error: movl $0, %eax #on error, we return zero movl %ebp, %esp popl %ebp ret ########END OF FUNCTION########
##deallocate## #PURPOSE: # The purpose of this function is to give back # a region of memory to the pool after we’re done # using it. # #PARAMETERS: # The only parameter is the address of the memory # we want to return to the memory pool.
164
Chapter 9. Intermediate Memory Topics # #RETURN VALUE: # There is no return value # #PROCESSING: # If you remember, we actually hand the program the # start of the memory that they can use, which is # 8 storage locations after the actual start of the # memory region. All we have to do is go back # 8 locations and mark that memory as available, # so that the allocate function knows it can use it. .globl deallocate .type deallocate,@function #stack position of the memory region to free .equ ST_MEMORY_SEG, 4 deallocate: #since the function is so simple, we #don’t need any of the fancy function stuff #get the address of the memory to free #(normally this is 8(%ebp), but since #we didn’t push %ebp or move %esp to #%ebp, we can just do 4(%esp) movl ST_MEMORY_SEG(%esp), %eax
#get the pointer to the real beginning of the memory subl $HEADER_SIZE, %eax #mark it as available movl $AVAILABLE, HDR_AVAIL_OFFSET(%eax) #return ret ########END OF FUNCTION##########
165
Chapter 9. Intermediate Memory Topics
The first thing to notice is that there is no _start symbol. The reason is that this is just a set of functions. A memory manager by itself is not a full program - it doesn’t do anything. It is simply a utility to be used by other programs. To assemble the program, do the following: as alloc.s -o alloc.o
Okay, now let’s look at the code.
Variables and Constants At the beginning of the program, we have two locations set up: heap_begin: .long 0 current_break: .long 0
Remember, the section of memory being managed is commonly referred to as the heap. When we assemble the program, we have no idea where the beginning of the heap is, nor where the current break is. Therefore, we reserve space for their addresses, but just fill them with a 0 for the time being. Next we have a set of constants to define the structure of the heap. The way this memory manager works is that before each region of memory allocated, we will have a short record describing the memory. This record has a word reserved for the available flag and a word for the region’s size. The actual memory allocated immediately follows this record. The available flag is used to mark whether this region is available for allocations, or if it is currently in use. The size field flag is offset 0 bytes from the beginning, and the size field is offset 4 bytes from the beginning. If we are careful to always use these constants, then we protect ourselves from having to do too much work if we later decide to add more information to the header. The values that we will use for our available field are either 0 for unavailable, or 1 for available. To make this easier to read, we have the following definitions: .equ UNAVAILABLE, 0 .equ AVAILABLE, 1
Finally, we have our Linux system call definitions: .equ BRK, 45 .equ LINUX_SYSCALL, 0x80
The allocate_init function Okay, this is a simple function. All it does is set up the heap_begin and current_break variables we discussed earlier. So, if you remember the discussion earlier, the current break can be found using the brk system call. So, the function starts like this: pushl %ebp movl %esp, %ebp movl
$SYS_BRK, %eax
167
Chapter 9. Intermediate Memory Topics movl int
$0, %ebx $LINUX_SYSCALL
Anyway, after int $LINUX_SYSCALL, %eax holds the last valid address. We actually want the first.
The allocate function This is the doozy function. Let’s start by looking at an outline of the function: 1. Start at the beginning of the heap. 2. Check to see if we’re at the end of the heap. 3. If we are at the end of the heap, grab the memory we need from Linux, mark it as "unavailable" and return it. If Linux won’t give us any more, return a 0. 4. If the current memory region is marked "unavailable", go to the next one, and go back to step 2. 5. If the current memory region is too small to hold the requested amount of space, go back to step 2.
168
Chapter 9. Intermediate Memory Topics 6. If the memory region is available and large enough, mark it as "unavailable" and return it. Now, look back through the code with this in mind. Be sure to read the comments so you’ll know which register holds which value. Now that you’ve looked back through the code, let’s first two lines are standard function stuff. The next move pulls the size of the memory to allocate off of the stack. This is our only function parameter. After that, it moves the beginning heap address and the end of the heap into registers. I am now ready to do processing. The next section is marked alloc_loop_begin. In this loop we are going to examine memory regions until we either find an open memory region or determine that we need more memory. Our first instructions check to see if we need more memory: cmpl %ebx, %eax je move_break %eax holds the current memory region being examined and %ebx holds the
location past the end of the heap. Therefore if the next region to be examined is past the end of the heap, it means we need more memory to allocate a region of this size. Let’s skip down to move_break and see what happens there: move_break: addl $HEADER_SIZE, %ebx addl %ecx, %ebx
169
Chapter 9. Intermediate Memory Topics pushl pushl pushl movl int
%eax %ecx %ebx $SYS_BRK, %eax $LINUX_SYSCALL
When we reach this point in the code, %ebx holds where we want the next region of memory to be. So, we add our header size and region size to %ebx, and that’s
The error code just returns 0 in %eax, so we won’t discuss it.
170
Chapter 9. Intermediate Memory Topics Let’s go back look at the rest of the loop. What happens if the current memory being looked at isn’t past the end of the heap? Well, let’s look. movl HDR_SIZE_OFFSET(%eax), %edx cmpl $UNAVAILABLE, HDR_AVAIL_OFFSET(%eax) je next_location
This first grabs the size of the memory region and puts it in %edx. Then it looks at the available flag to see if it is set to UNAVAILABLE. If so, that means that memory region is in use, so we’ll have to skip over it. So, if the available flag is set to UNAVAILABLE, you go to the code labeled next_location. If the available flag is set to AVAILABLE, then we keep on going. Let’s region’s size, we can use this block. It doesn’t matter if the current region is larger than requested, because the extra space will just be unused. So, let’s doesn’t need to even know about our memory header record. They just need a pointer to usable memory.
171
Chapter 9. Intermediate Memory Topics Okay, so let’s say the region wasn’t big enough. What then? Well, we would then be at the code labeled next_location. This section of code is used any time that we figure out that the current memory region won’t work for allocating memory. All it does is advance %eax to the next possible memory region, and goes back to the beginning of the loop. Remember that %edx is holding the size of the current memory region, and HEADER_SIZE is the symbol for the size of the memory region’s header. So this code will move us to the next memory region: addl addl jmp
$HEADER_SIZE, %eax %edx, %eax alloc_loop_begin
And now the function runs another loop. Whenever you have a loop, you must make sure that it will always end. The best way to do that is to examine all of the possibilities, and make sure that all of them eventually lead to the loop ending. In our case, we have the following possibilities: •
We will reach the end of the heap
•
We will find a memory region that’s available and large enough
•
We will go to the next location
The first two items are conditions that will cause the loop to end. The third one will keep it going. However, even if we never find an open region, we will eventually reach the end of the heap, because it is a finite size. Therefore, we know that no matter which condition is true, the loop has to eventually hit a terminating condition.
The deallocate function The deallocate function is much easier than the allocate one. That’s because it doesn’t have to do any searching at all. It can just mark the current memory
172
Chapter 9. Intermediate Memory Topics region as AVAILABLE, and allocate will find it next time it is called. So we have: movl subl movl ret
ST_MEMORY_SEG(%esp), %eax $HEADER_SIZE, %eax $AVAILABLE, HDR_AVAIL_OFFSET(%eax)
In this function, we don’t have to save %ebp or %esp since we’re not changing them, nor do we have to restore them at the end. All we’re doing is reading the address of the memory region from the stack, backing up to the beginning of the header, and marking the region as available. This function has no return value, so we don’t care what we leave in %eax.
Performance Issues and Other Problems Our simplistic memory manager is not really useful for anything more than an academic exercise. This section looks at the problems with such a simplistic allocator. The biggest problem here is speed. Now, if there are only a few allocations made, then speed won’t be a big issue. But think about what happens if you make a thousand allocations. On allocation number 1000, you have to search through 999 memory regions to find that you have to request more memory. As you can see, that’s getting pretty slow. In addition, remember that Linux can keep pages of memory on disk instead of in memory. So, since you have to go through every piece of memory your program’s memory, that means that Linux has to load every part of memory that’s currently on disk to check to see if its available. You can see how this could get really, really slow.5 This method is said to run in linear time, which means that every element you have to manage makes your program take 5. This is why adding more memory to your computer makes it run faster. The more memory your computer has, the less it puts on disk, so it doesn’t have to always be interrupting your programs to retreive pages off the disk.
173
Chapter 9. Intermediate Memory Topics longer. A program that runs in constant time takes the same amount of time no matter how many elements you are managing. Take the deallocate function, for instance. It only runs 4 instructions, no matter how many elements we are managing, or where they are in memory. In fact, although our allocate function is one of the slowest of all memory managers, the deallocate function is one of the fastest. Another performance problem is the number of times we’re calling the brk system call. System calls take a long time. They aren’t like functions, because the processor has to switch modes. Your program isn’t allowed to map itself memory, but the Linux kernel is. So, the processor has to switch into kernel mode, then Linux maps the memory, and then switches back to user mode for your application to continue running. This is also called a context switch. Context switches are relatively slow on x86 processors. Generally, you should avoid calling the kernel unless you really need to. Another problem that we have is that we aren’t recording where Linux actually sets the break. Previously we mentioned that Linux might actually set the break past where we requested it. In this program, we don’t even look at where Linux actually sets the break - we just assume it sets it where we requested. That’s not really a bug, but it will lead to unnecessary brk system calls when we already have the memory mapped in. Another problem we have is that if we are looking for a 5-byte region of memory, and the first open one we come to is 1000 bytes, we will simply mark the whole thing as allocated and return it. This leaves 995 bytes of unused, but allocated, memory. It would be nice in such situations to break it apart so the other 995 bytes can be used later. It would also be nice to combine consecutive free spaces when looking for large allocations.
174
Chapter 9. Intermediate Memory Topics
Using our Allocator The programs we do in this book aren’t complicated enough to necessitate a memory manager. Therefore, we will just use our memory manager to allocate a buffer for one of our file reading/writing programs instead of assigning it in the .bss. The program we will demonstrate this on is read-records.s from Chapter 6. This program uses a buffer named record_buffer to handle its input/output needs. We will simply change this from being a buffer defined in .bss to being a pointer to a dynamically-allocated buffer using our memory manager. You will need to have the code from that program handy as we will only be discussing the changes in this section. The first change we need to make is in the declaration. Currently it looks like this: .section .bss .lcomm, record_buffer, RECORD_SIZE
It would be a misnomer to keep the same name, since we are switching it from being an actual buffer to being a pointer to a buffer. In addition, it now only needs to be one word big (enough to hold a pointer). The new declaration will stay in the .data section and look like this: record_buffer_ptr: .long 0
Our next change is we need to initialize our memory manager immediately after we start our program. Therefore, right after the stack is set up, the following call needs to be added: call allocate_init
After that, the memory manager is ready to start servicing memory allocation requests. We need to allocate enough memory to hold these records that we are
175
Chapter 9. Intermediate Memory Topics reading. Therefore, we will call allocate to allocate this memory, and then save the pointer it returns into record_buffer_ptr. Like this: pushl $RECORD_SIZE call allocate movl %eax, record_buffer_ptr
Now, when we make the call to read_record, it is expecting a pointer. In the old code, the pointer was the immediate-mode reference to record_buffer. Now, record_buffer_ptr just holds the pointer rather than the buffer itself. Therefore, we must do a direct mode load to get the value in record_buffer_ptr. We need to remove this line: pushl $record_buffer
And put this line in its place: pushl record_buffer_ptr
The next change comes when we are trying to find the address of the firstname field of our record. In the old code, it was $RECORD_FIRSTNAME + record_buffer. However, that only works because it is a constant offset from a constant address. In the new code, it is the offset of an address stored in record_buffer_ptr. To get that value, we will need to move the pointer into a register, and then add $RECORD_FIRSTNAME to it to get the pointer. So where we have the following code: pushl $RECORD_FIRSTNAME + record_buffer
We need to replace it with this: movl record_buffer_ptr, %eax addl $RECORD_FIRSTNAME, %eax pushl %eax
176
Chapter 9. Intermediate Memory Topics Similarly, we need to change the line that says movl
$RECORD_FIRSTNAME + record_buffer, %ecx
so that it reads like this: movl addl
record_buffer_ptr, %ecx $RECORD_FIRSTNAME, %ecx
Finally, one change that we need to make is to deallocate the memory once we are done with it (in this program it’s not necessary, but it’s a good practice anyway). To do that, we just send record_buffer_ptr to the deallocate function right before exitting: pushl record_buffer_ptr call deallocate
Now you can build your program with the following commands: as read-records.s -o read-records.o ld alloc.o read-record.o read-records.o write-newline.o countchars.o -o read-records
You can then run your program by doing ./read-records. The uses of dynamic memory allocation may not be apparent to you at this point, but as you go from academic exercises to real-life programs you will use it continually.
More Information More information on memory handling in Linux and other operating systems can be found at the following locations:
177
Chapter 9. Intermediate Memory Topics •
More information about the memory layout of Linux programs can be found in Konstantin Boldyshev’s document, "Startup state of a Linux/i386 ELF binary", available at
•
A good overview of virtual memory in many different systems is available at
•
Several in-depth articles on Linux’s virtual memory subsystem is available at
•
Doug Lea has written up a description of his popular memory allocator at
•
A paper on the 4.4 BSD memory allocator is available at
Review Know the Concepts •
Describe the layout of memory when a Linux program starts.
•
What is the heap?
•
What is the current break?
•
Which direction does the stack grow in?
•
Which direction does the heap grow in?
•
What happens when you access unmapped memory?
•
How does the operating system prevent processes from writing over each other’s memory?
•
Describe the process that occurs if a piece of memory you are using is currently residing on disk?
178
Chapter 9. Intermediate Memory Topics •
Why do you need an allocator?
Use the Concepts •
Modify the memory manager so that it calls allocate_init automatically if it hasn’t been initialized.
•
Modify the memory manager so that if the requested size of memory is smaller than the region chosen, it will break up the region into multiple parts. Be sure to take into account the size of the new header record when you do this.
•
Modify one of your programs that uses buffers to use the memory manager to get buffer memory rather than using the .bss.
Going Further •
Research garbage collection. What advantages and disadvantages does this have over the style of memory management used here?
•
Research reference counting. What advantages and disadvantages does this have over the style of memory management used here?
•
Change the name of the functions to malloc and free, and build them into a shared library. Use LD_PRELOAD to force them to be used as your memory manager instead of the default one. Add some write system calls to STDOUT to verify that your memory manager is being used instead of the default one.
179
Chapter 9. Intermediate Memory Topics
180
Chapter 10. Counting Like a Computer Counting Counting Like a Human In many ways, computers count just like humans. So, before we start learning how computers count, let’s take a deeper look at how we count. How many fingers do you have? No, it’s not a trick question. Humans (normally) have ten fingers. Why is that significant? Look at our numbering system. At what point does a one-digit number become a two-digit number? That’s right, at ten. Humans count and do math using a base ten numbering system. Base ten means that we group everything in tens. Let’s say we’re counting sheep. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. Why did we all of a sudden now have two digits, and re-use the 1? That’s because we’re grouping our numbers by ten, and we have 1 group of ten sheep. Okay, let’s go to the next number 11. That means we have 1 group of ten sheep, and 1 sheep left ungrouped. So we continue - 12, 13, 14, 15, 16, 17, 18, 19, 20. Now we have 2 groups of ten. 21 - 2 groups of ten, and 1 sheep ungrouped. 22 - 2 groups of ten, and 2 sheep ungrouped. So, let’s say we keep counting, and get to 97, 98, 99, and 100. Look, it happened again! What happens at 100? We now have ten groups of ten. At 101 we have ten groups of ten, and 1 ungrouped sheep. So we can look at any number like this. If we counted 60879 sheep, that would mean that we had 6 groups of ten groups of ten groups of ten groups of ten, 0 groups of ten groups of ten groups of ten, 8 groups of ten groups of ten, 7 groups of ten, and 9 sheep left ungrouped. So, is there anything significant about grouping things by ten? No! It’s just that grouping by ten is how we’ve always done it, because we have ten fingers. We could have grouped at nine or at eleven (in which case we would have had to make up a new symbol). The only difference between the different groupings of numbers is that we have to re-learn our multiplication, addition, subtraction, and
181
Chapter 10. Counting Like a Computer division tables for each grouping. The rules haven’t changed, just the way we represent them. Also, some of our tricks that we learned don’t always apply, either. For example, let’s say we grouped by nine instead of ten. Moving the decimal point one digit to the right no longer multiplies by ten, it now multiplies by nine. In base nine, 500 is only nine times as large as 50.
Counting Like a Computer The question is, how many fingers does the computer have to count with? The computer only has two fingers. So that means all of the groups are groups of two. So, let’s count in binary - 0 (zero), 1 (one), 10 (two - one group of two), 11 (three one group of two and one left over), 100 (four - two groups of two), 101 (five two groups of two and one left over), 110 (six - two groups of two and one group of two), and so on. In base two, moving the decimal one digit to the right multiplies by two, and moving it to the left divides by two. Base two is also referred to as binary. The nice thing about base two is that the basic math tables are very short. In base ten, the multiplication tables are ten columns wide, and ten columns tall. In base two, it is very simple:
Table of binary addition + | 0 | 1 --+-----+----0 | 0 | 0 --+-----+----1 | 1 | 10 Table of binary multiplication
182
Chapter 10. Counting Like a Computer * | 0 | 1 --+-----+----0 | 0 | 0 --+-----+----1 | 0 | 1
So, let’s add the numbers 10010101 with 1100101: 10010101 + 1100101 ----------11111010
Now, let’s multiply them:
10010101 * 1100101 ----------10010101 00000000 10010101 00000000 00000000 10010101 10010101 --------------11101011001001
183
Chapter 10. Counting Like a Computer
Conversions Between Binary and Decimal Let’s learn how to convert numbers from binary (base two) to decimal (base ten). This is actually a rather simple process. If you remember, each digit stands for some grouping of two. So, we just need to add up what each digit represents, and we will have a decimal number. Take the binary number 10010101. To find out what it is in decimal, we take it apart like this: 1 0 0 1 0 1 0 1 | | | | | | | | | | | | | | | Individual units (2^0) | | | | | | 0 groups of 2 (2^1) | | | | | 1 group of 4 (2^2) | | | | 0 groups of 8 (2^3) | | | 1 group of 16 (2^4) | | 0 groups of 32 (2^5) | 0 groups of 64 (2^6) 1 group of 128 (2^7)
and then we add all of the pieces together, like this: 1*128 + 0*64 + 0*32 + 1*16 + 0*8 + 1*4 + 0*2 + 1*1 = 128 + 16 + 4 + 1 = 149
So 10010101 in binary is 149 in decimal. Let’s look at 1100101. It can be written as 1*64 + 1*32 + 0 * 16 + 0*8 + 1*4 + 0*2 + 1*1 = 64 + 32 + 4 + 1 = 101
So we see that 1100101 in binary is 101 in decimal. Let’s look at one more number, 11101011001001. You can convert it to decimal by doing 1*8192 + 1*4096 + 1*2048 + 0*1024 + 1*512 + 0*256
184
Chapter 10. Counting Like a Computer + 1*128 + 1*64 + 0*32 + 0*16 + 1*8 + 0*4 + 0*2 + 1*1 = 8192 + 4096 + 2048 + 512 + 128 + 64 + 8 + 1 = 15049
Now, if you’ve been paying attention, you have noticed that the numbers we just converted are the same ones we used to multiply with earlier. So, let’s check our results: 101 * 149 = 15049. It worked! Now let’s look at going from decimal back to binary. In order to do the conversion, you have to divide the number into groups of two. So, let’s say you had the number 17. If you divide it by two, you get 8 with 1 left over. So that means there are 8 groups of two, and 1 ungrouped. That means that the rightmost digit will be 1. Now, we have the rigtmost digit figured out, and 8 groups of 2 left over. Now, let’s see how many groups of two groups of two we have, by dividing 8 by 2. We get 4, with nothing left over. That means that all groups two can be further divided into more groups of two. So, we have 0 groups of only two. So the next digit to the left is 0. So, we divide 4 by 2 and get two, with 0 left over, so the next digit is 0. Then, we divide 2 by 2 and get 1, with 0 left over. So the next digit is 0. Finally, we divide 1 by 2 and get 0 with 1 left over, so the next digit to the left is 1. Now, there’s nothing left, so we’re done. So, the number we wound up with is 10001. Previously, we converted to binary 11101011001001 to decimal 15049. Let’s
Chapter 10. Counting Like a Computer 58 / 2 = 29 29 / 2 = 14 14 / 2 = 7 7 / 2 = 3 3 / 2 = 1 1 / 2 = 0
Remaining Remaining Remaining Remaining Remaining Remaining
0 1 0 1 1 1
Then, we put the remaining numbers back together, and we have the original number! Remember the first division remainder goes to the far right, so from the bottom up you have 11101011001001. Each digit in a binary number is called a bit, which stands for binary digit. Remember, computers divide up their memory into storage locations called bytes. Each storage location on an x86 processor (and most others) is 8 bits long. Earlier we said that a byte can hold any number between 0 and 255. The reason for this is that the largest number you can fit
The largest number that you can hold in 16 bits is 65535. The largest number you can hold in 32 bits is 4294967295 (4 billion). The largest number you can hold in 64 bits is 18,446,744,073,709,551,615. The largest number you can hold in 128 bits is 340,282,366,920,938,463,463,374,607,431,768,211,456. Anyway, you see the picture. For x86 processors, most of the time you will deal with 4-byte numbers (32 bits), because that’s the size of the registers.
186
Chapter 10. Counting Like a Computer
Truth, Falsehood, and Binary Numbers Now we’ve seen that the computer stores everything as sequences of 1’s and 0’s. Let’s look at some other uses of this. What if, instead of looking at a sequence of bits as a number, we instead looked at it as a set of switches. For example, let’s say there are four switches that control lighting in the house. We have a switch for outside lights, a switch for the hallway lights, a switch for the living room lights, and a switch for the bedroom lights. We could make a little table showing which of these were on and off, like so: Outside On
Hallway Off
Living Room On
Bedroom On
It’s obvious from looking at this that all of the lights are on except the hallway ones. Now, instead of using the words "On" and "Off", let’s use the numbers 1 and 0. 1 will represent on, and 0 will represent off. So, we could represent the same information as Outside 1
Hallway 0
Living Room 1
Bedroom 1
Now, instead of having labels on the light switches, let’s say we just memorized which position went with which switch. Then, the same information could be represented as 1
0
1
1
or as figuring out the best representation. Not only can you do regular arithmetic with binary numbers, they also have a few operations of their own, called binary or logical operations . The standard binary operations are •
AND
•
OR
•
NOT
•
XOR
Before we look at examples, I’ll describe them for you. AND takes two bits and returns one bit. AND will return a 1 only if both bits are 1, and a 0 otherwise. For example, 1 AND 1 is 1, but 1 AND 0 is 0, 0 AND 1 is 0, and 0 AND 0 is 0. it’s opposite NOT 1 is 0 and NOT 0 is 1. Finally, XOR is like OR, except it returns 0 if both bits are 1. Computers can do these operations on whole registers at a time. For example, if a register has 10100010101010010101101100101010 and another one has 10001000010101010101010101111010, you can run any of these operations on the whole registers. For example, if we were to AND them, the computer will run from the first’ll see that the resulting set of bits only has a one where both numbers had a one, and in every other position it has a zero. Let’s. Let’s
These operations are useful for two reasons: •
The computer can do them extremely fast
189
Chapter 10. Counting Like a Computer •
You can use them to compare many truth values at the same time
You may not have known that different instructions execute at different speeds. It’s true, they do. And these operations are the fastest on most processors. For example, you saw that XORing a number with itself produces 0. Well, the XOR operation is faster than the loading operation, so many programmers use it to load a register with zero. For example, the code movl
$0, %eax
is often replaced by xorl
%eax, %eax
We’ll discuss speed more in Chapter 12, but I want you to see how programmers often do tricky things, especially with these binary operators, to make things fast. Now let’s look at how we can use these operators to manipulate true/false values. Earlier we discussed how binary numbers can be used to represent any number of things. Let’s use binary numbers to represent what things my Dad and I like. First, let’s look at the things I like: Food: yes Heavy Metal Music: yes Wearing Dressy Clothes: no Football: yes
Now, let’s look at what my Dad likes: Food: yes Heavy Metal Music: no Wearing Dressy Clothes: yes Football: yes
Now, let’s use a 1 to say yes we like something, and a 0 to say no we don’t. Now we have:
190
Chapter 10. Counting Like a Computer Me Food: 1 Heavy Metal Music: 1 Wearing Dressy Clothes: 0 Football: 1 Dad Food: 1 Heavy Metal Music: 0 Wearing Dressy Clothes: 1 Football: 1
Now, if we just memorize which position each of these are in, we have Me 1101 Dad 1011
Now, let’s see we want to get a list of things both my Dad and I like. You would use the AND operation. So 1101 AND 1011 -------1001
Which translates to Things we both like Food: yes Heavy Metal Music: no Wearing Dressy Clothes: no Football: yes
191
Chapter 10. Counting Like a Computer Remember, the computer has no idea what the ones and zeroes represent. That’s your job and your program’s job. If you wrote a program around this representation your program would at some point examine each bit and have code to tell the user what it’s for (if you asked a computer what two people agreed on and it answered 1001, it wouldn’t be very useful). Anyway, let’s say we want to know the things that we disagree on. For that we would use XOR, because it will return 1 only if one or the other is 1, but not both. So 1101 XOR 1011 -------0110
And I’ll let you translate that back out. The previous operations: AND, OR, NOT, and XOR are called boolean operators because they were first studied by George Boole. So, if someone mentiones boolean operators or boolean algebra, you now know what they are talking about. In addition to the boolean operations, there are also two binary operators that aren’t boolean, shift and rotate. Shifts and rotates each do what their name implies, and can do so to the right or the left. A left shift moves each digit of a binary number one space to the left, puts a zero in the ones spot, and chops off the furthest digit to the left. A left rotate does the same thing, but takes the furthest digit to the left and puts it in the ones spot. For example,. Let’s say, for instance, that we had my Dad’s likes stored in a register (32 bits). It would look like this:
192
Chapter 10. Counting Like a Computer 00000000000000000000000000001011
Now, as we said previously, this doesn’t work as program output. So, in order to do output, we would need to do shifting and masking. Masking is the process of eliminating everything you don’t want. In this case, for every value we are looking for, we will shift the number so that value is in the ones place, and then mask that digit so that it is all we see. Masking is accomplished by doing an AND with a number that has the bits we are interested in set to 1. For example, let’s doesn’t. Then we can do a comparison to 1 and print the results. The code would look like this: #NOTE - assume that the register %ebx holds # my Dad’s preferences movl
%ebx, %eax #This copies the information into %eax so #we don’t lose the original data
shrl
$1, %eax
#This is the shift operator. It stands #for Shift Right Long. This first number #is the number of positions to shift,
193
Chapter 10. Counting Like a Computer #and the second is the register to shift #This does the masking andl $0b00000000000000000000000000000001, %eax #Check to see if the result is 1 or 0 cmpl $0b00000000000000000000000000000001, %eax je
yes_he_likes_dressy_clothes
jmp
no_he_doesnt_like_dressy_clothes
And then we would have two labels which printed something about whether or not he likes dressy clothes and then exits. The 0b notation means that what follows is a binary number. In this case it wasn’t needed, because 1 is the same in any numbering system, but I put it there for clarity. We also didn’t need the 31 zeroes, but I put them in to make a point that the number you are using is 32 bits. When a number represents a set of options for a function or system call, the individual true/false elements are called flags. Many system calls have numerous options that are all set in the same register using a mechanism like we’ve described. The open system call, for example, has as its second parameter a list of flags to tell the operating system how to open the file. Some of the flags include: O_WRONLY
This flag is 0b00000000000000000000000000000001 in binary, or 01 in octal (or any number system for that matter). This says to open the file in write-only mode. O_RDWR
This flag is 0b00000000000000000000000000000010 in binary, or 02 in octal. This says to open the file for both reading and writing.
194
Chapter 10. Counting Like a Computer O_CREAT
This flag is 0b00000000000000000000000001000000 in binary, or 0100 in octal. It means to create the file if it doesn’t already exist. O_TRUNC
This flag is 0b00000000000000000000001000000000 in binary, or 01000 in octal. It means to erase the contents of the file if the file already exists. O_APPEND
This flag is 0b00000000000000000000010000000000 in binary, or 02000 in octal. It means to start writing at the end of the file rather than at the beginning. To use these flags, you simply OR them together in the combination that you want. For example, to open a file in write-only mode, and have it create the file if it doesn’t exist, I would use O_WRONLY (01) and O_CREAT (0100). OR’d together, I would have 0101. Note that if you don’t set either O_WRONLY or O_RDWR, then the file is automatically opened in read-only mode (O_RDONLY, except that it isn’t really a flag since it’s zero). Many functions and system calls use flags for options, as it allows a single word to hold up to 32 possible options if each option is represented by a single bit.
The Program Status Register We’ve seen how bits on a register can be used to give the answers of yes/no and true/false statements. On your computer, there is a register called the program status register. This register holds a lot of information about what happens in a computation. For example, have you ever wondered what would happen if you
195
Chapter 10. Counting Like a Computer added two numbers and the result was larger than would fit in a register? The program status register has a flag called the carry flag. You can test it to see if the last computation overflowed the register. There are flags for a number of different statuses. In fact, when you do a compare (cmpl) instruction, the result is stored in this register. The conditional jump instructions (jge, jne, etc) use these results to tell whether or not they should jump. jmp, the unconditional jump, doesn’t care what is in the status register, since it is unconditional. Let’s say you needed to store a number larger than 32 bits. So, let’s say the number is 2 registers wide, or 64 bits. How could you handle this? If you wanted to add two 64 bit numbers, you would add the least significant registers first. Then, if you detected an carry, you could add 1 to the most significant register. In fact, this is probably the way you learned to do decimal addition. If the result in one column is more than 9, you simply carried the number to the next most significant column. If you added 65 and 37, first you add 7 and 4 to get 12. You keep the 2 in the right column, and carry the one to the next column. There you add 6, 3, and the 1 you carried. This results in 10. So, you keep the zero in that column and carry the one to the next most significant column, which is empty, so you just put the one there. Luckily, 32 bits is usually big enough to hold the numbers we use regularly. Additional program status register flags are examined in Appendix B.
Other Numbering Systems What we have studied so far only applies to positive integers. However, real-world numbers are not always positive integers. Negative numbers and numbers with decimals are also used.
Floating-point Numbers So far, the only numbers we’ve dealt with are integers - numbers with no decimal point. Computers have a general problem with numbers with decimal points,
196
Chapter 10. Counting Like a Computer because computers can only store fixed-size, finite values. Decimal numbers can be any length, including infinite length (think of a repeating decimal, like the result of 1 / 3). The way a computer handles decimals is by storing them at a fixed precision (number of significant floating point numbers. If the number is sufficiently big, like 5.234 * 10^5000, adding 1 to it might not even register in the mantissa (remember, both parts are only so long). This affects several things, especially order of operations. Let’s say that I add 1 to 5.234 * 10^5000 a few billion or trillion times. Guess what - the number won’t change at all. However, if I add one to itself enough times, and then add it to the original number, it might make a dent. You should note that it takes most computers a lot longer to do floating-point arithmetic than it does integer arithmetic. So, for programs that really need speed, integers are mostly used.
Negative Numbers How would you think that negative numbers on a computer might be represented? One thought might be to use the first problems. First of all, it takes a lot more circuitry to add and subtract signed numbers represented this way. Even more problematic, this representation has a problem with the number 0. In this system, you could have both a negative and a positive 0. This leads to a lot of questions, like "should negative zero be equal to positive zero?", and "What should the sign of zero be in various circumstances?". These problems were overcome by using a representation of negative numbers called two’s complement representation. To get the negative representation of a number in two’s complement form, you must perform the following steps: 1. Perform a NOT operation on the number 2. Add one to the resulting number So, to get the negative of 00000000000000000000000000000001, you would first do a NOT operation, which gives 11111111111111111111111111111110, and then add one, giving 11111111111111111111111111111111. To get negative two, first flip to zero. Also, the first two’s complement representation of signed numbers is that, unlike unsigned quantities, if you increase the number of bits, you can’t just add zeroes to the left of the number. For example, let’s two’s complement representation, you have to perform sign extension. Sign extension means that you have to pad the left-hand side of the quantity with whatever digit is in the sign digit when you add bits. So, if we extend a negative number by 4 digits, we should fill the new digits with a 1. If we extend a positive number by 4 digits, we should fill.
Octal and Hexadecimal Numbers The numbering systems discussed so far have been decimal and binary. However, two others are used common in computing - octal and hexadecimal. In fact, they are probably written more often than binary. Octal is a representation that only uses the numbers 0 through 7. So the octal number 10 is actually 8 in decimal because it is one group of eight. Octal 121 is decimal 81 (one group of 64 (8^2), two groups of 8, and one left over). What makes octal nice is that every 3 binary digits make one octal digit (there is no such grouping of binary digits into decimal). So 0 is 000, 1 is 001, 2 is 010, 3 is 011, 4 is 100, 5 is 101, 6 is 110, and 7 is 111. Permissions in Linux are done using octal. This is because Linux permissions are based on the ability to read, write and execute. The first bit is the read permission, the second bit is the write permission, and the third bit is the execute permission. So, 0 (000) gives no permissions, 6 (110) gives read and write permission, and 5 (101) gives read and execute permissions. These numbers are then used for the
199
Chapter 10. Counting Like a Computer three different sets of permissions - the owner, the group, and everyone else. The number 0644 means read and write for the first permission set, and read-only for the second and third set. The first permission set is for the owner of the file. The third permission set is for the group owner of the file. The last permission set is for everyone else. So, 0751 means that the owner of the file can read, write, and execute the file, the group members can read and execute the file, and everyone else can only execute the file. Anyway, as you can see, octal is used to group bits (binary digits) into threes. The way the assembler knows that a number is octal is because octal numbers are prefixed don’t have their own numbers, hexadecimal uses the letters a through f to represent them. For example, the letter a represents 10, the letter b represents 11, and so on. 10 in hexadecimal is 16 in decimal. In octal, each digit represented three bits. In hexadecimal, each digit represents four bits. Every two digits is a full byte, and eight digits is a 32-bit word. So you see, it is considerably easier to write a hexadecimal number than it is to write a binary number, because it’s only a quarter as many digits. The most important number to remember in hexadecimal is f, which means that all bits are set. So, if I want to set all of the bits of a register to 1, I can just do movl
$0xFFFFFFFF, %eax
Which is considerably easier and less error-prone than writing movl
$0b11111111111111111111111111111111, %eax
Note also that hexadecimal numbers are prefixed with 0x. So, when we do
200
Chapter 10. Counting Like a Computer int
$0x80.
Order of Bytes in a Word One thing that confuses many people when dealing with bits and bytes on a low level is that, when bytes are written from registers to memory, their bytes are written out least-significant-portion-first.1 What most people expect is that if they have a word in a register, say 0x5d 23 ef ee (the spacing is so you can see where the bytes are), the bytes will be written to memory in that order. However, on x86 processors, the bytes are actually written in reverse order. In memory the bytes would be 0xee ef 23 5d on x86 processors. The bytes are written in reverse order from what they would appear conceptually, but the bits within the bytes are ordered normally. Not all processors behave this way. The x86 processor is a little-endian processor, which means that it stores the "little end", or least-significant byte of its words first. 1. Significance in this context is referring to which digit they represent. For example, in the number 294, the digit 2 is the most significant because it represents the hundreds place, 9 is the next most significant, and 4 is the least significant.
201
Chapter 10. Counting Like a Computer
Register-to-memory transfers on little-endian systems Other processors are big-endian processors, which means that they store the "big end", or most significant byte, of their words first, the way we would naturally read a number.
202
Chapter 10. Counting Like a Computer
Register-to-memory transfers on big-endian systems This difference is not normally a problem (although it has sparked many technical controversies throughout the years). Because the bytes are reversed again (or not, if it is a big-endian processor) when being read back into a register, the programmer usually never notices what order the bytes are in. The byte-switching magic happens automatically behind the scenes during register-to-memory transfers. However, the byte order can cause problems in several instances: •
If you try to read in several bytes at a time using movl but deal with them on a byte-by-byte basis using the least significant byte (i.e. - by using %al and/or shifting of the register), this will be in a different order than they appear in memory.
203
Chapter 10. Counting Like a Computer •
If you read or write files written for different architectures, you may have to account for whatever order they write their bytes in.
•
If you read or write to network sockets, you may have to account for a different byte order in the protocol.
As long as you are aware of the issue, it usually isn’t a big deal. For more in-depth look at byte order issues, you should read DAV’s Endian FAQ at, especially the article "On Holy Wars and a Plea for Peace" by Daniel Cohen.
Converting Numbers for Display So far, we have been unable to display any number stored to the user, except by the extremely limitted means of passing it through exit codes. In this section, we will discuss converting positive numbers into strings for display. The function will be called integer2string, and it will take two parameters an integer to convert and a string buffer filled with null characters (zeroes). The buffer will be assumed to be big enough to store the entire number as a string.(at least 11 characters long, to include a trailing null character). Remember that the way that we see numbers is in base 10. Therefore, to access the individual decimal digits of a number, we need to be dividing by 10 and displaying the remainder for each digit. Therefore, the process will look like this: •
Divide the number by ten
•
The remainder is the current digit. Convert it to a character and store it.
•
We are finished if the quotient is zero.
•
Otherwise, take the quotient and the next location in the buffer and repeat the process.
204
Chapter 10. Counting Like a Computer The only problem is that since this process deals with the one’s place first, it will leave the number backwards. Therefore, we will have to finish by reversing the characters. We will do this by storing the characters on the stack as we compute them. This way, as we pop them back off to fill in the buffer, it will be in the reverse order that we pushed them on. The code for the function should be put in a file
Chapter 10. Counting Like a Computer #Current character count movl $0, %ecx #Move the value into position movl ST_VALUE(%ebp), %eax #When we divide by 10, the 10 #must be in a register or memory location movl $10, %edi conversion_loop: #Division is actually performed on the #combined %edx:%eax register, so first #clear out %edx movl $0, %edx #Divide %edx:%eax (which are implied) by 10. #Store the quotient in %eax and the remainder #in %edx (both of which are implied). divl %edi #Quotient is in the right place. %edx has #the remainder, which now needs to be converted #into a number. So, %edx has a number that is #0 through 9. You could also interpret this as #an index on the ASCII table starting from the #character ’0’. The ascii code for ’0’ plus zero #is still the ascii code for ’0’. The ascii code #for ’0’ plus 1 is the ascii code for the #character ’1’. Therefore, the following #instruction will give us the character for the #number stored in %edx addl $’0’, %edx #Now we will take this value and push it on the
206
Chapter 10. Counting Like a Computer #stack. This way, when we are done, we can just #pop off the characters one-by-one and they will #be in the right order. Note that we are pushing #the whole register, but we only need the byte #in %dl (the last byte of the %edx register) for #the character. pushl %edx #Increment the digit count incl %ecx #Check to see if %eax is zero yet, go to next #step if so. cmpl $0, %eax je end_conversion_loop #%eax already has its new value. jmp conversion_loop end_conversion_loop: #The string is now on the stack, if we pop it #off a character at a time we can copy it into #the buffer and be done. #Get the pointer to the buffer in %edx movl ST_BUFFER(%ebp), %edx copy_reversing_loop: #We pushed a whole register, but we only need #the last byte. So we are going to pop off to #the entire %eax register, but then only move the #small part (%al) into the character string. popl %eax movb %al, (%edx)
207
Chapter 10. Counting Like a Computer #Decreasing %ecx so we know when we are finished decl %ecx #Increasing %edx so that it will be pointing to #the next byte incl %edx #Check to see if we are finished cmpl $0, %ecx #If so, jump to the end of the function je end_copy_reversing_loop #Otherwise, repeat the loop jmp copy_reversing_loop end_copy_reversing_loop: #Done copying. Now write a null byte and return movb $0, (%edx) movl popl ret
%ebp, %esp %ebp
To show this used in a full program, use the following code, along with the count_chars and write_newline functions written about in previous chapters. The code should be in a file called conversion-program.s. .include "linux.s" .section .data #This is where it will be stored tmp_buffer: .ascii "\0\0\0\0\0\0\0\0\0\0\0"
208
Chapter 10. Counting Like a Computer .section .text .globl _start _start: movl %esp, %ebp #Storage for the result pushl $tmp_buffer #Number to convert pushl $824 call integer2string addl $8, %esp #Get the character count for our system call pushl $tmp_buffer call count_chars addl $4, %esp #The count goes in %edx for SYS_WRITE movl %eax, %edx #Make movl movl movl
the system call $SYS_WRITE, %eax $STDOUT, %ebx $tmp_buffer, %ecx
int
$LINUX_SYSCALL
#Write a carriage return pushl $STDOUT call write_newline #Exit movl $SYS_EXIT, %eax
209
Chapter 10. Counting Like a Computer movl int
$0, %ebx $LINUX_SYSCALL
To build the program, issue the following commands: as integer-to-string.s -o integer-to-number.o as count-chars.s -o count-chars.o as write-newline.s -o write-newline.o as conversion-program.s -o conversion-program.o ld integer-to-number.o count-chars.o write-newline.o conversionprogram.o -o conversion-program
To run just type ./conversion-program and the output should say 824.
Review Know the Concepts •
Convert the decimal number 5,294 to binary.
•
What number does 0x0234aeff represent? Specify in binary, octal, and decimal.
•
Add the binary numbers 10111001 and 101011.
•
Multiply the binary numbers 1100 1010110.
•
Convert the results of the previous two problems into decimal.
•
Describe how AND, OR, NOT, and XOR work.
•
What is masking for?
•
What number would you use for the flags of the open system call if you wanted to open the file for writing, and create the file if it doesn’t exist?
210
Chapter 10. Counting Like a Computer •
How would you represent -55 in a thirty-two bit register?
•
Sign-extend the previous quantity into a 64-bit register.
•
Describe the difference between little-endian and big-endian storage of words in memory.
Use the Concepts •
Go back to previous programs that returned numeric results through the exit status code, and rewrite them to print out the results instead using our integer to string conversion function.
•
Modify the integer2string code to return results in octal rather than decimal.
•
Modify the integer2string code so that the conversion base is a parameter rather than hardcoded.
•
Write a function called is_negative that takes a single integer as a parameter and returns 1 if the parameter is negative, and 0 if the parameter is positive.
Going Further •
Modify the integer2string code so that the conversion base can be greater than 10 (this requires you to use letters for numbers past 9).
•
Create a function that does the reverse of integer2string called number2integer which takes a character string and converts it to a register-sized integer. Test it by running that integer back through the integer2string function and displaying the results.
•
Write a program that stores likes and dislikes into a single machine word, and then compares two sets of likes and dislikes for commonalities.
211
Chapter 10. Counting Like a Computer •
Write a program that reads a string of characters from STDIN and converts them to a number.
212
Chapter 11. High-Level Languages In this chapter we will begin to look at our first "real-world" programming language. Assembly language is the language used at the machine’s level, but most people find coding in assembly language too cumbersome for everyday use. Many computer languages have been invented to make the programming task easier. Knowing a wide variety of languages is useful for many reasons, including
•
Different languages are based on different concepts, which will help you to learn different and better programming methods and ideas.
•
Different languages are good for different types of projects.
•
Different companies have different standard languages, so knowing more languages makes your skills more marketable.
• flinches at. In fact, if you do computer consulting you will often have to learn new languages on the spot in order to keep yourself employed. It will often be your customer, not you, who decides what language is used. This chapter will introduce you to a few of the languages available to you. I encourage you to explore as many languages as you are interested in. I personally try to learn a new language every few months.
Compiled and Interpreted Languages Many languages are compiled languages. When you write assembly language, each instruction you write is translated into exactly one machine instruction for processing. With compilers, a statement can translate into one or hundreds of that in turn runs the given program. These are usually slower than compiled programs, since the interpreter has to read and interpret the code as it goes along. However, in well-made interpreters, this time can be fairly negligible. There is also a class of hybrid languages which partially compile a program before execution into byte-codes. This is done because the interpreter can read the byte-codes much faster than it can read the regular language. There are many reasons to choose one or the other. Compiled programs are nice, because you don’t have to already have an interpreter installed in the user’s machine. You have to have a compiler for the language, but the users of your program don’t. In an interpreted language, you have to be sure that the user has an interpreter installed for your program, and that the computer knows which interpreter to run your program with. However, interpeted languages tend to be more flexible,: •
Being able to group multiple operations into a single expression
•
Being able to use "big values" - values that are much more conceptual than the 4-byte words that computers normally deal with (for example, being able to view text strings as a single value rather than as a string of bytes).
214
Chapter 11. High-Level Languages •
Having access to better flow control constructs than just jumps.
•
Having a compiler to check types of value assignments and other assertions.
•
Having memory handled automatically.
•
Being able to work in a language that resembles the problem domain rather than the computer hardware.
So why does one choose one language over another? For example, many choose Perl because it has a vast library of functions for handling just about every protocol or type of data on the planet. Python, however, has a cleaner syntax and often lends itself to more straightforward solutions. It’s cross-platform GUI tools are also excellent. PHP makes writing web applications simple. Common LISP has more power and features than any other environment for those willing to learn it. Scheme is the model of simplicity and power combined together. C is easy to interface with other languages. Each language is different, and the more languages you know the better programmer you will be. Knowing the concepts of different languages will help you in all programming, because you can match the programming language to the problem better, and you have a larger set of tools to work with. Even if certain features aren’t directly supported in the language you are using, often they can be simulated. However, if you don’t have a broad experience with languages, you won’t know of all the possibilities you have to choose from.
Your First C Program Here is your first C program, which prints "Hello world" to the screen and exits. Type it in, and give it the name Hello-World.c #include <stdio.h> /* PURPOSE: /*
This program is mean to show a basic */ C program. All it does is print */
215
Chapter 11. High-Level Languages /* /*
"Hello World!" to the screen and exit.
*/ */
/* Main Program */ int main(int argc, char **argv) { /* Print our string to standard output */ puts("Hello World!\n"); /* Exit with status 0 */ return 0; }
As you can see, it’s a pretty simple program. To compile it, run the command gcc -o HelloWorld Hello-World.c
To run the program, do ./HelloWorld
Let’s look at how this program was put together. Comments in C are started with /* and ended with */. Comments can span multiple lines, but many people prefer to start and end comments on the same line so they don’t get confused. #include <stdio.h> is the first part of the program. This is a preprocessor
directive. C compiling is split into two stages - the preprocessor and the main compiler. This directive tells the preprocessor to look for the file stdio.h and paste it into your program. The preprocessor is responsible for putting together the text of the program. This includes sticking different files filename tell the compiler to look in it’s standard paths for the file (/usr/include and /usr/local/include, usually). If it was in quotes, like #include "stdio.h" it would look in the current directory for the file. function’s name is main, it returns an int (integer - 4 bytes long on the x86 platform), and has two arguments - an int called argc and a char ** called argv. You don’t have to worry about where the arguments are positioned on the stack - the C compiler takes care of that for you. You also don’t first parameter is the number of arguments given to this command, and the second parameter is a list of the arguments that were given. The next line is a function call. In assembly language, you had to push the arguments of a function onto the stack, and then call the function. C takes care of this complexity for you. You simply have to call the function with the parameters in parenthesis. In this case, we call the function puts, with a single parameter. This parameter is the character string we want to print. We just have to type in the string in quotations, and the compiler takes care of defining storage and moving the pointers to that storage onto the stack before calling the function. As you can see, it’s. As you can see, using high-level languages makes life much easier. It also allows our programs to run on multiple platforms more easily. In assembly language, your program is tied to both the operating system and the hardware platform, while in compiled and interpreted languages the same code can usually run on multiple operating systems and hardware platforms. For example, this program can be built and executed on x86 hardware running Linux®, Windows®, UNIX®, or most other operating systems. In addition, it can also run on Macintosh hardware running a number of operating systems. Additional information on the C programming language can be found in Appendix E.
Perl Perl is an interpreted language, existing mostly on Linux and UNIX-based platforms. It actually runs on almost all platforms, but you find it most often on Linux and UNIX-based ones. Anyway, here is the Perl version of the program, which should be typed into a file named Hello-World.pl: #!/usr/bin/perl print("Hello world!\n");
Since Perl is interpreted, you don’t need to compile or link it. Just run in with the following command: perl Hello-World.pl
As you can see, the Perl version is even shorter than the C version. With Perl you don’t have to declare any functions or program entry points. You can just start
218
Chapter 11. High-Level Languages typing commands and the interpreter will run them as it comes to them. In fact this program only has two lines of code, one of which is optional. The first, specified that we were using the perl interpreter. The next line calls a Perl builtin function, print. This has one parameter, the string to print. The program doesn’t have an explicit return statement - it knows to return simply because it runs off the end of the file. It also knows to return 0 because there were no errors while it ran. You can see that interpreted languages are often focused on letting you get working code as quickly as possible, without having to do a lot of extra legwork. One thing about Perl that isn’t so evident from this example is that Perl treats strings as a single value. In assembly language, we had to program according to the computer’s memory architecture, which meant that strings had to be treated as a sequence of multiple values, with a pointer to the first letter. Perl pretends that strings can be stored directly as values, and thus hides the complication of manipulating them for you. In fact, one of Perl’s main strengths is it’s ability and speed at manipulating text.
Python The Python version of the program looks almost exactly like the Perl one. However, Python is really a very different language than Perl, even if it doesn’t seem so from this trivial example. Type the program into a file named Hello-World.py. The program follows: #!/usr/bin/python
219
Chapter 11. High-Level Languages print "Hello World"
You should be able to tell what the different lines of the program do.
Review Know the Concepts •
What is the difference between an intepretted language and a compiled language?
•
What reasons might cause you to need to learn a new programming language?
Use the Concepts •
Learn the basic syntax of a new programming language. Re-code one of the programs in this book in that language.
•
In the program you wrote in the question above, what specific things were automated in the programming language you chose?
•
Modify your program so that it runs 10,000 times in a row, both in assembly language and in your new language. Then run the time command to see which is faster. Which does come out ahead? Why do you think that is?
•
How does the programming language’s input/output methods differ from that of the Linux system calls?
220
Chapter 11. High-Level Languages
Going Further •
Having seen languages which have such brevity as Perl, why do you think this book started you with a language as verbose as assembly language?
•
How do you think high level languages have affected the process of programming?
•
Why do you think so many languages exist?
•
Learn two new high level languages. How do they differ from each other? How are they similar? What approach to problem-solving does each take?
221
Chapter 11. High-Level Languages
222
Chapter 12. Optimization Optimization is the process of making your application run more effectively. You can optimize for many things - speed, memory space usage, disk space usage, etc. This chapter, however, focuses on speed optimization.
When to Optimize It is better to not optimize at all than to optimize too soon. When you optimize, your code generally becomes less clear, because it becomes more complex. Readers of your code will have more trouble discovering why you did what you did which will increase the cost of maintenance of your project. Even when you know how and why your program runs the way it does, optimized code is harder to debug and extend. It slows the development process down considerably, both because of the time it takes to optimize the code, and the time it takes to modify your optimized code. Compounding this problem is that you don’t even know beforehand where the speed issues in your program will be. Even experienced programmers have trouble predicting which parts of the program will be the bottlenecks which need optimization, so you will probably end up wasting your time optimizing the wrong parts. the Section called Where to Optimize will discuss how to find the parts of your program that need optimization. While you develop your program, you need to have the following priorities: •
Everything is documented
•
Everything works as documented
•
The code is written in an modular, easily modifiable form
Documentation is essential, especially when working in groups. The proper functioning of the program is essential. You’ll notice application speed was not
223
Chapter 12. Optimization anywhere on that list. Optimization is not necessary during early development for the following reasons: •
Minor speed problems can be usually solved through hardware, which is often much cheaper than a programmer’s time.
•
Your application will change dramatically as you revise it, therefore wasting most of your efforts to optimize it.1
•
Speed problems are usually localized in a few places in your code - finding these is difficult before you have most of the program finished.
Therefore, the time to optimize is toward the end of development, when you have determined that your correct code actually has performance problems. In a web-based e-commerce project I was involved in, I focused entirely on correctness. This was much to the dismay of my colleagues, who were worried about the fact that each page took twelve seconds to process before it ever started loading (most web pages process in under a second). However, I was determined to make it the right way first, and put optimization as a last priority. When the code was finally correct after 3 months of work, it took only three days to find and eliminate the bottlenecks, bringing the average processing time under a quarter of a second. By focusing on the correct order, I was able to finish a project that was both correct and efficient.
Where to Optimize Once you have determined that you have a performance issue you need to determine where in the code the problems occur. You can do this by running a profiler. A profiler is a program that will let you run your program, and it will tell you how much time is spent in each function, and how many times they are run. 1. Many new projects often have a first code base which is completely rewritten as developers learn more about the problem they are trying to solve. Any optimization done on the first codebase is completely wasted.
224
Chapter 12. Optimization gprof is the standard GNU/Linux profiling tool, but a discussion of using
profilers is outside the scope of this text. After running a profiler, you can determine which functions are called the most or have the most time spent in them. These are the ones you should focus your optimization efforts on. If a program only spends 1% of its time in a given function, then no matter how much you speed it up you will only achieve a maximum of a 1% overall speed improvement. However, if a program spends 20% of its time in a given function, then even minor improvements to that functions speed will be noticeable. Therefore, profiling gives you the information you need to make good choices about where to spend your programming time. In order to optimize functions, you need to understand in what ways they are being called and used. The more you know about how and when a function is called, the better position you will be in to optimize it appropriately. There are two main categories of optimization - local optimizations and global optimizations. Local optimizations consist of optimizations that are either hardware specific - such as the fastest way to perform a given computation - or program-specific - such as making a specific piece of code perform the best for the most often-occuring case. Global optimization consist of optimizations which are structural. For example, if you were trying to find the best way for three people in different cities to meet in St. Louis, a local optimization would be finding a better road to get there, while a global optimization would be to decide to teleconference instead of meeting in person. Global optimization often involves restructuring code to avoid performance problems, rather than trying to find the best way through them.
Local Optimizations The following are some well-known methods of optimizing pieces of code. When using high level languages, some of these may be done automatically by your compiler’s optimizer.
225
Chapter 12. Optimization Precomputing Calculations Sometimes a function has a limitted number of possible inputs and outputs. In fact, it may be so few that you can actually precompute all of the possible answers beforehand, and simply look up the answer when the function is called. This takes up some space since you have to store all of the answers, but for small sets of data this works out really well, especially if the computation normally takes a long time. Remembering Calculation Results This is similar to the previous method, but instead of computing results beforehand, the result of each calculation requested is stored. This way when the function starts, if the result has been computed before it will simply return the previous answer, otherwise it will do the full computation and store the result for later lookup. This has the advantage of requiring less storage space because you aren’t precomputing all results. This is sometimes termed caching or memoizing. Locality of Reference Locality of reference is a term for where in memory the data items you are accessing are. With virtual memory, you may access pages of memory which are stored on disk. In such a case, the operating system has to load that memory page from disk, and unload others to disk. Let’s say, for instance, that the operating system will allow you to have 20k of memory in physical memory and forces the rest of it to be on disk, and your application uses 60k of memory. Let’s say your program has to do 5 operations on each piece of data. If it does one operation on every piece of data, and then goes through and does the next operation on each piece of data, eventually every page of data will be loaded and unloaded from the disk 5 times. Instead, if you did all 5 operations on a given data item, you only have to load each page from disk once. When you bundle as many operations on data that is physically close to each other in memory, then you are taking advantage of locality of reference.
226
Chapter 12. Optimization In addition, processors usually store some data on-chip in a cache. If you keep all of your operations within a small area of physical memory, your program may bypass even main memory and only use the chip’s ultra-fast cache memory. This is all done for you - all you have to do is to try to operate on small sections of memory at a time, rather than bouncing all over the place. Register Usage Registers are the fastest memory locations on the computer. When you access memory, the processor has to wait while it is loaded from the memory bus. However, registers are located on the processor itself, so access is extremely fast. Therefore making wise usage of registers is extremely important. If you have few enough data items you are working with, try to store them all in registers. In high level languages, you do not always have this option - the compiler decides what goes in registers and what doesn’t. Inline Functions Functions are great from the point of view of program management - they make it easy to break up your program into independent, understandable, and reuseable parts. However, function calls do involve the overhead of pushing arguments onto the stack and doing the jumps (remember locality of reference - your code may be swapped out on disk instead of in memory). For high level languages, it’s often impossible for compilers to do optimizations across function-call boundaries. However, some languages support inline functions or function macros. These functions look, smell, taste, and act like real functions, except the compiler has the option to simply plug the code in exactly where it was called. This makes the program faster, but it also increases the size of the code. There are also many functions, like recursive functions, which cannot be inlined because they call themselves either directly or indirectly.
227
Chapter 12. Optimization Optimized Instructions Often times there are multiple assembly language instructions which accomplish the same purpose. A skilled assembly language programmer knows which instructions are the fastest. However, this can change from processor to processor. For more information on this topic, you need to see the user’s manual that is provided for the specific chip you are using. As an example, let’s look at the process of loading the number 0 into a register. On most processors, doing a movl $0, %eax is not the quickest way. The quickest way is to exclusive-or the register with itself, xorl %eax, %eax. This is because it only has to access the register, and doesn’t have to transfer any data. For users of high-level languages, the compiler handles this kind of optimizations for you. For assembly-language programmers, you need to know your processor well. Addressing Modes Different addressing modes work at different speeds. The fastest are the immediate and register addressing modes. Direct is the next fastest, indirect is next, and base pointer and indexed indirect are the slowest. Try to use the faster addressing modes, when possible. One interesting consequence of this is that when you have a structured piece of memory that you are accessing using base pointer addressing, the first element can be accessed the quickest. Since it’s offset is 0, you can access it using indirect addressing instead of base pointer addressing, which makes it faster. Data Alignment Some processors can access data on word-aligned memory boundaries (i.e. addresses divisible by the word size) faster than non-aligned data. So, when setting up structures in memory, it is best to keep it word-aligned. Some non-x86 processors, in fact, cannot access non-aligned data in some modes. These are just a smattering of examples of the kinds of local optimizations possible. However, remember that the maintainability and readability of code is
228
Chapter 12. Optimization much more important except under extreme circumstances.
Global Optimization Global optimization has two goals. The first one is to put your code in a form where it is easy to do local optimiztions. For example, if you have a large procedure that performs several slow, complex calculations, you might see if you can break parts of that procedure into their own functions where the values can be precomputed or memoized. Stateless functions (functions that only operate on the parameters that were passed to them - i.e. no globals or system calls) are the easiest type of functions to optimize in a computer. The more stateless parts of your program you have, the more opportunities you have to optimize. In the e-commerce situation I wrote about above, the computer had to find all of the associated parts for specific inventory items. This required about 12 database calls, and in the worst case took about 20 seconds. However, the goal of this program was to be interactive, and a long wait would destroy that goal. However, I knew that these inventory configurations do not change. Therefore, I converted the database calls into their own functions, which were stateless. I was then able to memoize the functions. At the beginning of each day, the function results were cleared in case anyone had changed them, and several inventory items were automatically preloaded. From then on during the day, the first time someone accessed an inventory item, it would take the 20 seconds it did beforehand, but afterwards it would take less than a second, because the database results had been memoized. Global optimization usually often involves achieving the following properties in your functions: Parallelization Parallelization means that your algorithm can effectively be split among multiple processes. For example, pregnancy is not very parallelizable because
229
Chapter 12. Optimization no matter how many women you have, it still takes nine months. However, building a car is parallelizable because you can have one worker working on the engine while another one is working on the interior. Usually, applications have a limit to how parallelizable they are. The more parallelizable your application is, the better it can take advantage of multiprocessor and clustered computer configurations. Statelessness As we’ve discussed, stateless functions and programs are those that rely entirely on the data explicitly passed to them for functioning. Most processes are not entirely stateless, but they can be within limits. In my e-commerce example, the function wasn’t entirely stateless, but it was within the confines of a single day. Therefore, I optimized it as if it were a stateless function, but made allowances for changes at night. Two great benefits resulting from statelessness is that most stateless functions are parallelizable and often benefit from memoization. Global optimization takes quite a bit of practice to know what works and what doesn’t. Deciding how to tackle optimization problems in code involves looking at all the issues, and knowing that fixing some issues may cause others.
Review Know the Concepts •
At what level of importance is optimization compared to the other priorities in programming?
•
What is the difference between local and global optimizations?
•
Name some types of local optimizations.
230
Chapter 12. Optimization •
How do you determine what parts of your program need optimization?
•
At what level of importance is optimization compared to the other priorities in programming? Why do you think I repeated that question?
Use the Concepts •
Go back through each program in this book and try to make optimizations according to the procedures outlined in this chapter
•
Pick a program from the previous exercise and try to calculate the performance impact on your code under specific inputs.2
Going Further •
Find an open-source program that you find particularly fast. Contact one of the developers and ask about what kinds of optimizations they performed to improve the speed.
•
Find an open-source program that you find particularly slow, and try to imagine the reasons for the slowness. Then, download the code and try to profile it using gprof or similar tool. Find where the code is spending the majority of the time and try to optimize it. Was the reason for the slowness different than you imagined?
•
Has the compiler eliminated the need for local optimizations? Why or why not?
•
What kind of problems might a compiler run in to if it tried to optimize code across function call boundaries?
2. Since these programs are usually short enough not to have noticeable performance problems, looping through the program thousands of times will exaggerate the time it takes to run enough to make calculations.
231
Chapter 12. Optimization
232
Chapter 13. Moving On from Here Congratulations on getting this far. You should now have a basis for understanding the issues involved in many areas of programming. Even if you never use assembly language again, you have gained a valuable perspective and mental framework for understanding the rest of computer science. There are essentially three methods to learn to program: •
From the Bottom Up - This is how this book teaches. It starts with low-level programming, and works toward more generalized teaching.
•
From the Top Down - This is the opposite direction. This focuses on what you want to do with the computer, and teaches you how to break it down more and more until you get to the low levels.
•
From the Middle - This is characterized by books which teach a specific programming language or API. These are not as concerned with concepts as they are with specifics.
Different people like different approaches, but a good programmer takes all of them into account. The bottom-up approaches help you understand the machine aspects, the top-down approaches help you understand the problem-area aspects, and the middle approaches help you with practical questions and answers. To leave any of these aspects out would be a mistake. Computer Programming is a vast subject. As a programmer, you will need to be prepared to be constantly learning and pushing your limits. These books will help you do that. They not only teach their subjects, but also teach various ways and methods of thinking. As Alan Perlis said, "A language that doesn’t affect the way you think about programming is not worth knowing" (). If you are constantly looking for new and better ways of doing and thinking, you will make a successful programmer. If you do not seek to enhance yourself, "A little sleep, a little slumber, a little folding of the hands to rest - and poverty will come on you like a
233
Chapter 13. Moving On from Here bandit and scarcity like an armed man." (Proverbs 24:33-34 NIV). Perhaps not quite that severe, but still, it’s best to always be learning. These books were selected because of their content and the amount of respect they have in the computer science world. Each of them brings something unique. There are many books here. The best way to start would be to look through online reviews of several of the books, and find a starting point that interests you.
From the Bottom Up This list is in the best reading order I could find. It’s not necessarily easiest to hardest, but based on subject matter. •
Programming from the Ground Up by Jonathan Bartlett
•
Introduction to Algorithms by Thomas H. Cormen, Charles E. Leiserson, and Ronald L. Rivest
•
The Art of Computer Programming by Donald Knuth (3 volume set - volume 1 is the most important)
•
Programming Languages by Samuel N. Kamin
•
Modern Operating Systems by Andrew Tanenbaum
•
Linkers and Loaders by John Levine
•
Computer Organization and Design: The Hardware/Software Interface by David Patterson and John Hennessy
From the Top Down These books are arranged from the simplest to the hardest. However, they can be read in any order you feel comfortable with.
234
Chapter 13. Moving On from Here •
How to Design Programs by Matthias Felleisen, Robert Bruce Findler, Matthew Flatt, and Shiram Krishnamurthi, available online at
•
Simply Scheme: An Introduction to Computer Science by Brian Harvey and Matthew Wright
•
How to Think Like a Computer Scientist: Learning with Python by Allen Downey, Jeff Elkner, and Chris Meyers, available online at
•
Structure and Interpretation of Computer Programs by Harold Abelson and Gerald Jay Sussman with Julie Sussman, available online at
•
Design Patterns by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides
•
What not How: The Rules Approach to Application Development by Chris Date
•
The Algorithm Design Manual by Steve Skiena
•
Programming Language Pragmatics by Michael Scott
•
Essentials of Programming Languages by Daniel P. Friedman, Mitchell Wand, and Christopher T. Haynes
From the Middle Out Each of these is the best book on its subject. If you need to know these languages, these will tell you all you need to know. •
Programming Perl by Larry Wall, Tom Christiansen, and Jon Orwant
•
Common LISP: The Language by Guy R. Steele
•
ANSI Common LISP by Paul Graham
•
The C Programming Language by Brian W. Kernighan and Dennis M. Ritchie
235
Chapter 13. Moving On from Here •
The Waite Group’s C Primer Plus by Stephen Prata
•
The C++ Programming Language by Bjarne Stroustrup
•
Thinking in Java by Bruce Eckel, available online at
•
The Scheme Programming Language by Kent Dybvig
•
Linux Assembly Language Programming by Bob Neveln
Specialized Topics These books are the best books that cover their topic. They are thorough and authoritative. To get a broad base of knowledge, you should read several outside of the areas you normally program in. •
Practical Programming - Programming Pearls and More Programming Pearls by Jon Louis Bentley
•
Databases - Understanding Relational Databases by Fabian Pascal
•
Project Management - The Mythical Man-Month by Fred P. Brooks
•
UNIX Programming - The Art of UNIX Programming by Eric S. Raymond, available online at
•
UNIX Programming - Advanced Programming in the UNIX Environment by W. Richard Stevens
•
Network Programming - UNIX Network Programming (2 volumes) by W. Richard Stevens
•
Generic Programming - Modern C++ Design by Andrei Alexandrescu
•
Compilers - The Art of Compiler Design: Theory and Practice by Thomas Pittman and James Peters
236
Chapter 13. Moving On from Here •
Compilers - Advanced Compiler Design and Implementation by Steven Muchnick
•
Development Process - Refactoring: Improving the Design of Existing Code by Martin Fowler, Kent Beck, John Brant, William Opdyke, and Don Roberts
•
Typesetting - Computers and Typesetting (5 volumes) by Donald Knuth
•
Cryptography - Applied Cryptography by Bruce Schneier
•
Linux - Professional Linux Programming by Neil Matthew, Richard Stones, and 14 other people
•
Linux Kernel - Linux Device Drivers by Alessandro Rubini and Jonathan Corbet
•
Open Source Programming - The Cathedral and the Bazaar: Musings on Linux and Open Source by an Accidental Revolutionary by Eric S. Raymond
•
Computer Architecture - Computer Architecture: A Quantitative Approach by David Patterson and John Hennessy
Further Resources on Assembly Language In assembly language, your best resources are on the web. • - a great resource for Linux assembly language programmers
• - a repository of reference material on x86, x86-64, and compatible processors
• - Dr. Dobb’s Journal Microprocessor Resources
• - Dr. Paul Carter’s PC Assembly Language Page
• - The Art of Assembly Home Page
237
Chapter 13. Moving On from Here • - Intel’s manuals for their processors
• - Jan Wagemaker’s Linux assembly language examples
• - Paul Hsieh’s x86 Assembly Page
238
Appendix A. GUI Programming Introduction to GUI Programming The purpose of this appendix is not to teach you how to do Graphical User Interfaces. It is simply meant to show how writing graphical applications is the same as writing other applications, just using an additional library to handle the graphical parts. As a programmer you need to get used to learning new libraries. Most of your time will be spent passing data from one library to another.
The GNOME Libraries The GNOME projects is one of several projects to provide a complete desktop to Linux users. The GNOME project includes a panel to hold application launchers and mini-applications called applets, several standard applications to do things such as file management, session management, and configuration, and an API for creating applications which fit in with the way the rest of the system works. One thing to notice about the GNOME libraries is that they constantly create and give you pointers to large data structures, but you never need to know how they are laid out in memory. All manipulation of the GUI data structures are done entirely through function calls. This is a characteristic of good library design. Libraries change from version to version, and so does the data that each data structure holds. If you had to access and manipulate that data yourself, then when the library is updated you would have to modify your programs to work with the new library, or at least recompile them. When you access the data through functions, the functions take care of knowing where in the structure each piece of data is. The pointers you receive from the library are opaque - you don’t need to know specifically what the structure they are pointing to looks like, you only need to know the functions that will properly manipulate it. When designing libraries, even for use within only one program, this is a good practice to keep in mind.
239
Appendix A. GUI Programming This chapter will not go into details about how GNOME works. If you would like to know more, visit the GNOME developer web site at. This site contains tutorials, mailing lists, API documentation, and everything else you need to start programming in the GNOME environment.
A Simple GNOME Program in Several Languages This program will simply show a Window that has a button to quit the application. When that button is clicked it will ask you if you are sure, and if you click yes it will close the application. To run this program, type in the following as gnome-example.s: #PURPOSE: # # # #INPUT: # # #OUTPUT: # #PROCESS: # # # # #
This program is meant to be an example of what GUI programs look like written with the GNOME libraries The user can only click on the "Quit" button or close the window The application will close If the user clicks on the "Quit" button, the program will display a dialog asking if they are sure. If they click Yes, it will close the application. Otherwise it will continue running
.section .data ###GNOME definitions - These were found in the GNOME # header files for the C language # and converted into their assembly
240
Appendix A. GUI Programming #:
241
Appendix A. GUI Programming .ascii "I Want to Quit the GNOME Example Program\0" quit_question: .ascii "Are you sure you want to quit?\0"
.section .bss #Variables to save the created widgets in .equ WORD_SIZE, 4 .lcomm appPtr, WORD_SIZE .lcomm btnQuit, WORD_SIZE .section .text .globl main .type main,@function main: pushl %ebp movl %esp, %ebp #Initialize GNOME libraries pushl 12(%ebp) #argv pushl 8(%ebp) #argc pushl $app_version pushl $app_id call gnome_init addl $16, %esp #recover the stack #Create new application window pushl $app_title #Window title pushl $app_id #Application ID call gnome_app_new addl $8, %esp #recover the stack movl %eax, appPtr #save the window pointer
242
Appendix A. GUI Programming #Create new button pushl $button_quit_text #button text call gtk_button_new_with_label addl $4, %esp #recover the stack movl %eax, btnQuit #save the button pointer #Make pushl pushl call addl
the button show up inside the application window btnQuit appPtr gnome_app_set_contents $8, %esp
#Makes the button show up (only after it’s window #shows up, though) pushl btnQuit call gtk_widget_show addl $4, %esp #Makes the application window show up pushl appPtr call gtk_widget_show addl $4, %esp #Have GNOME call our delete_handler function #whenever a "delete" event occurs pushl $NULL #extra data to pass to our #function (we don’t use any) pushl $delete_handler #function address to call pushl $signal_delete_event #name of the signal pushl appPtr #widget to listen for events on call gtk_signal_connect addl $16, %esp #recover stack #Have GNOME call our destroy_handler function #whenever a "destroy" event occurs
243
Appendix A. GUI Programming pushl $NULL
#extra data to pass to our #function (we don’t
244
Appendix A. GUI Programming #is being removed, we simply want the event loop to #quit destroy_handler: pushl %ebp movl %esp, %ebp #This causes gtk to exit it’s pushl $GNOME_STOCK_BUTTON_NO pushl $GNOME_STOCK_BUTTON_YES pushl $GNOME_MESSAGE_BOX_QUESTION pushl $quit_question call gnome_message_box_new addl $16, %esp
#End of #Button #Button #Dialog #Dialog
buttons 1 0 type mesasge
#recover stack
245
Appendix A. GUI Programming #’s event loop. Otherwise, do nothing cmpl $0, %eax jne click_handler_end call
gtk_main_quit
click_handler_end: leave
246
Appendix A. GUI Programming ret
To build this application, execute the following commands: as gnome-example.s -o gnome-example.o gcc gnome-example.o ‘gnome-config --libs gnomeui‘ \ -o gnome-example
Then type in ./gnome-example to run it. This program, like most GUI programs, makes heavy use of passing pointers to functions as parameters. In this program you create widgets with the GNOME functions and then you set up functions to be called when certain events happen. These functions are called callback functions. All of the event processing is handled by the function gtk_main, so you don’t have to worry about how the events are being processed. All you have to do is have callbacks set up to wait for them. Here is a short description of all of the GNOME functions that were used in this program: gnome_init Takes the command-line arguments, argument count, application id, and application version and initializes the GNOME libraries. gnome_app_new Creates a new application window, and returns a pointer to it. Takes the application id and the window title as arguments. gtk_button_new_with_label Creates a new button and returns a pointer to it. Takes one argument - the text that is in the button.
247
Appendix A. GUI Programming gnome_app_set_contents This takes a pointer to the gnome application window and whatever widget you want (a button in this case) and makes the widget be the contents of the application window gtk_widget_show This must be called on every widget created (application window, buttons, text entry boxes, etc) in order for them to be visible. However, in order for a given widget to be visible, all of it’s parents must be visible as well. gtk_signal_connect This is the function that connects widgets and their signal handling callback functions. This function takes the widget pointer, the name of the signal, the callback function, and an extra data pointer. After this function is called, any time the given event is triggered, the callback will be called with the widget that produced the signal and the extra data pointer. In this application, we don’t use the extra data pointer, so we just set it to NULL, which is 0. gtk_main This function causes GNOME to enter into it’s main loop. To make application programming easier, GNOME handles the main loop of the program for us. GNOME will check for events and call the appropriate callback functions when they occur. This function will continue to process events until gtk_main_quit is called by a signal handler. gtk_main_quit This function causes GNOME to exit it’s main loop at the earliest opportunity. gnome_message_box_new This function creates a dialog window containing a question and response
248
Appendix A. GUI Programming buttons. It takes as parameters the message to display, the type of message it is (warning, question, etc), and a list of buttons to display. The final parameter should be NULL to indicate that there are no more buttons to display. gtk_window_set_modal This function makes the given window a modal window. In GUI programming, a modal window is one that prevents event processing in other windows until that window is closed. This is often used with Dialog windows. gnome_dialog_run_and_close This function takes a dialog pointer (the pointer returned by gnome_message_box_new can be used here) and will set up all of the appropriate signal handlers so that it will run until a button is pressed. At that time it will close the dialog and return to you which button was pressed. The button number refers to the order in which the buttons were set up in gnome_message_box_new.
The following is the same program written in the C language. Type it in as gnome-example-c.c: /* PURPOSE: This program is meant to be an example of what GUI programs look like written with the GNOME libraries */ #include <gnome.h> /* Program definitions */ #define MY_APP_TITLE "Gnome Example Program" #define MY_APP_ID "gnome-example" #define MY_APP_VERSION "1.000"
249
Appendix A. GUI Programming */
250
Appendix A. GUI Programming "destroy" signal */ int destroy_handler(gpointer window, GdkEventAny *e, gpointer data) { /* Leave GNOME event loop */ gtk_main_quit(); return 0; } /* Function to receive the "delete_event" signal */ int delete_handler(gpointer window, GdkEventAny *e, gpointer data) { return 0; }
251
Appendix A. GUI Programming /*’s event loop. Otherwise, do nothing */ if(buttonClicked == 0) { gtk_main_quit(); } return 0; }
To compile it, type
252
Appendix A. GUI Programming gcc gnome-example-c.c ‘gnome-config --cflags \ --libs gnomeui‘ -o gnome-example-c
Run it by typing ./gnome-example-c. Finally, we have a version in Python. Type it in as gnome-example.py: #PURPOSE: # # #
This program is meant to be an example of what GUI programs look like written with the GNOME libraries
#Import GNOME libraries import gtk import gnome.ui ####DEFINE CALLBACK FUNCTIONS FIRST#### #In Python, functions have to be defined before #they are used, so we have to define our callback #functions first. def destroy_handler(event): gtk.mainquit() return 0 def delete_handler(window, event): return 0 def click_handler(event): #Create the "Are you sure" dialog msgbox = gnome.ui.GnomeMessageBox( "Are you sure you want to quit?", gnome.ui.MESSAGE_BOX_QUESTION, gnome.ui.STOCK_BUTTON_YES, gnome.ui.STOCK_BUTTON_NO)
253
Appendix A. GUI Programming msgbox.set_modal(1) msgbox.show() result = msgbox.run_and_close() #Button 0 is the Yes button. If this is the #button they clicked on, tell GNOME to quit #it’s)
254
Appendix A. GUI Programming #Transfer control to GNOME gtk.mainloop()
To run it type python gnome-example.py.
GUI Builders In the previous example, you have created the user-interface for the application by calling the create functions for each widget and placing it where you wanted it. However, this can be quite burdensome for more complex applications. Many programming environments, including GNOME, have programs called GUI builders that can be used to automatically create your GUI for you. You just have to write the code for the signal handlers and for initializing your program. The main GUI builder for GNOME applications is called GLADE. GLADE ships with most Linux distributions. There are GUI builders for most programming environments. Borland has a range of tools that will build GUIs quickly and easily on Linux and Win32 systems. The KDE environment has a tool called QT Designer which helps you automatically develop the GUI for their system. There is a broad range of choices for developing graphical applications, but hopefully this appendix gave you a taste of what GUI programming is like.
255
Appendix A. GUI Programming
256
Appendix B. Common x86 Instructions Reading the Tables The tables of instructions presented in this appendix include: •
The instruction code
•
The operands used
•
The flags used
•.
257
Appendix B. Common x86 Instructions. first operand to the second, and, if there is an overflow, sets overflow and carry to true. This is usually used for operations larger than a machine word. The addition on the least-significant first operand to the second, storing the result in the second. If the result is larger than the destination register, the overflow and carry bits are set to true. This instruction operates on both signed and unsigned integers. cdq O/S/Z/A/P/C Converts the %eax word into the double-word consisting of %edx:%eax with sign extension. The q signifies that it is a quad-word. It’s actually a double-word, but it’s called a quad-word because of the terminology used in the 16-bit days. This is usually used before issuing an idivl instruction. cmpl I/R/M, R/M O/S/Z/A/P/C Compares two integers. It does this by subtracting the first operand from the second. It discards the results, but sets the flags specified. The %eax register contains the resulting quotient, and the %edx register contains the resulting remainder. If the quotient is too large to fit two’s first overflow and carry flags to false. notl R/M Performs a logical not on each bit in the operand. Also known as a one’s complement. orl I/R/M, R/M O/S/Z/A/P/C Performs a logical or between the two operands, and stores the result in the second operand. Sets the overflow and carry flags to false. rcll I/%cl, R/M O/C Rotates the given location’s bits to the left the number of times in the first operand, which is either an immediate-mode value or the register %cl. The carry flag is included in the rotation, making it use 33 bits instead of 32. Also sets the overflow flag. rcrl I/%cl, R/M O/C Same as above, but rotates right. roll I/%cl, R/M O/C Rotate bits to the left. It sets the overflow and carry flags, but does not count the carry flag as part of the rotation. The number of bits to roll is either specified in immediate mode or is contained in the %cl register. rorl I/%cl, R/M O/C Same as above, but rotates right. sall I/%cl, R/M C Arithmetic shift left. The sign bit is shifted out to the carry flag, and a zero bit is placed in the least significant bit. Other bits are simply shifted to the left. This is the same as the regular shift left. The number of bits to shift is either specified in immediate mode or is contained in the %cl register. sarl I/%cl, R/M C
262
Appendix B. Common x86 Instructions Instruction Operands Affected Flags Arithmetic shift right. The least significant bit is shifted out to the carry flag. The sign bit is shifted in, and kept as the sign bit. Other bits are simply shifted to the right. The number of bits to shift is either specified in immediate mode or is contained in the %cl register. shll I/%cl, R/M C Logical shift left. This shifts all bits to the left (sign bit is not treated specially). The leftmost bit is pushed to the carry flag. The number of bits to shift is either specified in immediate mode or is contained in the %cl register. shrl I/%cl, R/M C Logical shift right. This shifts all bits in the register to the right (sign bit is not treated specially). The rightmost bit is pushed to the carry flag. The number of bits to shift is either specified in immediate mode or is contained in the %cl register. testl I/R/M, R/M O/S/Z/A/P/C Does a logical and of both operands and discards the results, but sets the flags accordingly. xorl I/R/M, R/M O/S/Z/A/P/C Does an exclusive or on the two operands, and stores the result in the second operand. Sets the overflow and carry flags to false.
Flow Control Instructions These instructions may alter the flow: • [n]a[e] - above (unsigned greater than). An n can be added for "not" and an e can be added for "or equal to" • [n]b[e]
- below (unsigned less than)
• [n]e
- equal to
• [n]z
- zero
• [n]g[e]
- greater than (signed comparison)
• [n]l[e]
- less than (signed comparison)
• [n]c
- carry flag set
• [n]o
- overflow flag set
• [p]p
- parity flag set
• [n]s
- sign flag set
• ecxz
- defined files. .include FILE
266
Appendix B. Common x86 Instructions Directive Operands Includes the given file just as if it were typed in right there. .lcomm SYMBOL, SIZE This is used in the .bss section to specify storage that should be allocated when the program is executed. Defines specified. .section SECTION NAME Switches the section that is being worked on. Common sections include .text (for code), .data (for data embedded in the program itself), and .bss (for uninitialized global data). .type SYMBOL, @function Tells the linker that the given symbol is a function.Ž syntax) is different. It is the same assembly language for the same platform, but it looks different. Some of the differences include: •
In Intel syntax, the operands of instructions are often reversed. The destination operand is listed before the source operand.
267
Appendix B. Common x86 Instructions •
In Intel syntax, registers are not prefixed with the percent sign (%).
•
In Intel syntax, a dollar-sign ($) is not required to do immediate-mode addressing. Instead, non-immediate addressing is accomplished by surrounding the address with brackets ([]).
•
In Intel syntax, the instruction name does not include the size of data being moved. If that is ambiguous, it is explicitly stated as BYTE, WORD, or DWORD immediately after the instruction name.
•
The way that memory addresses are represented in Intel assembly language is much different (shown below).
•".
• it’s AT&T counterpart because it spells out exactly how the address will be computed. However, but the order of operands in Intel syntax can be confusing.
268
Appendix B. Common x86 Instructions:: •
Volume 1: System Programming Guide ()
•
Volume 2: Instruction Set Reference ()
•
Volume 3: System Programming Guide ()
In addition, you can find a lot of information in the manual for the GNU assembler, available online at. Similarly, the manual for the GNU linker is available online at.
269
Appendix B. Common x86 Instructions
270
Appendix C. Important System Calls These are some of the more important system calls to use when dealing with Linux. For most cases, however, it is best to use library functions rather than direct system calls, because the system calls were designed to be minimalistic while the library functions were designed to be easy to program with. For information about the Linux C library, see the manual at Remember that %eax holds the system call numbers, and that the return values and error codes are also stored in %eax. Table C-1. Important Linux System Calls
1
Name exit
3
read
4
write
file descriptor
5
open
nulloption terminatedlist file name
6
file descriptor
%eax
Notes Exits the program
%ebx
%ecx
%edx
return value (int) file descriptor
buffer start
buffer Reads into the given buffer size (int)
buffer start
buffer Writes the buffer to the file size (int) descriptor permissionOpens the given file. Returns mode the file descriptor or an error number. Closes the give file descriptor
271
Appendix C. Important System Calls
12
Name chdir
19
lseek
20
getpid
39
mkdir
40
rmdir
41
dup
42
pipe
%eax
272
%ebx
%ecx
nullterminated directory name file de- offset scriptor
%edx
Notes Changes the current directory of your program.
mode
Repositions where you are in the given file. The mode (called the "whence") should be 0 for absolute positioning, and 1 for relative positioning. Returns the process ID of the current process. Creates the given directory. Assumes all directories leading up to it already exist.
nullpermission terminatedmode directory name nullterminated directory name file descriptor pipe array
Removes the given directory.
Returns a new file descriptor that works just like the existing file descriptor. Creates two file descriptors, where writing on one produces data to read on the other and vice-versa. %ebx is a pointer to two words of storage to hold the file descriptors.
Appendix C. Important System Calls %ebx
45
Name brk
54
ioctl
file descriptor
%eax
%ecx
new system break
request
Notes Sets the system break (i.e. the end of the data section). If the system break is 0, it simply returns the current system break. argumentsThis is used to set parameters on device files. It’s actual usage varies based on the type of file or device your descriptor references. %edx
A more complete listing of system calls, along with additional information is available at You can also get more information about a system call by typing in man 2 SYSCALLNAME which will return you the information about the system call from section 2 of the UNIX manual. However, this refers to the usage of the system call from the C programming language, and may or may not be directly helpful. For information on how system calls are implemented on Linux, see the Linux Kernel 2.4 Internals section on how system calls are implemented at
273
Appendix C. Important System Calls
274
Appendix D. Table of ASCII Codes To use this table, simply find the character or escape that you want the code for, and add the number on the left and the top. Table D-1. Table of ASCII codes in decimal
0 8 16 24 32 40 48 56 64 72 80 88 96 104 112 120
+0 NUL BS DLE CAN ( 0 8 @ H P X ‘ h p x
+1 SOH HT DC1 EM ! ) 1 9 A I Q Y a i q y
+2 STX LF DC2 SUB " * 2 : B J R Z b j r z
+3 ETX VT DC3 ESC # + 3 ; C K S [ c k s {
+4 EOT FF DC4 FS $ , 4 < D L T \ d l t |
+5 ENQ CR NAK GS % 5 = E M U ] e m u }
+6 ACK SO SYN RS & . 6 > F N V ^ f n v ~
+7 BEL SI ETB US ’ / 7 ? G O W _ g o w DEL
ASCII is actually being phased out in favor of an international standard known as Unicode, which allows you to display any character from any known writing system in the world. As you may have noticed, ASCII only has support for English characters. Unicode is much more complicated, however, because it requires more than one byte to encode a single character. There are several
275
Appendix D. Table of ASCII Codes different methods for encoding Unicode characters. The most common is UTF-8 and UTF-32. UTF-8 is somewhat backwards-compatible with ASCII (it is stored the same for English characters, but expands into multiple byte for international characters). UTF-32 simply requires four bytes for each character rather than one. Windows速 uses UTF-16, which is a variable-length encoding which requires at least 2 bytes per character, so it is not backwards-compatible with ASCII. A good tutorial on internationalization issues, fonts, and Unicode is available in a great Article by Joe Spolsky, called "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)", available online at
276
Appendix E. C Idioms in Assembly Language This appendix is for C programmers learning assembly language. It is meant to give a general idea about how C constructs can be implemented in assembly language. If Statement In C, an if statement consists of three parts - the condition, the true branch, and the false branch. However, since assembly language is not a block structured language, you have to work a little to implement the block-like nature of C. For example, look at the following C code:
277
Appendix E. C Idioms in Assembly Language false_branch:
#This label is unnecessary, #only here for documentation #False Branch Code Here #Jump to recovergence point jmp reconverge
true_branch: #True Branch Code Here
reconverge: #Both branches recoverge to this point
As you can see, since assembly language is linear, the blocks have to jump around each other. Recovergence is handled by the programmer, not the system. A case statement is written just like a sequence of if statements.
Function Call A function call in assembly language simply requires pushing the arguments to the function onto the stack in reverse order, and issuing a call instruction. After calling, the arguments are then popped back off of the stack. For example, consider the C code: printf("The number is %d", 88);
In assembly language, this would be rendered as: .section .data text_string: .ascii "The number is %d\0"
278
Appendix E. C Idioms in Assembly Language .section .text pushl $88 pushl $text_string call printf popl %eax popl %eax #%eax is just a dummy variable, #nothing is actually being done #with the value. You can also #directly re-adjust %esp to the #proper location.
Variables and Assignment Global and static variables are declared using .data or .bss entries. Local variables are declared by reserving space on the stack at the beginning of the function. This space is given back at the end of the function. Interestingly, global variables are accessed differently than local variables in assembly language. Global variables are accessed using direct addressing, while local variables are accessed using base pointer addressing. For example, consider the following C code:
movl movl
$1, my_local_var(%ebp) $2, my_global_var
movl popl ret
%ebp, %esp %ebp
#Clean up function and return
What may not be obvious is that accessing the global variable takes fewer machine cycles than accessing the global variable. However, that may not matter because the stack is more likely to be in physical memory (instead of swap) than the global variable is. Also note that in the C programming language, after the compiler loads a value into a register, that value will likely stay in that register until that register is needed for something else. It may also move registers. For example, if you have a variable foo, it may start on the stack, but the compiler will eventually move it into registers for processing. If there aren’t many variables in use, the value may simply stay in the register until it is needed again. Otherwise, when that register is needed for something else, the value, if it’s changed, is copied back to its corresponding memory location. In C, you can use the keyword volatile to make sure all modifications and references to the variable are done to the memory
280
Appendix E. C Idioms in Assembly Language location itself, rather than a register copy of it, in case other processes, threads, or hardware may be modifying the value while your function is running.
Loops Loops work a lot like if statements in assembly language - the blocks are formed by jumping around. In C, a while loop consists of a loop body, and a test to determine whether or not it is time to exit the loop. A for loop is exactly the same, with optional initialization and counter-increment sections. These can simply be moved around to make a while loop. In C, a while loop looks like this: while(a < b) { /* Do stuff here */ } /* Finished Looping */
This can be rendered in assembly language like this: loop_begin: movl a, %eax movl b, %ebx cmpl %eax, %ebx jge loop_end loop_body: #Do stuff here jmp loop_begin loop_end: #Finished looping
281
Appendix E. C Idioms in Assembly Language here
One thing to notice is that the loop instruction requires you to be counting backwards to zero. If you need to count forwards or use another ending number, you should use the loop form which does not include the loop instruction. For really tight loops of character string operations, there is also the rep instruction, but we will leave learning about that as an exercise to the reader.
Structs Structs are simply descriptions of memory blocks. For example, in C you can say:
282
Appendix E. C Idioms in Assembly Language struct person { char firstname[40]; char lastname[40]; int age; };
This doesn’t
283
Appendix E. C Idioms in Assembly Language .equ P_VAR, 0 - PERSON_SIZE #Do Stuff Here #Standard function ending movl %ebp, %esp popl %ebp ret
To access structure members, you just have to use base pointer addressing with the offsets defined above. For example, in C you could set the person’s age like this: p.age = 30;
In assembly language it would look like this: movl $30, P_VAR + PERSON_AGE_OFFSET(%ebp)
Pointers Pointers are very easy. Remember, pointers are simply the address that a value resides at. Let’s start by taking a look at global variables. For example: int global_data = 30;
In assembly language, this would be: .section .data global_data: .long 30
Taking the address of this data in C: a = &global_data;
284
Appendix E. C Idioms in Assembly Language Taking the address of this data in assembly language: movl $global_data, %eax
You see, with assembly language, you are almost always accessing memory through pointers. That’s
285
Appendix E. C Idioms in Assembly Language
As you can see, to take the address of a local variable, the address has to be computed the same way the computer computes the addresses in base pointer addressing. There is an easier way - the processor provides the instruction leal, which stands for "load effective address". This lets the computer compute the address, and then load it wherever you want. So, we could just say: #b = &a leal A_VAR(%ebp), %eax movl %eax, B_VAR(%ebp)
It’s the same number of lines, but a little cleaner. Then, to use this value, you simply have to move it to a general-purpose register and use indirect addressing, as shown in the example above.
Getting GCC to Help One of the nice things about GCC is it’s ability to spit out assembly language code. To convert a C language file to assembly, you can simply do:
286
Appendix E. C Idioms in Assembly Language gcc -S file.c
The output will be in file.s. It’s not the most readable output - most of the variable names have been removed and replaced either with numeric stack locations or references to automatically-generated labels. To start with, you probably want to turn off optimizations with -O0 so that the assembly language output will follow your source code better. Something else you might notice is that GCC reserves more stack space for local variables than we do, and then AND’s %esp 1 This is to increase memory and cache efficiency by double-word aligning variables. Finally, at the end of functions, we usually do the following instructions to clean up the stack before issuing a ret instruction: movl %ebp, %esp popl %ebp
However, GCC output will usually just include the instruction leave. This instruction is simply the combination of the above two instructions. We do not use leave in this text because we want to be clear about exactly what is happening at the processor level. I encourage you to take a C program you have written and compile it to assembly language and trace the logic. Then, add in optimizations and try again. See how the compiler chose to rearrange your program to be more optimized, and try to figure out why it chose the arrangement and instructions it did.
1.
Note that different versions of GCC do this differently.
287
Appendix E. C Idioms in Assembly Language
288
Appendix F. Using the GDB Debugger By the time you read this appendix, you will likely have written at least one program with an error in it. In assembly language, even minor errors usually have results such as the whole program crashing with a segmentation fault error. In most programming languages, you can simply print out the values in your variables as you go along, and use that output to find out where you went wrong. In assembly language, calling output functions is not so easy. Therefore, to aid in determining the source of errors, you must use a source debugger. A debugger is a program that helps you find bugs by stepping through the program one step at a time, letting you examine memory and register contents along the way. A source debugger is a debugger that allows you to tie the debugging operation directly to the source code of a program. This means that the debugger allows you to look at the source code as you typed it in - complete with symbols, labels, and comments. The debugger we will be looking at is GDB - the GNU Debugger. This application is present on almost all GNU/Linux distributions. It can debug programs in multiple programming languages, including assembly language. An Example Debugging Session The best way to explain how a debugger works is by using it. The program we will be using the debugger on is the maximum program used in Chapter 3. Let’s say that you entered the program perfectly, except that you left out the line: incl %edi
When you run the program, it just goes in an infinite
Appendix F. Using the GDB Debugger as --gstabs maximum.s -o maximum.o
Linking would be the same as normal. "stabs" is the debugging format used by GDB. Now, to run the program under the debugger, you would type in gdb ./maximum. Be sure that the source files infinite find bugs in a program is to follow the flow of the program to see where it is branching incorrectly. To follow the flow find out what the problem is, let’s first prefixed with dollar signs rather than percent signs. Your screen should have this on it: (gdb) print/d $eax $1 = 3 (gdb)
This means that the result of your first inquiry is 3. Every inquiry you make will be assigned a number prefixed with a dollar sign. Now, if you look back into the code, you will find that 3 is the first number in the list of numbers to search through. If you step through the loop a few more times, you will find. Let’s. It’s first element of the array. This should cause you to ask yourself two questions - what is the purpose of %edi, and how should its value be changed? To answer the first find errors in your programs.
Breakpoints and Other GDB Features The program we entered in the last section had an infinite loop, and could be easily stopped using control-c. Other programs may simply abort or finish with errors. In these cases, control-c doesn’t help, because by the time you press control-c, the program is already finished. To fix. Then, when the program crosses line 27, it will stop running, and print out the current line and instruction. You can then step through the program from that point and examine registers and memory. To look at the lines and line numbers of your program, you can simply use the command don’t One problem that GDB has is with handling interrupts. Often times GDB will miss the instruction that immediately follows an interrupt. The instruction is actually executed, but GDB doesn’t] ...
Running the Program run [arg1] [arg2] ... set args arg1 [arg2] ... show args Using Breakpoints info breakpoints
break linenum break *addr break fn condition bpnum expr
Exit GDB Print description of debugger command cmd. Without cmd, prints a list of topics. Add directories dir1, dir2, etc. to the list of directories searched for source files. Run the program with command line arguments arg1, arg2, etc. Set the program’s command-line arguments to arg1, arg2, etc. Print the program’s specified. Clear the breakpoint at memory address addr. Clear the breakpoint at function fn, or the current breakpoint. Clear the breakpoint at line number linenum. Disable breakpoints bpnum1, bpnum2, etc., or all breakpoints if none specified. Enable breakpoints bpnum1, bpnum2, etc., or all breakpoints if none specified. "Step over" the next instruction (doesn’t follow function calls). "Step into" the next instruction (follows function calls). "Step out" of the current function.
finish (floating point). x/rsf addr Print the contents of memory address addr using repeat count r, size s, and format f . Repeat count defaults to 1 if not specified. Size can be b (byte), h (halfword), w (word), or g (double word). Size defaults to word if not specified.
298
Print the top of the call stack. Move the context toward the bottom of the call stack. Move the context toward the top of the call stack.
Appendix G. Document History •
12/17/2002 - Version 0.5 - Initial posting of book under GNU FDL
•
07/18/2003 - Version 0.6 - Added ASCII appendix, finished the discussion of the CPU in the Memory chapter, reworked exercises into a new format, corrected several errors. Thanks to Harald Korneliussen for the many suggestions and the ASCII table.
•
01/11/2004 - Version 0.7 - Added C translation appendix, added the beginnings of an appendix of x86 instructions, added the beginnings of a GDB appendix, finished out the files chapter, finished out the counting chapter, added a records chapter, created a source file of common linux definitions, corrected several errors, and lots of other fixes
•
01/22/2004 - Version 0.8 - Finished GDB appendix, mostly finished w/ appendix of x86 instructions, added section on planning programs, added lots of review questions, and got everything to a completed, initial draft state.
•
01/29/2004 - Version 0.9 - Lots of editting of all chapters. Made code more consistent and made explanations clearer. Added some illustrations.
•
01/31/2004 - Version 1.0 - Rewrote chapter 9. Added full index. Lots of minor corrections.
299
Appendix G. Document History
300
Appendix H. GNU Free Documentation License
301
Appendix H. GNU Free Documentation License
302
Appendix H. GNU Free Documentation License
303
Appendix H. GNU Free Documentation License€˘. • B. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has less than five).
304
Appendix H. GNU Free Documentation License
305
Appendix H. GNU Free Documentation License the section titles. • M. Delete any section entitled “Endorsements”. Such a section may not be included in the Modified Version. •
306
Appendix H. GNU Free Documentation License
307
Appendix H. GNU Free Documentation License’s
308
Appendix H. GNU Free Documentation License.
309
Appendix H. GNU Free Documentation License
310
Appendix I. Personal Dedication There.
311
Appendix I. Personal Dedicationflags, flag,
314
C programming language, 52, 135, 215, 273, 277 cache, 227 cache hierarchies, 10 caching, 226 call, 52, 54, 62, 67, 263, 278 calling convention, 58 calling conventions, 52, 58 calling interface, 135 carry flag, fields, 95 file descriptors, 75, 78 files, 75, 79 finish, 294 flags, 194, 257 float, 138 flow infinite loop, 31 info, 294 info display, 294 info register, 292 info registers, 294 inline functions, 227 instruction, 126 instruction decoder, 9 instruction pointer, 13, 54 int, 27, 135, 201, 263 Intel syntax, 267 interpreter, 214 interrupts, 27, 294
316 file, 21 octal, 91, 199 offset, 16 offsets, 96 one’s complement, 261 open, 75, 91, 194, 271 operands, 24 optimization, 223 OR, 188 orl, 261 out-of-order execution, 10
overflow flag, 257 O_APPEND, 195 O_CREAT, 195 O_RDWR, 194 O_TRUNC, 195 O_WRONLY, 194 pad, 104 padding, 100 pages, 154 parallelization, 229 parameter, 69 parameters, 26, 49, 50, 54, 67, 135 parity flag, profiler, files, 79 rep, 282 resident set size, 155 ret, 52, 57, 263, 287 return address, 51, 54, 89 return value, 52, 58, 68 return values, 69 rmdir, 271 robust, 117, 117, 119 roll, 261 rorl, 261 rotate, 192
318 flag, 257 signed, 199 signed numbers, 198 skeleton code, 129 source code, 20 source file, 21 source operand, 43 special files, 79 special register, 55 special-purpose register, 13 special-purpose registers, 10, 25 stack, 53 stack frame, 55, 65 stack memory, 53 stack pointer, 55 two’s flag, 258
319
Published on Nov 13, 2011
DominickBruno,Jr. JonathanBartlett Editedby Toreceiveacopyofthisbookinelectronicform,pleasevisitthewebsite... | https://issuu.com/hohohotang/docs/assembly-language | CC-MAIN-2017-39 | refinedweb | 47,557 | 63.8 |
If you have a gameobject with a script running a current InvokeRepeating method and you set the gameobject to inactive, then back to to active, will the InvokeRepeating loop resume or will it have been cancelled outright?
By the way, to cancel an InvokeRepeating("someName" .) is very simple,
just use CancelInvoke("someName");
Answer by robertbu
·
May 18, 2013 at 06:16 AM
The answer is that the object will continue to execute the InvokeRepeating().
Deactivating a game object does not stop the InvokeRepeating().
To deactivate the whole game object: gameObject.SetActive(false)
Deactiving just the script component itself does not stop the InvokeRepeating().
to deactivate just the script component: this.enabled = false
BUT NOTE THAT COROUTINES ARE DIFFERENT
Note however that ordinary coroutines, do indeed get stopped, when you deactivate the game object. However if you deactivate only script itself then the coroutine does keep going.
For InvokeRepeating...
1) disable whole game object - InvokeRepeating does not stop
2) disable just the script component - InvokeRepeating does not stop
For coroutines...
3) disable whole game object - coroutine DOES stop
4) disable just the script component - coroutine does not stop
In all four cases, the repeat is "eliminated", it is NOT paused. If you again SetActive(true), in all four cases, the repeat does NOT continue where it left off.
.
When I have questions like this one, I just test it:
private var i = 0;
function Start() {
InvokeRepeating("CountUp", 0.0, 0.5);
Invoke("Disable", 3.0);
}
function Disable() {
gameObject.SetActive(false);
}
function CountUp() {
i = i+1;
Debug.Log("i=" + i);
}
to test all four situations, simply do this,
using UnityEngine;
using System.Collections;
public class CoTeste:MonoBehaviour
{
void Start ()
{
InvokeRepeating("_everySecondInvoked", 1.1f, 1.1f);
StartCoroutine(_everySecondCoroutine());
}
private void _everySecondInvoked()
{
Debug.Log("this I.R. appears every second "
+ Random.Range(1111111,9999999) );
}
private IEnumerator _everySecondCoroutine()
{
while(true)
{
Debug.Log("\t\t\t\tthis coroutine appears every second "
+ Random.Range(1111111,9999999) );
yield return new WaitForSeconds(Random.Range(1.1f,1.2f));
}
yield break;
}
}
Run the project, and simply in the editor try disabling just the script (un-tick the box in the inspector).
note that both the coroutine and the invokeRepating simply keep going forever.
Start over, and disable the whole game object (un-tick the box in the inspector).
note that the InvokeRepeating keeps going forever, BUT, the coroutine DOES STOP.
Simply use OnDisable()...
, or one of the similar routines, if you want something "custom" to happen when a game object (or just the script) is disabled.
OnDisable and the similar routines
This is completely commonplace. Indeed,
... You almost always use OnDisable() ...
.
when you launch a coroutine or invokeRepeating - unless it's a really trivial situation and it doesn't matter.
An excellent question and answer
But scripts stop running when de-activating an object, correct? So how is InvokeRepeating still running?
And you're right, this is testable. I usually google a question first and will post it as a question if it doesn't already exist, presuming it might save others time in the future! :)
Hi Essential - I think ultimately there's no "real" explanation for the difference between the four situations. It's really not worth worrying about. It's completely and totally normal in software broadly, that if you launch "some sort of process" (another thread, scene - whatever) then, naturally, that process is not particularly killed when the launcher process is killed. Again it's honestly not worth worrying about why Unity adopted, basically, the system of four points shown above.
If you want to make a situation where (say) invokes or coroutines are indeed killed when you kill the "launcher", that is trivial to do so (just use OnDisable, etc, with a line of code. Note that if Unity worked the "other" way in any of the four situations, and you needed it to work the 'other" way, again you'd just have to set that up yourself. (It can't "always work for everyone", they had to pick one way or the other.)
The bottom line is "everyone" who programs unity just has to know it works as per the four routes above - it's no big deal.
Why is the text in this so absurdly huge? Can an admin please fix this. No reason to put everything in giant bold lettering.
Answer by GingerLoaf
·
Mar 17, 2015 at 07:12 PM
This post is very old at this point, however I had some interesting thoughts that I wanted to share on this subject for any future viewers.
always like to think about the enabled property of a component as something closer to "allowUnityLifeCycleEvents" rather than enabled. An interesting example outside of the coroutine or invokerepeat case would be the case where I have (enabled) scriptA that references a disabled scriptB reference. ScriptA can invoke public facing members of scriptB despite the fact that scriptB is disabled. "Enabled" does not mean "nothing will function and everything gracefully pauses".. instead it only stops the built in unity lifecycle events from being triggered (Awake, Start, Update, LateUpdate, ect...). A good test/sandbox could be this:
public class TestClassA : MonoBehaviour {
private TestClassB m_classBReference = null;
public void Update()
{
m_classBReference.Update();
}
}
public class TestClassB : MonoBehaviour
{
public void Update()
{
Debug.Log("I am active!");
}
}
Create a new scene, create a gameobject and place a "TestClassA" component on it
Create another gameobject and place a "TestClassB" component on it
Drag and drop the gameobject with your "TestClassB" component on it onto the "Class B Reference" property exposed in the inspector for the gameobject with the TestClassA component
Run the scene
You should see the logs being printed out at first... now try disabling combinations of both scripts. If you disable TestClassB and leave TestClassA enabled, you should still see the logs. Play around with this and become comfortable with how it works.
Now in regard to the "I think my script should disable everything" mentality... Unity will not do this for you, but you have powerful tools and frameworks at your fingertips to accomplish something that you are comfortable with. You could create your own class to use instead of MonoBehaviour (pardon my awful programmer class name) named something like "DisableableBehaviour". This class can inherit from MonoBehaviour... then all you need to do is framework how you want it to work... for example: You could expose your own special function for starting coroutines or invokerepeat calls and have the class track them so that the class can cancel them on disable and restart them on enable. I'm certain there are tons of ways of doing this... just know that unity doesn't need to do it all. Coroutines and invoke calls are very useful in the fact that they do span across frames regardless of enable or disable states, but you can always code up something that works for you :)
Hi Ginger. Simply use "OnDisable" if you want something to happen when the gameObject, or, script is disabled. This is an utterly commonplace aspect of programming. (It's exactly like when you do cleanup along the lines of "when I am destroyed..." in any environent.) It' trivial, easy, and commonplace.
note again that
But generally - who can remember that 'exception' - just use "OnDisable" to do whatever you want when, well, the thing is disabled. It's one line of code.
Answer by nitsnbolts_unity
·
Dec 18, 2020 at 05:38 AM
Not sure if this was an option in Unity when this was posted - but using Cancellnvoke() on any Monobehaviour script stops all invoke Keep GameObjects From Enabling Again?
2
Answers
How to make an open and close box?,How to make open and close a box?
0
Answers
Toggling a script on/off using the keyboard?
2
Answers
Set Player 2 to use player 1's postion in world
1
Answer
gameobject.setActive(true) || (false) hiccups game for 3 to 5 seconds
4
Answers | https://answers.unity.com/questions/458780/if-you-disable-a-gameobject-does-an-invokerepeatin.html | CC-MAIN-2021-04 | refinedweb | 1,313 | 64.61 |
This is a new series Modules in Python.
Python Modules. There are different ways to import a module. This is also why Python comes with battery included
Importing Modules
Let’s how the different ways to import a module
import sys #access module, after this you can use sys.name to refer to things defined in module sys. from sys import stdout # access module without qualiying name. This reads from the module "sys" import "stdout", so that we would be able to refer "stdout"in our program. from sys import * # access all functions/classes in the sys module.
Catching Errors
I like to use the import statement to ensure that all modules can be loaded on the system. The Import Error basically means that you cannot use this module, and that you should look at the traceback to find out why.
Import sys try: import BeautifulSoup except ImportError: print 'Import not installed' sys.exit()
Recommended Python Training
For Python training, our top recommendation is DataCamp. | https://www.pythonforbeginners.com/modules-in-python/python-modules | CC-MAIN-2021-31 | refinedweb | 165 | 65.22 |
Reusable components adhering to the Flock Design written in VueJS
Flock Components for VueJS
Reusable components adhering to the Flock Design written in VueJS.
Installation and Usage:
- Just use
npm install --save @flockos/vue-components
- Now you can include the scripts by using following snippet:
import Components from '@flockos/vue-components'; // Global registration in your main.js/App.vue file Object.entried(Components).forEach((name, component) => { Vue.component(name, component); });
List of components:
All components are registered with the Vue global and are available for use. You do not need to re-register them.
Event Bus
You can use the Flock Component's own event bus to pass data around.
Events:
focusChanged: Whenever the document is clicked, this event is fired. The only parameter is
element which was clicked.
Usage:
import { eventBus } from '@flockos/vue-components'; eventBus.$on('focusChanged', (element) => { // Do a few things if focus changes. });
More events will be supported as needed.
Flock Button
Usage:
<flock-buttonSubmit</flock-button>
Events:
click: Emits the
click event when clicked.
Props:
styles: Custom styles for your button.
shape: Default is
default. Options are
default and
flat. Flat means that there's no hover state.
size: Size of the button. Possible values:
full,
half &
auto. Default is
auto.
small: Reduce padding and makes a smaller styled button. Default is
false.
loading: To show asynchronous operations, a loader circle shows up whenever this is set to
true.
disabled: Disables the button and applies an opacity to it.
type: The style of the button. Possible values are
primary,
secondary &
destructive. Default is primary.
invert: Replaces the color & background with each other.
Flock Radio
Usage:
<flock-radio> </flock-radio> <flock-radio> </flock-radio>
Flock Select
Usage:
<flock-select :
Events:
change: Whenever the
FlockSelect changes value, this event is fired with the new value as a parameter.
Props:
open: Initial state of the
FlockSelect dropdown.
options: Array of options. Every
option needs to be in the
{ label: 'Some Visible Text', value: String|Object|Number } format.
width: The width of the
FlockSelect component, if it needs to be constant.
v-model: The value that will dynamically change just like normal models in Vue.js.
Flock Modal
Usage:
<FlockModal @ List of devices! </FlockModal>
Events:
close: Fired whenever the modal is closed. User has to handle the close themselves using a
v-if.
Props:
closeOnBgClick: When set to
true, the modal will automatically emit the
close event whenever the background is clicked.
background: This sets the backdrop of th modal. Default is none.
title: The title of the
Modal.
Flock Banner
Usage:
<FlockBanner> This is a banner. </FlockBanner>
Props:
position: Position of the toast. Can be either
top or
bottom. Default is
bottom.
styles: A styles object to customize background, color etc. of your banner. By default, the banner will occupy 100% of the total width of the page.
Flock Toast
Usage:
<FlockToast v- Let's make a toast! </FlockToast>
Events:
toasthidden: Gets triggered when the toast is hidden, automatically or manually.
Props:
time: The time duration of the toast in
milliseconds. Default duration is 5000ms.
position: Position of the toast. Can be either
top or
bottom. Default is
bottom.
styles: A styles object to customize background and color of your toast.
Gotchas:
You need to control the visibility of the toast by supplying a
v-if conditional.
TODO: Make
Toast better so that a user can directly use it like:
eventBus.showToast(Some Text
, 4000) | https://vuejsexamples.com/reusable-components-adhering-to-the-flock-design-written-in-vuejs/ | CC-MAIN-2019-04 | refinedweb | 567 | 62.34 |
Parent Directory
|
Revision Log
moved to
add _q_unused_ to fix -Wunused-parameter gcc warnings
constify more strings
- update headers
- update copyright headers
- more whitespace cleanups. Added new whitespace test
add support from Gordon Malm for selecting which items to process
-.
- keep applets in alphabetical order
- initial commit of qimlate applet from tcort@gentoo (not finished)
- update some default binhosts
- update the way manpages are created when exit code from help2man & applet does not return 0; Enable qmerge applet by default but force env variable to control getting into its guts=
- better qlist -e matching mode to cmp full PV now. make applets optional
update copyright years
- make qmerge into an applet real quick
- added qatom and removed the need for the applets enum
-.
- lets go with realpath anyway for qfile handling of relative paths
cleanup license header
initial import of a new applet to build binary packages
- add option to optimize for size by disabling the color constants. We now search make.globals to fill PORTDIR just incase it's not set in make.conf or via the environment
import a new applet to manipulate portage xpak archives
- applets.h
This form allows you to request diffs between any two revisions of this file. For each of the two "sides" of the diff, select a symbolic revision name using the selection box, or choose 'Use Text Field' and enter a numeric revision. | http://sources.gentoo.org/cgi-bin/viewvc.cgi/gentoo-projects/portage-utils/applets.h?view=log | CC-MAIN-2014-15 | refinedweb | 232 | 57 |
An Introduction to the Command-Line (on Unix-like systems)Everybody Knows How to Use a Computer, but Not Everyone Knows How to Use the Command Line. Yet This is the Gateway to Doing Anything and Everything Sophisticated with a Computer and the Most Natural Starting Place to Learn Programming
by Oliver; 2014
IntroductionI took programming in high school, but I never took to it. This, I strongly believe, is because it wasn't taught right—and teaching it right means starting at the beginning, with the command line. The reason for this is three-fold: (1) it gives you a deeper sense of how a high-level computer works (which a glossy front, like Windows, conceals); (2) it's the most natural port of entry into all other programming languages; and (3) it's super-useful in its own right. If you don't know the command line and start programming, some things will forever remain hazy and mysterious, even if you can't put your finger on exactly what they are. If you already know a lot about computers, the point is moot; if you don't, then by all means start your programming education by learning the command line!
A word about terminology here: I'm in the habit of horrendously confusing and misusing all of the precisely defined words "the command line", "Unix", "Linux", "the terminal", "the shell", and "Bash." Properly speaking, unix is an operating system while linux refers to a closely-related family of unix-based operating systems, which includes commercial and non-commercial distributions [1]. (Unix was not free under its developer, AT&T, which caused the unix-linux schism.) The command line, as Wikipedia says, is:
... a means of interacting with a computer program where the user issues commands to the program in the form of successive lines of text (command lines) ... The interface is usually implemented with a command line shell, which is a program that accepts commands as text input and converts commands to appropriate operating system functions.This article was originally titled "An Introduction to Unix" and I use "unix" as a shorthand throughout. This is not technically accurate. What I mean when I proselytize for "unix" is simply that you learn how to punch commands in on the command line on a Unix-like system (which includes Linux and Macintosh but excludes Windows [2]). The terminal is your portal into this world. Here's what my mine looks like:
There is a suite of commands to become familiar with—The GNU Core Utilities (wiki entry)—and, in the course of learning them, you learn about computers. This is a foundational piece of your programming education.
In terms of bang for the buck, it's also an excellent investment. You can gain powerful abilities by learning just a little. My coworker was fresh out of his introductory CS course, when he was given a small task by our boss. He wrote a full-fledged program, reading input streams and doing heavy parsing, and then sent an email to the boss that began, "After 1.5 days of madly absorbing perl syntax, I completed the exercise..." He didn't know how to use the command-line at the time, and now a print-out of that email hangs on his wall as a joke—and as a monument to the power of the terminal.
You can find ringing endorsements for learning the command line from all corners of the internet. For instance, in the excellent course Startup Engineering (Stanford/Coursera) Balaji Srinivasan writes:
A command line interface (CLI) is a way to control your computer by typing in commands rather than clicking on buttons in a graphical user interface (GUI). Most computer users are only doing basic things like clicking on links, watching movies, and playing video games, and GUIs are fine for such purposes.To provide foreshadowing, here are some things you can do on the command line:
But to do industrial strength programming - to analyze large datasets, ship a webapp, or build a software startup - you will need an intimate familiarity with the CLI. Not only can many daily tasks be done more quickly at the command line, many others can only be done at the command line, especially in non-Windows environments. You can understand this from an information transmission perspective: while a standard keyboard has 50+ keys that can be hit very precisely in quick succession, achieving the same speed in a GUI is impossible as it would require rapidly moving a mouse cursor over a profusion of 50 buttons. It is for this reason that expert computer users prefer command-line and keyboard-driven interfaces.
- make or rename 100 folders or files en masse
- find all files of a given extension or any file that was created within the last week
- log onto a computer remotely and access its files with ssh
- copy files to your computer directly over the network (no external hard drive necessary!) with rsync
- run a Perl or Python script
- run one of the many programs that are only available on the command line
- see all processes running on your computer or the space occupied by your folders
- see or change the permissions on a file
- parse a text file in any way imaginable (count lines, swap columns, replace words, etc.)
- soundly encrypt your files or communications with gpg2
- run your own web server on the Amazon cloud with nginx
Is this the truth, the whole truth, and nothing but the truth, so help my white ass? I believe it is, but also my trajectory through the world of computing began with unix. So perhaps I instinctively want to push this on other people: do it the way I did it. And, because it occupies a bunch of my neuronal real estate at the moment, I could be considered brainwashed :-)
[1] Still confused about unix vs linux? Refer to the full family tree and these more precise definitions from Wikipedia:
unix: a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, developed in the 1970s at the Bell Labs research center by Ken Thompson, Dennis Ritchie, and others
linux: a Unix-like and mostly POSIX-compliant computer operating system assembled under the model of free and open-source software development and distribution [whose] defining component ... is the Linux kernel, an operating system kernel first released [in] 1991 by Linus Torvalds ↑
[2] See the the postscript for a further discussion ↑
100 Useful Unix CommandsThis article is an introduction to the command line. It aims to teach the basic principles and neglects to mention many of the utilities that give unix superpowers. To learn about those, see 100 Useful Command-Line Utilities.
Getting Started: Opening the TerminalIf you have a Mac, navigate to Applications > Utilities and open the application named "Terminal":
If you have a PC, abandon all hope, ye who enter here! Just kidding—partially. None of the native Windows shells, such as cmd.exe or PowerShell, are unix-like. Instead, they're marked with hideous deformities that betray their ignoble origin as grandchildren of the MS-DOS command interpreter. If you didn't have a compelling reason until now to quit using PCs, here you are [1]. Typically, my misguided PC friends don't use the command line on their local machines; instead, they have to
sshinto some remote server running Linux. (You can do this with an ssh client like PuTTY, Chrome's Terminal Emulator, or MobaXterm, but don't ask me how.) On Macintosh you can start practicing on the command line right away without having to install a Linux distribution [2] (the Mac-flavored unix is called Darwin).
For both Mac and PC users who want a bona fide Linux command line, one easy way to get it is in the cloud with Amazon EC2 via the AWS Free Tier. If you want to go whole hog, you can download and install a Linux distribution—Ubuntu, Mint, Fedora, and CentOs are popular choices—but this is asking a lot of non-hardcore-nerds (less drastically, you could boot Linux off of a USB drive or run it in a virtual machine).
[1] I should admit, you can and should get around this by downloading something like Cygwin, whose homepage states: "Get that Linux feeling - on Windows" ↑
[2] However, if you're using Mac OS rather than Linux, note that OS does not come with the GNU coreutils, which are the gold standard. You should download them ↑
The Definitive Guides to Unix, Bash, and the CoreutilsBefore going any further, it's only fair to plug the authoritative guides which, unsurprisingly, can be found right on your command line:
$ man bash $ info coreutils(The $ at the beginning of the line represents the terminal's prompt.) These are good references, but overwhelming to serve as a starting point. There are also great resources online:
- The Linux Information Project
- GNU Bash Reference Manual
- The Linux Documentation Project
- SS64 | Command line reference
- Stack Overflow
- Wikipedia
The Unix FilestructureAll the files and directories (a fancy word for "folder") on your computer are stored in a hierarchical tree. Picture a tree in your backyard upside-down, so the trunk is on the top. If you proceed downward, you get to big branches, which then give way to smaller branches, and so on. The trunk contains everything in the sense that everything is connected to it. This is the way it looks on the computer, too, and the trunk is called the root directory. In unix it's represented with a slash:
/The root contains directories, which contain other directories, and so on, just like our tree. To get to any particular file or directory, we need to specify the path, which is a slash-delimited address:
/dir1/dir2/dir3/some_fileNote that a full path always starts with the root, because the root contains everything. As we'll see below, this won't necessarily be the case if we specify the address in a relative way, with respect to our current location in the filesystem.
Let's examine the directory structure on our Macintosh. We'll go to the root directory and look down just one level with the unix command tree. (If we tried to look at the whole thing, we'd print out every file and directory on our computer!) We have:
While we're at it, let's also look at the directory /Users/username, which is the specially designated home directory on the Macintosh:
One thing we notice right away is that the Desktop, which holds such a revered spot in the GUI, is just another directory—simply the first one we see when we turn on our computer.
If you're on Linux rather than Mac OS, the directory tree might look less like the screenshot above and more like this:
(Image credit: The Geek Stuff: Linux Directory Structure)
The naming of these folders is not always intuitive, but you can read about the role of each one at thegeekstuff.com.
If the syntax of a unix path looks familiar, it is. A webpage's URL, with its telltale forward slashes, looks like a unix path with a domain prepended to it. This is not a coincidence! For a simple static website, its structure on the web is determined by its underlying directory structure on the server, so navigating to: serve you content in the folder websitepath/abc/xyz on the host's computer (i.e., the one owned by example.com). Modern dynamic websites are more sophisticated than this, but it's neat to reflect that the whole word has learned this unix syntax without knowing it.
To learn more, see the O'Reilly discussion of the unix file structure.
The Great Trailing Slash DebateSometimes you'll see directories written with a trailing slash, as in:
dir1/This helpfully reminds you that the entity is a directory rather than a file, but on the command line using the more compact dir1 is sufficient. There are a handful of unix commands [1] which behave slightly differently if you leave the trailing slash on, but this sort of pedantry isn't worth worrying about yet.
[1] See, for example, the discussion of rsync ↑
Where Are You? - Your Path and How to Navigate through the FilesystemWhen you open up the terminal to browse through your filesystem, run a program, or do anything, you're always somewhere. Where? You start out in the designated home directory when you open up the terminal. The home directory's path is preset by a global variable called HOME. Again, it's /Users/username on a Mac.
As we navigate through the filesystem, there are some conventions. The current working directory (cwd)—whatever directory we happen to be in at the moment—is specified by a dot:
.Sometimes it's convenient to write this as:
./which is not to be confused with the root directory:
/When a program is run in the cwd, you often see the syntax:
$ ./myprogramwhich emphasizes that you're executing a program from the current directory. The directory one above the cwd is specified by two dots:
..With the trailing slash syntax, that's:
../A tilde is shorthand for the home directory:
~or:
~/To see where we are, we can print working directory:
$ pwdTo move around, we can change directory:
$ cd /some/pathBy convention, if we leave off the argument and just type:
$ cdwe will go home. To make directory—i.e., create a new folder—we use:
$ mkdirAs an example, suppose we're in our home directory, /Users/username, and want to get one back to /Users. We can do this two ways:
$ cd /Usersor:
$ cd ..This illustrates the difference between an absolute path and a relative path. In the former case, we specify the complete address, while in the later we give the address with respect to our cwd. We could even accomplish this with:
$ cd /Users/username/..or maniacally seesawing back and forth:
$ cd /Users/username/../username/..if our primary goal were obfuscation. This distinction between the two ways to specify a path may seem pedantic, but it's not. Many scripting errors are caused by programs expecting an absolute path and receiving a relative one instead or vice versa. Use relative paths if you can because they're more portable: if the whole directory structure gets moved, they'll still work.
Let's mess around. We know cd with no arguments takes us home, so try the following experiment:
$ echo $HOME # print the variable HOME /Users/username $ cd # cd is equivalent to cd $HOME $ pwd # print working directory shows us where we are /Users/username
$ unset HOME # unset HOME erases its value $ echo $HOME $ cd /some/path # cd into /some/path $ cd # take us HOME? $ pwd /some/pathWhat happened? We stayed in /some/path rather than returning to /Users/username. The point? There's nothing magical about home—it's merely set by the variable HOME. More about variables soon!
Gently Wading In - The Top 10 Indispensable Unix CommandsNow that we've dipped one toe into the water, let's make a list of the 10 most important unix commands in the universe:
- pwd
- ls
- cd
- mkdir
- echo
- cat
- cp
- mv
- rm
- man
$ man pwdBut pwd isn't particularly interesting and its man page is barely worth reading. A better example is afforded by one of the most fundamental commands of all, ls, which lists the contents of the cwd or of whatever directories we give it as arguments:
$ man lsThe man pages tend to give TMI (too much information) but the most important point is that commands have flags which usually come in a one-dash-one-letter or two-dashes-one-word flavor:
command -f command --flag
$ man manHowever, as the old unix joke goes, this won't work:
$ man woman No manual entry for womanBelow we'll discuss the commands in the top 10 list in more depth.
lsLet's go HOME and try out ls with various flags:
$ cd $ ls $ ls -1 $ ls -hl $ ls -alSome screen shots:
First, vanilla ls. We see our files—no surprises. And ls -1 merely displays our files in a column. To show the human-readable, long form we stack the -h and -l flags:
ls -hlThis is equivalent to:
ls -h -lScreenshot:
This lists the owner of the file; the group to which he belongs (staff); the date the file was created; and the file size in human-readable form, which means bytes will be rounded to kilobytes, gigabytes, etc. The column on the left shows permissions. If you'll indulge mild hyperbole, this simple command is already revealing secrets that are well-hidden by the GUI and known only to unix users. In unix there are three spheres of permission—user, group, and other/world—as well as three particular types for each sphere—read, write, and execute. Everyone with an account on the computer is a unique user and, although you may not realize it, can be part of various groups, such as a particular lab within a university or team in a company. To see yourself and what groups you belong to, try:
$ whoami $ groupsA string of dashes displays permission:
--------- rwx------ rwxrwx--- rwxrwxrwx
If you look at the screenshot above, you see a tenth letter prepended to the permission string, e.g.:
drwxrwxrwx
The -a option in:
ls -allists all files in the directory, including dotfiles. These are files that begin with a dot and are hidden in the GUI. They're often system files—more about them later. Screenshot:
Note that, in contrast to ls -hl, the file sizes are in pure bytes, which makes them a little hard to read.
A general point about unix commands: they're often robust. For example, with ls you can use an arbitrary number of arguments and it obeys the convention that an asterisk matches anything (this is known as file globbing, and I think of it as the prequel to regular expressions). Take:
$.
Suppose I create some nested directories:
$ mkdir -p squirrel/mouse/fox(The -p flag is required to make nested directories in a single shot) The directory fox is empty, but if I ask you to list its contents for the sake of argument, how would you do it? Beginners often do it like this:
$ cd squirrel $ cd mouse $ cd fox $ lsBut this takes forever. Instead, list the contents from the current working directory, and—crucially—use bash autocompletion, a huge time saver. To use autocomplete, hit the tab key after you type ls. Bash will show you the directories available (if there are many possible directories, start typing the name, sq..., before you hit tab). In short, do it like this:
$ ls squirrel/mouse/fox/ # use autocomplete to form this path quickly
Single Line CommentsAnything prefaced with a # —that's pound-space—is a comment and will not be executed:
$ # This is a comment. $ # If we put the pound sign in front of a command, it won't do anything: $ # ls -hlSuppose you write a line of code on the command line and decided you don't want to execute it. You have two choices. The first is pressing Cntrl-c, which serves as an "abort mission." The second is jumping to the beginning of the line (Cntrl-a) and adding the pound character. This has an advantage over the first method that the line will be saved in bash history (discussed below) and can thus be retrieved and modified later.
In a script, pound-special-character (like #!) is sometimes interpreted (see below), so take note and include a space after # to be safe.
The Primacy of Text Files, Text EditorsAs we get deeper into unix, we'll frequently be using text editors to edit code, and viewing either data or code in text files. When I got my hands on a computer as a child, I remember text editors seemed like the most boring programs in the world (compared to, say, 1992 Prince of Persia). And text files were on the bottom of my food chain. But the years have changed me and now I like nothing better than a clean, unformatted .txt file. It's all you need! If you store your data, your code, your correspondence, your book, or almost anything in .txt files with a systematic structure, they can be parsed on the command line to reveal information from many facets. Here's some advice: do all of your text-related work in a good text editor. Open up clunky Microsoft Word, and you've unwittingly spoken a demonic incantation and summoned the beast. Are these the words of a lone lunatic dispensing hateration? No, because on the command line you can count the words in a text file, search it with grep, input it into a Python program, et cetera. However, a file in Microsoft Word's proprietary and unknown formatting is utterly unusable.
Because text editors are extremely important, some people develop deep relationships with them. My co-worker, who is a Vim aficionado, turned to me not long ago and said, "You know how you should think about editing in Vim? As if you're talking to it." On the terminal, a ubiquitous and simple editor is nano. If you're more advanced, try Vim or Emacs. Not immune to my co-worker's proselytizing, I've converted to Vim. Although it's sprawling and the learning curve can be harsh—Vim is like a programming language in itself—you can do a zillion things with it. There's a section on Vim near the end of this article.
On the GUI, there are many choices: Sublime, Visual Studio Code, Atom, Brackets, TextMate (Mac only), Aquamacs (Mac only), etc.
Exercise: Let's try making a text file with nano. Type:
$ nano file.txtand make the following three-row two-column file:
1 x 4 b z 9
echo and catMore essential commands: echo prints the string passed to it as an argument, while cat prints the contents of files passed to it as arguments. For example:
$ echo joe $ echo "joe"would both print joe, while:
$ cat file.txtwould print the contents of file.txt. Entering:
$ cat file.txt file2.txtwould print out the contents of both file.txt and file2.txt concatenated together, which is where this command gets its slightly confusing name.
Finally, a couple of nice flags for these commands:
$ echo -n "joe" # suppress newline $ echo -e "joe\tjoe\njoe" # interpret special chars ( \t is tab, \n newline ) $ cat -n file.txt # print file with line numbers
cp, mv, and rmFinishing off our top 10 list we have cp, mv, and rm. The command to make a copy of a file is cp:
$ cp file1 file2 $ cp -R dir1 dir2The first line would make an identical copy of file1 named file2, while the second would do the same thing for directories. Notice that for directories we use the -R flag (for recursive). The directory and everything inside it are copied.
Question: what would the following do?
$ cp -R dir1 ../../Answer: it would make a copy of dir1 up two levels from our current working directory.
To.
Finally, rm removes a file or directory:
$ rm file # removes a file $ rm -r dir # removes a file or directory $ rm -rf dir # force removal of a file or directory # (i.e., ignore warnings)
VariablesTo declare something as a variable use an equals sign, with no spaces. Let's declare a to be a variable:
$ a=3 # This syntax is right (no whitespace) $ a = 3 # This syntax is wrong (whitespace) -bash: a: command not foundOnce we've declared something as a variable, we need to use $ to access its value (and to let bash know it's a variable). For example:
$ a=3 $ echo a a $ echo $a 3So, with no $ sign, bash thinks we just want to echo the string a. With a $ sign, however, it knows we want to access what the variable a is storing, which is the value 3. Variables in unix are loosely-typed, meaning you don't have to declare something as a string or an integer.
$ a=3 # a can be an integer $ echo $a 3
$ a=joe # or a can be a string $ echo $a joe
$ a="joe joe" # Use quotes if you want a string with spaces $ echo $a joe joeWe can declare and echo two variables at the same time, and generally play fast and loose, as we're used to doing on the command line:
$ a=3; b=4 $ echo $a $b 3 4 $ echo $a$b # mesh variables together as you like 34 $ echo "$a$b" # use quotes if you like 34 $ echo -e "$a\t$b" # the -e flag tells echo to interpret \t as a tab 3 4As
$ joe="hello $var" $ echo $joe hello 5
$ joe='hello $var' $ echo $joe hello $varAn important note is that often we use variables to store paths in unix. Once we do this, we can use all of our familiar directory commands on the variable:
$ d=dir1/dir2/dir3 $ ls $d $ cd $d
$ d=.. # this variable stores the directory one above us (relative path) $ cd $d/.. # cd two directories up
Escape SequencesEscape sequences are important in every language. When bash reads $a it interprets it as whatever's stored in the variable a. What if we actually want to echo the string $a? To do this, we use \ as an escape character:
$ a=3 $ echo $a 3 $ echo \$a $a $ echo "\$a" # use quotes if you like $aWhat if we want to echo the slash, too? Then we have to escape the escape character (using the escape character!):
$ echo \\\$a # escape the slash and the dollar sign \$aThis really comes down to parsing. The slash helps bash figure out if your text is a plain old string or a variable. It goes without saying that you should avoid special characters in your variable names. In unix we might occasionally fall into a parsing tar-pit trap. To avoid this, and make extra sure bash parses our variable right, we can use the syntax ${a} as in:
$ echo ${a} 3When could this possibly be an issue? Later, when we discuss scripting, we'll learn that $n, where n is a number, is the nth argument to our script. If you were crazy enough to write a script with 11 arguments, you'd discover that bash interprets a=$11 as a=$1 (the first argument) concatenated with the string 1 while a=${11} properly represents the eleventh argument. This is getting in the weeds, but FYI.
Here's a more practical example:
$ a=3 $ echo $a # variable a equals 3 3 $ echo $apple # variable apple is not set $ echo ${a}pple # this describes the variable a plus the string "pple" 3pple
Global VariablesIn general, it is the convention to use capital letters for global variables. We've already learned about one: HOME. We can see all the variables set in our shell by simply typing:
$ setSome basic variables deserve comment:
- PS1
- TMPDIR
- EDITOR
- DISPLAY
$ PS1=':-) 'changes our prompt from a dollar-sign into an emoticon, as in:
This is amusing, but the PS1 variable is actually important for orienting you on the command line. A good prompt is a descriptive one: it tells you what directory you're in and perhaps your username and the name of the computer. The default prompt should do this but, in case you want to nerd out, you can read about the arcane language required to customize PS1 here. (If you're familiar with git, you can even have your prompt display the branch of the git repository you're on.[1])
On your computer there is a designated temporary directory and its path is stored in TMPDIR. Some commands, such as sort, which we'll learn later, surreptitiously make use of this directory to store intermediate files. At work, we have a shared computer system and occasionally this common directory $TMPDIR will run out of space, causing programs trying to write there to fail. One solution is to simply set TMPDIR to a different path where there's free space. EDITOR sets the default text editor (you can invoke it by pressing Cntrl-x-e). And DISPLAY is a variable related to the X Window System.
Many programs rely on their own agreed-upon global variables. For example, if you're a Perl user, you may know that Perl looks for modules in the directory whose path is stored in PERL5LIB. Python looks for its modules in PYTHONPATH; R looks for packages in R_LIBS; Matlab uses MATLABPATH; awk uses AWKPATH; C++ looks for libraries in LD_LIBRARY_PATH; and so on. These variables don't exist in the shell by default. A program will make a system call and look for the variable. If the user has had the need or foresight to define it, the program can make use of it.
[1] Here's the trick, although it's beyond the scope of this introduction. Add these lines to your bash configuation file:
# via: parse_git_branch() { git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/()/' } # add git branch to prompt export PS1="\[\033]0;\h:\W\007\]\h:\W\$(parse_git_branch)] "↑
The PATHThe most important global variable of all is the PATH. This is the PATH, as distinct from a path, a term we've already learned referring to a location in the filesystem. The PATH is a colon-delimited list of directories where unix will look for executable programs when you enter something on command line. If your program is in one of these directories, you can run it from any location by simply entering its name. If the program is not in one of these directories, you can still run it, of course, but you'll have to include its path.
Let's revisit the idea of a command in unix. What's a command? It's nothing more than a program sitting in a directory somewhere. So, if ls is a program [1], where is it? Use the command which to see its path:
$ which ls # on my work computer /bin/ls
$ which ls # on my home Mac /usr/local/Cellar/coreutils/8.20/libexec/gnubin/lsFor the sake of argument, let's say I download an updated version of the ls command, and then type ls in my terminal. What will happen—will the old ls or the new ls execute? The PATH comes into play here because it also determines priority. When you enter a command, unix will look for it in each directory of the PATH, from first to last, and execute the first instance it finds. For example, if:
PATH=/bin/dir1:/bin/dir2:/bin/dir3and there's a command named ls in both /bin/dir1 and /bin/dir2, the one in /bin/dir1 will be executed.
Let's see what your PATH looks like. Enter:
$ echo $PATHFor example, here's a screenshot of the default PATH on Ubuntu:
To emphasize the point again, all the programs in the directories specified by your PATH are all the programs that you can access on the command line by simply typing their names.
The PATH is not immutable. You can set it to be anything you want, but in practice you'll want to augment, rather than overwrite, it. By default, it contains directories where unix expects executables, like:
- /bin
- /usr/bin
- /usr/local/bin
$ /mydir/newcommandHowever, if you're going to be using it frequently, you can just add /mydir to the PATH and then invoke the command by name:
$ PATH=/mydir:$PATH # add /mydir to the front of PATH - highest priority $ PATH=$PATH:/mydir # add /mydir to the back of PATH - lowest priority $ newcommand # now invoking newcommand is this easyThis is a frequent chore in unix. If you download some new program, you will often find yourself updating the PATH to include the directory containing its binaries. How can we avoid having to do this every time we open the terminal for a new session? We'll discuss this below when we learn about .bashrc.
If you want to shoot yourself in the foot, you can vaporize the PATH:
$ unset PATH # not advisable $ ls # now ls is not found -bash: ls: No such file or directorybut this is not advisable, save as a one-time educational experience.
[1] In fact, if you want to view the source code (written in the C programming language) of ls and other members of the coreutils, you can download it at. E.g., get and untar the latest version as of this writing:
$ wget $ tar -xvf coreutils-8.9.tar.xzor use git:
$ git clone git://git.sv.gnu.org/coreutils↑
LinksWhile we're on the general subject of paths, let's talk about symbolic links. If you've ever used the Make Alias command on a Macintosh (not to be confused with the unix command alias, discussed below),!
What is Scripting?By this point, you should be comfortable using basic utilities like echo, cat, mkdir, cd, and ls. Let's enter a series of commands, creating a directory with an empty file inside it, for no particular reason:
$ mkdir tmp $ cd tmp $ pwd /Users/oliver/tmp $ touch myfile.txt # the command touch creates an empty file $ ls myfile.txt $ ls myfile_2.txt # purposely execute a command we know will fail ls: cannot access myfile_2.txt: No such file or directoryWhat if we want to repeat the exact same sequence of commands 5 minutes later? Massive bombshell—we can save all of these commands in a file! And then run them whenever we like! Try this:
$ nano myscript.shand write the following:
# a first script mkdir tmp cd tmp pwd touch myfile.txt ls ls myfile_2.txtGratuitous screenshot:
This file is called a script (.sh is a typical suffix for a shell script), and writing it constitutes our first step into the land of bona fide computer programming. In general usage, a script refers to a small program used to perform a niche task. What we've written is a recipe that says:
- create a directory called "tmp"
- go into that directory
- print our current path in the file system
- make a new file called "myfile.txt"
- list the contents of the directory we're in
- specifically list the file "myfile_2.txt" (which doesn't exist)
Let's run our program! Try:
$ ./myscript.sh -bash: ./myscript.sh: Permission deniedWTF! It's dysfunctional. What's going on here is that the file permissions are not set properly. In unix, when you create a file, the default permission is not executable. You can think of this as a brake that's been engaged and must be released before we can go (and do something potentially dangerous). First, let's look at the file permissions:
$ ls -hl myscript.sh -rw-r--r-- 1 oliver staff 75 Oct 12 11:43 myscript.shLet's change the permissions with the command chmod and execute the script:
$ chmod u+x myscript.sh # add executable(x) permission for the user(u) only $ ls -hl myscript.sh -rwxr--r-- 1 oliver staff 75 Oct 12 11:43 myscript.sh
$ ./myscript.sh /Users/oliver/tmp/tmp myfile.txt ls: cannot access myfile_2.txt: No such file or directoryNot bad. Did it work? Yes, it did because it's printed stuff out and we see it's created tmp/myfile.txt:
$ ls myfile.txt myscript.sh tmp $ ls tmp myfile.txtAn important note is that even though there was a cd in our script, if we type:
$ pwd /Users/oliver/tmpwe see that we're still in the same directory as we were in when we ran the script. Even though the script entered /Users/oliver/tmp/tmp, and did its bidding, we stay in /Users/oliver/tmp. Scripts always work this way—where they go is independent of where we go.
If you're wondering why anyone would write such a pointless script, you're right—it would be odd if we had occasion to repeat this combination of commands. There are some more realistic examples of scripting below.
File SuffixesAs we begin to script it's worth following some file naming conventions. We should use common sense suffixes, like:
- .txt - for text files
- .html - for html files
- .sh - for shell scripts
- .pl - for Perl scripts
- .py - for Python scripts
- .cpp - for c++ code
$ ls *.txtList all text files in the cwd and below (i.e., including child directories):
$ find . -name "*.txt"
[1] An astute reader noted that, for commands—as opposed to, say, html or text files—using suffixes is not the best practice because it violates the principle of encapsulation. The argument is that a user is neither supposed to know nor care about a program's internal implementation details, which the suffix advertises. You can imagine a program that starts out as a shell script called mycommand.sh, is upgraded to Python as mycommand.py, and then is rewritten in C for speed, becoming the binary mycommand. What if other programs depend on mycommand? Then each time mycommand's suffix changes they have to be rewritten—an annoyance. Although I make this sloppy mistake in this article, that doesn't excuse you! Read the full argument
Update: There's a subtlety inherent in this argument that I didn't appreciate the first time around. I'm going to jump ahead of the narrative here, so you may want to skip this for now and revist it later. Suppose you have two identical Python scripts. One is called hello.py and one is simply called hi. Both contain the following code:
#!/usr/bin/env python def yo(): print('hello')In the Python shell, this works:
>>> import hellobut this doesn't:
>>> import hi Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named hiBeing able to import scripts in Python is important for all kinds of things, such as making modules, but you can only import something with a .py extension. So how do you get around this if you're not supposed to use file extensions? The sage answers this question as follows:
The best way to handle this revolves around the core question of whether the file should be a command or a library. Libraries have to have the extension, and commands should not, so making a tiny command wrapper that handles parsing options and then calls the API from the other, imported one is correct.To elaborate, this considers a command to be something in your PATH, while a library—which could be a runnable script—is not. So, in this example, hello.py would stay the same, as a library not in your PATH:
#!/usr/bin/env python def yo(): print('hello')hi, a command in your PATH, would look like this:
#!/usr/bin/env python import hello hello.yo()Hat tip: Alex
↑
The ShebangWe've left out one important detail about scripting. How does unix know we want to run a bash script, as opposed to, say, a Perl or Python script? There are two ways to do it. We'll illustrate with two simple scripts, a bash script and a Perl script:
$ cat myscript_1.sh # a bash script echo "hello kitty"
$ cat myscript_1.pl # a Perl script print "hello kitty\n";The first way to tell unix which program to use to interpret the script is simply to say so on the command line. For example, we can use bash to execute bash scripts:
$ bash ./myscript_1.sh # use bash for bash scripts hello kittyand perl for Perl scripts:
$ perl ./myscript_1.pl # use Perl for Perl scripts hello kittyBut this won't work for a Perl script:
$ ./myscript_1.pl # this won't work ./myscript_1.pl: line 1: print: command not foundAnd if we purposefully specify the wrong language, we'll get errors:
$ bash ./myscript_1.pl # let's purposefully do it backwards ./myscript_1.pl: line 1: print: command not found
$ perl ./myscript_1.sh String found where operator expected at ./myscript_1.sh line 1, near "echo "hello kitty"" (Do you need to predeclare echo?) syntax error at ./myscript_1.sh line 1, near "echo "hello kitty"" Execution of ./myscript_1.sh aborted due to compilation errors.The second way to specify the proper interpreter—and the better way, which you should emulate—is to put it in the script itself using a shebang. To do this, let's remind ourselves where bash and perl reside on our system. On my computer, they're here:
$ which perl /usr/bin/perl
$ which bash /bin/bashalthough perl could be somewhere else on your machine (bash should be in /bin by convention). The shebang specifies the language in which your script is interpreted according to the syntax #! followed by the path to the language. It should be the first line of your script. Note that it's not a comment even though it looks like one. Let's add shebangs to our two scripts:
$ cat myscript_1.sh #!/bin/bash echo "hello kitty"
$ cat myscript_1.pl #!/usr/bin/perl print "hello kitty\n";Now we can run them without specifying the interpreter in front:
$ ./myscript_1.sh hello kitty $ ./myscript_1.pl hello kittyHowever, there's still a lingering issue and it has to do with portability, an important software principle. What if perl is in a different place on your machine than mine and you copy my scripts and try to run them? The path will be wrong and they won't work. The solution to this issue is courtesy of a neat trick using env. We can amend our script to be:
$ cat myscript_1.pl #!/usr/bin/env perl print "hello kitty\n";Of course, this assumes you have a copy of env in /usr/bin, but this is usually a correct assumption. What env does here is to use whatever your environmental variable for perl is—i.e., the perl that's first in your PATH.
This is a useful practice even if you're not sharing scripts. Suppose you've updated your version of perl and there's a newer copy than /usr/bin/perl. You've appropriately updated your PATH such that the directory containing the updated perl comes before /usr/bin. If you have env in your shebang, you're all set. However, if you've hardwired the old path in your shebang, your script will run on the old perl [1].
The question that the shebang resolves—which program will run your script?—reminds us of a more fundamental distinction between interpreted languages and compiled languages. The former are those like bash, Perl, and Python, where you can cat a script and look inside it. The later, like C++, require compilation, the process whereby code is translated into machine language (the result is sometimes called a binary). This can be done with a command line utility like g++:
$ g++ MyProgram.cpp -o MyProgramCompiled programs, such as the unix utilities themselves, tend to run faster. Don't try to cat a binary, such as ls, or it will spew out gibberish:
$ cat $( which ls ) # don't do this!
[1] Of course, depending on circumstances, you may very well want to stick with the old version of Perl or whatever's running your program. An update can have unforeseen consequences and this is the motivation for tools like virtualenv (Python), whose docs remind us: "If an application works, any change in its libraries or the versions of those libraries can break the application" ↑
bashWe've thrown around the term bash a few times but we haven't defined it. To do so, let's examine the special command, sh, which is more primitive than bash and came before it. To quote Wikipedia and the manual page:
The Bourne shell (sh) is a shell, or command-line interpreter, for computer operating systems. The shell is a command that reads lines from either a file or the terminal, interprets them, and generally executes other commands. It is the program that is running when a user logs into the system ... Commands can be typed directly to the running shell or can be put into a file and the file can be executed directly by the shellAs it describes, sh is special because it's both a command interpreter and a command itself (usually found at /bin/sh). Put differently, you can run myscript as:
$ sh ./myscriptor you can simply type:
$ shto start an interactive sh shell. If you're in this shell and run:
$ ./myscriptwithout specifying an interpreter or using a shebang, your script will be interpreted by sh by default. On most computers, however, the default shell is no longer sh but bash (usually located at /bin/bash). To mash up Wikipedia and the manual page:
The Bourne-Again SHell (bash) a Unix shell written by Brian Fox for the GNU Project as a free software replacement for the Bourne shell. bash is an sh-compatible command language interpreter that executes commands read from the standard input or from a file ... There are some subtle differences between bash and traditional versions of shLike sh, bash is a command you can either invoke on a script or use to start an interactive bash shell. Read more on Stackoverflow: Difference between sh and bash.
Which shell are you using right now? Almost certainly bash, but if you want to double check, there's a neat command given here to display your shell type:
$ ps -p $$There are more exotic shells, like Z shell and tcsh, but they're beyond the scope of this article.
chmodLet's take a closer look at how to use chmod. Remember the three domains:
- u - user
- g - group
- o - other/world
- r - read
- w - write
- x - execute two I have memorized are 777 and 755:
$.
sshIn addition to chmod, there's another command it would be remiss not to mention. For many people, the first time they need to go to the command line, rather than the GUI, is to use the Secure Shell (ssh) protocol. Suppose you want to use a computer, but it's not the computer that's in front of you. It's a different computer in some other location—say, at your university, your company, [1]. The basic syntax is:
ssh username@hostFor example:
$ ssh username@myhost.university.eduIf you're trying to ssh into a private computer and don't know the hostname, use its IP address (username@IP-address).
ssh also allows you to run a command on the remote server without logging in. For instance, to list of the contents of your remote computer's home directory, you could run:
$ ssh username@myhost.university.edu "ls -hl"Cool, eh? Moreover, if you have ssh access to a machine, you can copy files to or from it with the utility rsync—a great way to move data without an external hard drive.
The file:
~/.ssh/configdetermines ssh's behavior and you can create it if it doesn't exist (the dot in the name .ssh confers invisibility—see the discussion about dotfiles below). On your own private computer, you can ssh into selected servers without having to type in a password by updating this configuration file. To do this,Instead of doing this, add these lines to your ~/.ssh/config file:
Host Myserver HostName myserver.com User myusername IdentityFile ~/.ssh/localkeyNext, cat your public key and paste it into:
~/.ssh/authorized_keyson the remote machine (i.e., the myserver.com computer). Now on your local computer, you can ssh into myserver.com without a password:
$ ssh MyserverYou can also use this technique to push to github.com [2], without having to punch your password in each time, by pasting your public key into:
Settings > SSH Keys > Add SSH Keyon GitHub (read the official tutorial).
If this is your first encounter with ssh, you'd be surprised how much of the work of the world is done by ssh. It's worth reading the extensive man page, which gets into matters of computer security and cryptography.
[1] The host also has to enable ssh access. On Macintosh, for example, it's disabled by default, but you can turn it on, as instructed here. For Ubuntu, check out the official docs. ↑
[2] As you get deeper into the game, tracking your scripts and keeping a single, stable version of them becomes crucial. Git, a vast subject for another tutorial, is the neat solution to this problem and the industry standard for version control. On the web GitHub provides free hosting of script repositories and connects to the command line via the git interface ↑
Saving to a File; Stdout and StderrTo save to a file in unix, use an angle bracket:
$ echo joe > junk.txt # save to file $ cat junk.txt joeTo append to the end of a pre-existing file, use a double angle bracket:
$ echo joe >> junk.txt # append to already-existing file $ cat junk.txt joe joeReturning to our first script, myscript.sh, let's save the output to a file:
$ ./myscript.sh > out.txt mkdir: cannot create directory ‘tmp’: File exists ls: cannot access myfile_2.txt: No such file or directory
$ cat out.txt /Users/oliver/tmp/tmp myfile.txtThis is interesting: out.txt has its output. However, not everything went into out.txt, because some error messages were echoed to the console. What's going on here is that there are actually two output streams: stdout (standard out) and stderr (standard error). Look at the following figure from Wikipedia:
(Image credit: Wikipedia: Standard streams)
Proper output goes into stdout while errors go into stderr. The syntax for saving stderr in unix is 2> as in:
$ # save the output into out.txt and the error into err.txt $ ./myscript.sh > out.txt 2> err.txt $ cat out.txt /Users/oliver/tmp/tmp myfile.txt $ cat err.txt mkdir: cannot create directory ‘tmp’: File exists ls: cannot access myfile_2.txt: No such file or directoryWhen you think about it, the fact that output and error are separated is supremely useful. At work, sometimes we parallelize heavily and run 1000 instances of a script. For each instance, the error and output are saved separately. The 758th job, for example, might look like this:
./myjob --instance 758 > out758.o 2> out758.e(I'm in the habit of using the suffixes .o for output and .e for error.) With this technique we can quickly scan through all 1000 .e files and check if their size is 0. If it is, we know there was no error; if not, we can re-run the failed jobs. Some programs are in the habit of echoing run statistics or other information to stderr. This is an unfortunate practice because it muddies the water and, as in the example above, would make it hard to tell if there was an actual error.
Output vs error is a distinction that many programming languages make. For example, in C++ writing to stdout and stderr is like this:
cout << "some output" << endl; cerr << "some error" << endl;In Perl it's:
print STDOUT "some output\n"; print STDERR "some error\n";In Python it's:
import sys sys.stdout.write("some output\n") sys.stderr.write("some error\n")and so on.
More on Stdout and Stderr; RedirectionFor the sake of completeness, we should note that you can redirect standard error to standard output and vice versa. Let's make sure we get the syntax of all things pertaining to stdout and stderr right:
1> # save stdout to (plain old > also works) 2> # save stderr toas in:
$ ./myscript.sh 1> out.o 2> out.e $ ./myscript.sh > out.o 2> out.e # these two lines are identicalWhat if we want to choose where things will be printed from within our script? Then we can use the following syntax:
&1 # standard out stream &2 # standard error streamLet's examine five possible versions of our Hello Kitty script:
#!/bin/bash # version 1 echo "hello kitty"
#!/bin/bash # version 2 echo "hello kitty" > somefile.txt
#!/bin/bash # version 3 echo "hello kitty" > &1
#!/bin/bash # version 4 echo "hello kitty" > &2
#!/bin/bash # version 5 echo "hello kitty" > 1Here's how they work:
- version 1 - echo "hello kitty" to stdout
- version 2 - echo "hello kitty" to the file somefile.txt
- version 3 - same as version 1
- version 4 - echo "hello kitty" to sterr
- version 5 - echo "hello kitty" to the file named 1
$ # output saved to file but error printed to console $ ./hellokitty.sh > junk.txt hello kittyhello kitty is indeed stderr because it's echoed to the console, not saved into junk.txt.
This syntax makes it easy to see how we could, e.g., redirect the standard error to standard output:
$ ./somescript.sh 2> &1 # redirect stderr to stdoutI rarely have occasion to do this and, although it's not something you need in your introductory unix toolkit, it's good to know.
Conditional LogicConditional Logic is a universal feature of programming languages. The basic idea is, if this condition, then do something. It can be made more complex: if this condition, then do something; else if that condition, then do another thing; else (if any other condition), then do yet another thing. Let's see how to implement this in bash:
$ a=joe $ if [ $a == "joe" ]; then echo hello; fi helloor:
$ a=joe $ if [ $a == "joe" ]; then echo hello; echo hello; echo hello; fi hello hello helloThe structure is:
if [ condition ]; then ... ; fiEverything between the words then and fi (if backwards in case you didn't notice) will execute if the condition is satisfied. In other languages, this block is often defined by curly brackets: { }. For example, in a Perl script, the same code would be:
#!/usr/bin/env perl my $a="joe"; if ( $a eq "joe" ) { print "hello\n"; print "hello\n"; print "hello\n"; }In bash, if is if, else is else, and else if is elif. In a script it would look like this:
#!/bin/bash a=joe if [ $a == "joe" ]; then echo hello; elif [ $a == "doe" ]; then echo goodbye; else echo "ni hao"; fiYou can also use a case statement to implement conditional logic. See an example of that here.
Although I said in the intro that unix is the best place to start your computer science education, I have to admit that the syntax for if-then logic is somewhat unwieldy—even unfriendly. Bash is a bad teaching language for conditional logic, arrays, hashes, etc. But that's only because its element is not heavy-duty programming with lots of functions, numerical operations, sophisticated data structures, and logic. Its mastery is over the quick and dirty, manipulating files and directories, and doing system stuff. I still maintain it's the proper starting point because of its wonderful tools, and because knowing its fundamentals is a great asset. Every language has its place in the programming ecosystem. Back in College, I stumbled on a physics book called The Tiger and the Shark: Empirical Roots of Wave-Particle Dualism by Bruce Wheaton. The book had a great epigraph:
It is like a struggle between a tiger and a shark,In our context, this would read: bash is supreme on the command line, but not inside of a script.
each is supreme in his own element,
but helpless in that of the other.
J.J. Thomson, 1925
File Test Operators; Return or Exit StatusFile Test Operators and exit status are two completely different topics, but since they both go well with if statements, I'll discuss them here. File Test Operators are things you can stick in an if statement to give you information about a file. Two common problems are (1) checking if your file exists and (2) checking if it's non-zero size: Let's create two files, one empty and one not:
$ touch emptyfile # create an empty file $ echo joe > nonemptyfile # create a non-empty fileThe operator -e tests for existence and -s tests for non-zero-ness:
$ file=emptyfile $ if [ -e $file ]; then echo "exists"; if [ -s $file ]; then echo "non-0"; fi; fi exists
$ file=nonemptyfile $ if [ -e $file ]; then echo "exists"; if [ -s $file ]; then echo "non-0"; fi; fi exists non-0Read The Linux Documentation Project's discussion of file test operators here.
Changing the subject altogether, you may be familiar with the idea of a return value in computer science. Functions can return a value upon completion. In unix, commands also have a return value or exit code, queryable with:
$?This is usually employed to tell the user whether or not the command successfully executed. By convention, successful execution returns 0. For example:
$ echo joe joe $ echo $? # query exit code of previous command 0Let's see how the exit code can be useful. We'll make a script, test_exitcode.sh, such that:
$ cat test_exitcode.sh #!/bin/bash sleep 10This script just pauses for 10 seconds. First, we'll let it run and then we'll interrupt it using Cntrl-c:
$ ./test_exitcode.sh; # let it run $ echo $? 0
$ ./test_exitcode.sh; # interrupt it ^C $ echo $? 130The non-zero exit code tells us that it's failed. Now we'll try the same thing with an if statement:
$ ./test_exitcode.sh $ if [ $? == 0 ]; then echo "program succeeded"; else echo "program failed"; fi program succeeded
$ ./test_exitcode.sh; ^C $ if [ $? == 0 ]; then echo "program succeeded"; else echo "program failed"; fi program failedIn research, you might run hundreds of command-line programs in parallel. For each instance, there are two key questions: (1) Did it finish? (2) Did it run without error? Checking the exit status is the way to address the second point. You should always check the program you're running to find information about its exit code, since some use different conventions. Read The Linux Documentation Project's discussion of exit status here.
Question: What's going on here?
$ if echo joe; then echo joe; fi joe joeThis is yet another example of bash allowing you to stretch syntax like silly putty. In this code snippet,
echo joeis run, and its successful execution passes a true return code to the if statement. So, the two joes we see echoed to the console are from the statement to be evaluated and the statement inside the conditional. We can also invert this formula, doing something if our command fails:
$ outputdir=nonexistentdir # set output dir equal to a nonexistent dir $ if ! cd $outputdir; then echo "couldnt cd into output dir"; fi -bash: pushd: nonexistentdir: No such file or directory couldnt cd into output dir
$ mkdir existentdir # make a test directory $ outputdir=existentdir $ if ! cd $outputdir; then echo "couldnt cd into output dir"; fi $ # no error - now we're in the directory existentdirDid you follow that? (! means logical NOT in unix.) The idea is, we try to cd but, if it's unsuccessful, we echo an error message. This is a particularly useful line to include in a script. If the user gives an output directory as an argument and the directory doesn't exist, we exit. If it does exist, we cd into it and it's business as usual:
if ! cd $outputdir; then echo "[error] couldn't cd into output dir"; exit; fiWithout this line, the script will run in whatever directory it's in if cd fails. Once in lab, I was running a script that didn't have this kind of protection. The output directory wasn't found and the script starting making and deleting files in the wrong directory. It was powerfully uncool!
We can implement similar constructions using the && and || operators rather than an if statement. Let's see how this works by making some test files:
$ touch file{1..4} $ ls file1 file2 file3 file4The && operator will chug through a chain of commands and keep on going until one of the commands fails, as in:
$ ( ls file1 ) && ( ls file2 ) && ( ls file3 ) && ( ls file4 ) file1 file2 file3 file4
$ ( ls file1 ) && ( ls file2 ) && ( ls fileX ) && ( ls file4 ) file1 file2 ls: cannot access fileX: No such file or directoryIn contrast, the || operator will proceed through the command chain and stop after the first successful one, as in:
$ ( ls file1 ) || ( ls file2 ) || ( ls file3 ) || ( ls file4 ) file1
$ ( ls fileX ) || ( ls fileY ) || ( ls fileZ ) || ( ls file4 ) ls: cannot access fileX: No such file or directory ls: cannot access fileY: No such file or directory ls: cannot access fileZ: No such file or directory file4
Basic LoopsIn programming, loops are a way of performing operations iteratively. Loops come in different flavors, but the for loop and while loop are the most basic. In bash, we can implement a for loop like this:
$ for i in 1 2 3; do echo $i; done 1 2 3The structure is:
for variable in list; do ... ; donePut anything you like in the list:
$ for i in 1 2 hello; do echo $i; done 1 2 helloMany other languages wouldn't let you get away with combining data types in the iterations of a loop, but this is a recurrent bash theme: it's fast; it's loose; it's malleable.
To count from 1 to 10, try:
$ for i in {1..10}; do echo -n "$i "; done; echo 1 2 3 4 5 6 7 8 9 10But if we can just write:
$ echo {1..10}why do we need a loop here? Loops really come into their own in bash when—no surprise!—we're dealing with files, paths, and commands. For example, to loop through all of the text files in the cwd, use:
$ for i in *.txt; do echo $i; doneAlthough this is nearly the same as:
$ ls *.txtthe former construction has the advantage that we can stuff as much code as we like in the block between do and done. Let's make a random directory structure like so:
$ mkdir -p myfolder{1..3}/{X,Y}We can populate it with token files (fodder for our example) via a loop:
$ j=0; for i in myfolder*/*; do echo "*** "$i" ***"; touch ${i}/a_${j}.txt ${i}/b_${j}.txt; ((j++)); doneIn bash, ((j++)) is a way of incrementing j. We echo $i to get some visual feedback as the loop iterates. Now our directory structure looks like this:
To practice loops, suppose we want to find any file that begins with b in any subfolder and make a symbolic link to it from the cwd:
$ for i in myfolder*/*/b*; do echo "*** "$i" ***"; ln -s $i; doneAs we learned above, a link is not a copy of a file but, rather, a kind of pointer that allows us to access a file from a path other than the one where it actually resides. Our loop yields the links:
b_0.txt -> myfolder1/X/b_0.txt b_1.txt -> myfolder1/Y/b_1.txt b_2.txt -> myfolder2/X/b_2.txt b_3.txt -> myfolder2/Y/b_3.txt b_4.txt -> myfolder3/X/b_4.txt b_5.txt -> myfolder3/Y/b_5.txtallowing us to access the b files from the cwd.
I can't overstate all the heroic things you can do with loops in bash. Suppose we want to change the extension of any text file that begins with a and resides in an X subfolder from .txt to .html:
$ for i in myfolder*/X/a*.txt; do echo "*** "$i" ***"; j=$( echo $i | sed 's|\.txt|\.html|' ); echo $j; mv $i $j; echo; doneBut I've jumped the gun! This example features three things we haven't learned yet: command substitution, piping, and sed. You should revisit it after reading those sections, but the idea is that the variable j stores a path that looks like our file's but has the extension replaced. And you see that a knowledge of loops is like a stick of dynamite you can use to blow through large numbers of files.
Here's another contrived example with these yet-to-be-discussed techniques:
$ for i in $( echo $PATH | tr ":" " " ); do echo "*** "$i" ***"; ls $i | head; echo; done | lessCan you guess what this does? It shows the first ten commands in each folder in our PATH—not something you'd likely need to do, but a demonstration of the fluidity of these constructions.
If we want to run a command or script in parallel, we can do that with loops, too. gzip is a utility to compress files, thereby saving hard drive space. To compress all text files in the cwd, in parallel, do:
$ for i in *.txt; do { echo $i; gzip $i & }; doneBut I've gotten ahead of myself again. We'll leave the discussion of this example to the section on processes.
The structure of a while loop is:
while condition; do ... ; doneI use while loops much less than for loops, but here's an example:
$ x=1; while ((x <= 3)); do echo $x; ((x++)); done 1 2 3The while loop can also take input from a file. Suppose there's a file junk.txt such that:
$ cat junk.txt 1 2 3You can iterate over this file as such:
$ while read x; do echo $x; done < junk.txt 1 2 3
Arguments to a ScriptNow that we've covered basic control flow, let's return to the subject of scripting. An important question is, how can we pass arguments to our script? Let's make a script called hellokitty.sh:
#!/bin/bash echo helloTry running it:
$ chmod 755 hellokitty.sh $ ./hellokitty.sh helloWe can change it to the following:
#!/bin/bash echo hello $1Now:
$ ./hellokitty.sh kitty hello kittyIn bash $1 represents the first argument to the script, $2 the second, and so on. If our script is:
#!/bin/bash echo $0 echo hello $1 $4Then:
$ ./hellokitty.sh my sweet kitty cat ./hellokitty.sh hello my catIn most programming languages, arguments passed in on the command line are stored as an array. Bash stores the nth element of this array in the variable $n. $0 is special and refers to the name of the script itself.
For casual scripts this suits us well. However, as you go on to write more involved programs with many options, it becomes impractical to rely on the position of an argument to determine its function in your script. The proper way to do this is using flags that can be deployed in arbitrary order, as in:
command --flag1 1 --flag2 1 --flag3 5or, in short form:
command -f1 1 -f2 1 -f3 5You can do this with the command getopts, but it's sometimes easier just to write your own options parser. Here's a sample script called test_args. Although a case statement would be a good way to handle numerous conditions, I'll use an if statement:
This has some things we haven't seen yet:
#!/bin/bash helpmessage="This script showcases how to read arguments" ### get arguments # while input array size greater than zero while (($# > 0)); do if [ "$1" == "-h" -o "$1" == "-help" -o "$1" == "--help" ]; then shift; echo "$helpmessage" exit; elif [ "$1" == "-f1" -o "$1" == "--flag1" ]; then # store what's passed via flag1 in var1 shift; var1=$1; shift elif [ "$1" == "-f2" -o "$1" == "--flag2" ]; then shift; var2=$1; shift elif [ "$1" == "-f3" -o "$1" == "--flag3" ]; then shift; var3=$1; shift # if unknown argument, just shift else shift fi done ### main # echo variable if not empty if [ ! -z $var1 ]; then echo "flag1 passed "$var1; fi if [ ! -z $var2 ]; then echo "flag2 passed "$var2; fi if [ ! -z $var3 ]; then echo "flag3 passed "$var3; fi
- $# is the size of our input argument array
- shift pops an element off of our array (the same as in Perl)
- exit exits the script
- -o is logical OR in unix
- -z checks if a variable is empty
$ ./test_args --flag1 x -f2 y --flag3 zzz flag1 passed x flag2 passed y flag3 passed zzzTo spell out how this works, the first argument is --flag1. Since this matches one of our checks, we shift. This pops this element out of our array, so the first element, $1, becomes x. This is stored in the variable var1, then there's another shift and $1 becomes -f2, which matches another condition, and so on.
The flags can come in any order:
$ ./test_args --flag3 x --flag1 zzz flag1 passed zzz flag3 passed x
$ ./test_args --flag2 asdf flag2 passed asdfWe're brushing up against the outer limits of bash here. My prejudice is that you usually shouldn't go this far with bash, because its limitations will come sharply into focus if you try to do too-involved scripting. Instead, use a more friendly language. In Perl, for example, the array containing inputs is @ARGV; in Python, it's sys.argv. Let's compare these common scripting languages:
Perl has a Getopt package that is convenient for reading arguments, and Python has an even better one called argparse. Their functionality is infinitely nicer than bash's, so steer clear of bash if you're going for a script with lots of options.Perl has a Getopt package that is convenient for reading arguments, and Python has an even better one called argparse. Their functionality is infinitely nicer than bash's, so steer clear of bash if you're going for a script with lots of options.
[1] The distinction between $* and $@ is knotty. Dive into these subtleties on Stackoverflow ↑
Multi-Line Comments, Multi-Line Strings in BashLet's continue in the realm of scripting. You can do a multi-line comment in bash with an if statement:
# multi-line comment if false; then echo hello echo hello echo hello fi(Yes, this is a bit of a hack!)
Multi-line strings are handy for many things. For example, if you want a help section for your script, you can do it like this:
cat <<_EOF_ Usage: $0 --flag1 STRING [--flag2 STRING] [--flag3 STRING] Required Arguments: --flag1 STRING This argument does this Options: --flag2 STRING This argument does that --flag3 STRING This argument does another thing _EOF_How does this syntax work? Everything between the _EOF_ tags comprises the string and is printed. This is called a Here Document. Read The Linux Documentation Project's discussion of Here Documents here.
Source and ExportQuestion:.
Dotfiles (.bashrc and .bash_profile)Dotfiles are simply files that begin with a dot. We can make a test one as follows:
$ touch .testSuch a file will be invisible in the GUI and you won't see it with vanilla ls either. (This works the same way for directories.) The only way to see it is to use the list all option:
ls -alor to list it explicitly by name. This is useful for files that you generally want to keep hidden from the user or discourage tinkering with.
Many programs, such as bash, Vim, and Git, are highly configurable. Each uses dotfiles to let the user add functionality, change options, switch key bindings, etc. For example, here are some of the dotfiles files each program employs:
- bash - .bashrc
- vim - .vimrc
- git - .gitconfig
export PATH=/some/path/to/prog:$PATHRecalling how export works, this will allow any programs we run on the command line to have access to our amended PATH. Note that we're adding this to the front of our PATH (so, if the program exists in our PATH already, the existing copy will be superseded). Here's an example snippet of my setup file:
PATH=/apps/python/2.7.6/bin:$PATH # use this version of Python PATH=/apps/R/3.1.2/bin:$PATH # use this version of R PATH=/apps/gcc/4.6.0/bin/:$PATH # use this version of gcc export PATHThere is much ado about .bashrc (read .bash_profile) and it inspired one of the greatest unix blog-post titles of all time: Pimp my .bashrc—although this blogger is only playing with his prompt, as it were. As you go on in unix and add things to your .bash_profile, it will evolve into a kind of fingerprint, optimizing bash in your own unique way (and potentially making it difficult for others to use).
If you have multiple computers, you'll want to recycle much of your program configurations on all of them. My co-worker uses a nice system I've adopted where the local and global aspects of setup are separated. For example, if you wanted to use certain aliases across all your computers, you'd put them in a global settings file. However, changes to your PATH might be different on different machines, so you'd store this in a local settings file. Then any time you change computers you can simply copy the global files and get your familiar setup, saving lots of work. A convenient way to accomplish this goal of a unified shell environment across all the systems you work on is to put your dotfiles on a server, like GitHub or Bitbucket, you can access from anywhere.
Here's a sketch of how this idea works: in HOME make a .dotfiles/bash directory and populate it with your setup files, using a suffix of either local or share:
$ ls -1 .dotfiles/bash/ bash_aliases_local bash_aliases_share bash_functions_share bash_inirun_local bash_paths_local bash_settings_local bash_settings_share bash_welcome_local bash_welcome_shareWhen .bash_profile is called at the startup of your session, it sources all these files:
A word of caution: echoing things in your .bash_profile, as I'm doing here, can be dangerous and break the functionaly of utilities like scp and rsync. However, we protect against this with the cryptic line near the top.
# the directory where bash configuration files reside INIT_DIR="${HOME}/.dotfiles/bash" # to make local configurations, add these files into this directory: # bash_aliases_local # bash_paths_local # bash_settings_local # bash_welcome_local # this line, e.g., protects the functionality of rsync by only turning on the below if the shell is in interactive mode # In particular, rsync fails if things are echo-ed to the terminal [[ "$-" != *i* ]] && return # bash welcome if [ -e "${INIT_DIR}/bash_welcome_local" ]; then cat ${INIT_DIR}/bash_welcome_local elif [ -e "${INIT_DIR}/bash_welcome_share" ]; then cat ${INIT_DIR}/bash_welcome_share fi #--------------------LOCAL------------------------------ # aliases local if [ -e "${INIT_DIR}/bash_aliases_local" ]; then source "${INIT_DIR}/bash_aliases_local" echo "bash_aliases_local loaded" fi # settings local if [ -e "${INIT_DIR}/bash_settings_local" ]; then source "${INIT_DIR}/bash_settings_local" echo "bash_settings_local loaded" fi # paths local if [ -e "${INIT_DIR}/bash_paths_local" ]; then source "${INIT_DIR}/bash_paths_local" echo "bash_paths_local loaded" fi #---------------SHARE----------------------------- # aliases share if [ -e "${INIT_DIR}/bash_aliases_share" ]; then source "${INIT_DIR}/bash_aliases_share" echo "bash_aliases_share loaded" fi # settings share if [ -e "${INIT_DIR}/bash_settings_share" ]; then source "${INIT_DIR}/bash_settings_share" echo "bash_settings_share loaded" fi # functions share if [ -e "${INIT_DIR}/bash_functions_share" ]; then source "${INIT_DIR}/bash_functions_share" echo "bash_functions_share loaded" fi
Taking care of bash is the hard part. Other programs are less of a chore because, even if you have different programs in your PATH on your home and work computers, you probably want everything else to behave the same. To accomplish this, just drop all your other configuration files into your .dotfiles repository and link to them from your home directory:
.gitconfig -> .dotfiles/.gitconfig .vimrc -> .dotfiles/.vimrc
Working Faster with Readline Functions and Key BindingsIf you've started using the terminal extensively, you might find that things are a bit slow. Perhaps you need some long command you wrote yesterday and you don't want to write the damn thing again. Or, if you want to jump to the end of a line, it's tiresome to move the cursor one character at a time. Failure to immediately solve these problems will push your productivity back into the stone age and you may end up swearing off the terminal as a Rube Goldberg-ian dystopia. So—enter keyboard shortcuts!
The backstory about shortcuts is that there are two massively influential text editors, Emacs and Vim, whose users—to be overdramatic—are divided into two warring camps. Each program has its own conventions for shortcuts, like jumping words with your cursor, and in bash they're Emacs-flavored by default. But you can toggle between either one:
$ set -o emacs # Set emacs-style key bindings (this is the default) $ set -o vi # Set vi-style key bindingsAlthough I prefer Vim as a text-editor, I use Emacs key bindings on the command line. The reason is that in Vim there are multiple modes (normal mode, insert mode, command mode). If you want to jump to the front of a line, you have to switch from insert mode to normal mode, which breaks up the flow a little. In Emacs there's no such complication. Emacs commands usually start with the Control key or the Meta key (usually Esc). Here are some things you can do:
- Cntrl-a - jump cursor to beginning of line
- Cntrl-e - jump cursor to end of line
- Cntrl-k - delete to end of line
- Cntrl-u - delete to beginning of line
- Cntrl-w - delete back one word
- Cntrl-y - paste (yank) what was deleted with the above shortcuts
- Cntrl-r - reverse-search history for a given word
- Cntrl-c - kill the process running in the foreground; don't execute current line on the command line
- Cntrl-z - suspend the process running in the foreground
- Cntrl-l - clear screen. (this has an advantage over the unix command clear in that it works in the Python, MySQL, and other shells)
- Cntrl-d - end of transmission (in practice, often synonymous with quit - e.g., exiting the Python or MySQL shells)
- Cntrl-s - freeze screen
- Cntrl-q - un-freeze screen
$ [1].) How does this cryptic symbology translate into these particular keybindings? There's a neat trick you can use, to be revealed in the next section.
Tip: On Mac, you can move your cursor to any position on the line by holding down Option and clicking your mouse there. I rarely use this, however, because it's faster to make your cursor jump via the keyboard.
[1] If you have trouble getting this to work on OS's terminal, try iTerm2 instead, as described here ↑
More on Key Bindings, the ASCII Table, Control-vBefore we get to the key binding conundrum, let's review ASCII. This is, simply, a way of mapping every character on your keyboard to a numeric code. As Wikipedia puts it:
The American Standard Code for Information Interchange (ASCI.For example, the character A is mapped to the number 65, while q is 113. Of special interest are the control characters, which are the representations of things that cannot be printed like return or delete. Again from Wikipedia, here is the portion of the ASCII table for these control characters:
([a], [b], and [c] refer to different notations—unicode, caret notation, and escape codes.)([a], [b], and [c] refer to different notations—unicode, caret notation, and escape codes.)
So, the punchline: on the terminal you can press Cntrl-v followed by a special key, like up-arrow or delete, to see its key binding. For example, what's the code for the up-arrow key? Press Cntrl-v up-arrow. On my computer the result is:
$ ^[[ACntrl-v down-arrow is:
$ ^[[Bwhile Cntrl-v Cntrl-left-arrow is:
$ ^[[5Dand so on. These may be different on your computer. As the chart above shows us, the ^[ is the terminal's notation for Escape (it can also be represented as 033 or \e). To state the obvious, a sequence of characters following the escape character can take on a life of its own: Esc-f means something different than f. So, after all this effort, we finally get the payoff of understanding how the following lines work:
#If you want to use different key bindings than mine or more functions, go for it, but the important thing is that you make use of the Readline Functions—they will save you loads of time. Remember, you can list their names with bind -l.
Note: On the Mac you can also see and edit some key bindings for the terminal in:
Terminal > Preferences > Settings > KeyboardScreenshot:
Aliases, FunctionsLet's look at another convenience bash offers: the alias command.:
alias c="cat"*)$/}'" alias awkf="awk -F'\t'" alias length="awk '{print length}'"Aliases are a godsend. But they also have their limitations. If you're familiar with git, you know the following commands might go together:
$ git add . $ git commit -m "some message" $ git pushIf you always want to call them together, you can put them in a function which gets sourced in your setup file. We'll call this function gup for git update:
A couple of notes about functions in bash: (1) the arguments to a functions are retrieved as $1, $2, etc., just as in a script; (2) if you're making a function in a script, variables are global by default unless you declare them as local. I declared mymessage as a local variable, even though in this case there's no danger I'd confuse it with a global variable of the same name.
# stage all changes, commit, then push gup () { local mymessage="next update"; # if $1 not zero length if [ ! -z "$1" ]; then mymessage=$1 fi git add . git commit -m "$mymessage" git push }
This teaches us how to build functions but it's not terribly useful, because because you can git add and git commit in a single step anyway—so this is a lot of overhead merely to call two commands together. The Linux Documentation Project provides a sample .bashrc with the following more interesting function:
There are many ways to compress files in unix, such as zip and bzip2. And the command tar is for archiving—taking a whole directory structure and rolling it up into a single file (sometimes called a tarball). This function serves as a one-size-fits-all command to untar and/or uncompress these many different compression formats. Note that, because there are so many cases, it's better to use a case statement than an if statement. }
To use this function, the syntax would simply be:
$ extract my_compressed_file.gz
$ extract my_compressed_file.bz2
$ extract my_compressed_tarball.tar.gz
The Top 20 Indispensable Unix CommandsBefore going any further, let's learn some more bedrock commands that—according to any unix primer—it would be impossible to get by without knowing:
- pwd
- ls
- cd
- mkdir
- echo
- cat
- cp
- mv
- rm
- man
- head
- tail
- less
- more
- sort
- grep
- which
- chmod
- history
- clear
head and tailheadThese are great alternatives to cat, because you usually don't want to spew out a giant file. You only want to peek at it, get a sense of the formatting, or hone in on some specific portion. If you combine head and tail together in the same command chain—we'll see how to do this in the section about unix pipelines—you can get a row of your file by number.
Another thing I like to do with head is look at multiple files simultaneously. For example, whereas cat concatenates files together:
$ cat hello.txt hello hello hello
$ cat kitty.txt kitty kitty kitty
$ cat hello.txt kitty.txt hello hello hello kitty kitty kittyhead will print out the name of the file when it takes multiple arguments, as in:
$ head -2 hello.txt kitty.txt ==> hello.txt <== hello hello ==> kitty.txt <== kitty kittyThis is useful if you're previewing many files—say doing:
$ head *
less and moreless is, as the manual pages say, "a filter for paging through text one screenful at a time...which allows backward movement in the file as well as forward movement." If you have a big file, vanilla cat is not a suitable command because printing thousands of lines of text to stdout will flood your screen. Instead, use less, the go-to command for viewing files in the terminal:
$ less myfile.txt # view the file page by pageType the arrow keys to scroll up and down, Space to page down, and q to exit. Another nice thing about less: it has many Vim-like features. This flag works particularly well in combination with the column command, which forces the columns of your file to line up nicely:
cat myfile.txt | column -t | less -S(this construction will be clearer when we learn about unix pipes below.) column delimits on whitespace by default, so if your fields themselves contain spaces and you want to delimit on tabs,_18<<
I included less and more together because I think about them as a pair, but I told a little white lie in calling more indispensable: you really only need to use less, which is an improved version of more. Less is more :-)
grepUnix has many file processing utilities, and grep and sort are among them. These are tremendously useful commands for gleaning information about files. grep is the terminal's analog of find from ordinary computing (not to be confused with unix find). If you've ever used Safari or Chrome also do an inverse grep with the -v flag. To find lines that don't contain apple, try:
$ grep -v apple myfile.txt # return lines that don't contain appleTo find any occurrence of apple in any file in some directory, use the recursive flag:
$ grep -R apple mydirectory/ # search for apple in any file in mydirectoryYou can exit after, say, finding the first two instances of apple, so you don't waste more time searching:
$ grep -m 2 apple myfile.txtThere are more powerful variants of grep, like egrep, which permits the use of regular expressions (more on these later), as in:
$ egrep "apple|orange" myfile.txt # return lines with apple OR orangeas well as other fancier grep-like tools, such as ack, available for download. For some reason—perhaps because it's useful in a quick and dirty way and doesn't have any other meanings in English—grep has inspired a peculiar cult following. There are grep t-shirts, grep memes, a grep function in Perl, and—unbelievably—even a whole O'Reilly book devoted to the command:
(Image credit: O'Reilly Media)
sort!
Two more notes about sort. Sometimes it is necessary to sort rows uniquely and the flag for this is -u:
$ sort -u testsort.txt # sort uniquelyTo get really in the weeds, another interesting flag is -T:
$ sort -T /my/tmp/dir testsort.txt # sort using a designated tmp directoryWe touched on this briefly in the section about global variables. Behind.
historyBash"or equivalently:
alias n="echo -n '# ' >> notes && history | tail -2 | head -1 | tr -s ' ' | cut -d' ' -f3- >> notes"which—you know the refrain!—will be easier to understand after we learn pipes..
Piping in UnixPiping is, without a shred of exaggeration, one of the greatest things in unix. To pipe in unix is to string commands together such that the output of the previous one becomes the input of the next one. It's the cat's meow! The beauty of piping is that commands become modular components—building blocks you can snap together a million different ways. A vertical line ( | ) is the syntactic connector:
$ cat file.txt | sort | lessLet's parse this: instead of going to stdout, the output of cat goes into sort, and the output of sort, in turn, goes into less, whose output finally lands on our screen. This is perfect when you have a big file you want to view page by page, but you want to see it sorted. Remember that there are two streams, stdout and stderr. With piping, only the stdout stream gets passed through the pipeline; the stderr—we hope there isn't any—hits our screen right away. There's a nice figure from Wikipedia summarizing this:
(Image credit: Wikipedia: Pipeline (Unix))
It's been hard to get this far without mentioning pipes and you saw we were starting to break down in the section about about loops as well as history:
$ history | tail # show the last 10 lines of history $ history | grep apple # find commands in history containing "apple"because there's no other simple way to do these things. I also mentioned that we'd learn how to print, say, the 37th line of a file using pipes. In unix there's always more than one way to skin a cat, so here are two:
$ cat -n file.txt | head -37 | tail -1 # print row 37 $ cat -n file.txt | awk 'NR==37' # print row 37(In awk, which we'll learn about below, NR is a special variable which refers to the row number.) Another command you can use in your pipelines is tee. Consider the following. We have a file text.
Using pipes expands the number of things you can do in the shell exponentially. The following are some miscellaneous examples of command pipelines.
Print the number of unique elements in the second column of a file:
$ cat file.txt | cut -f2 | sort -u | wc -lNumber the fields in a tab-delimited header and display them as a column:
$ head -1 file.txt | tr "\t" "\n" | nl -b aFind the key-binding for history-search-backward:
$ bind -P | grep history-search-backwardDisplay columns 2 through 4 of a file for rows such that the first column equals 1.
$ cat file.txt | awk '$1==1' | cut -f2-4Find all the commands in your history with pipes:
$ history | grep "|" | lessIn the previous section, I talked about my homemade alias n for notesappend. To flesh out this code snippet, the last command in history is the one we just typed:
$ history | tail -1 1022 history | tail -1We want one before the last:
$ echo Hello Hello $ history | tail -2 | head -1 1023 echo HelloThe next part is subtle:
$ history | tail -2 | head -1 | tr -s ' ' 1023 echo HelloThe -s flag in tr stands for squeeze-repeats and the point of this is that there can be a varying number of space characters in the whitespace. Since we're going to cut on space as the delimiter, we have to make sure this doesn't trip us up. With this out of the way, we simply cut on space and use awk to put a pound sign in front of the command, so it's read as a comment:
$ history | tail -2 | head -1 | tr -s ' ' | cut -d' ' -f3- | awk '{print "# "$0}' # echo HelloOne can always write a script to do something but some unix programmers like to rely on pipes to create long (sometimes unreadable) chains of commands, all the while staying on the same line. This is called a one-liner. I've witnessed some epic ones in my day!
Command SubstitutionCommand substitution is another powerful technique that allows you to run a command on the fly and use its output as an argument for another command or store it in a variable. Let's look at the later case first. It's sometimes useful to store the current working directory in a variable. With command substitution, you can do it like this:
$ d=$( pwd )
$ d=`pwd`These are two different syntaxes for doing the same thing. You should use the first one, because it's much cleaner and nicer (if you're a Perl user, you'll recognize the second one, which Perl shares). To take another example, suppose you want to store the length of your file in a variable:
$ len=$( cat file.txt | wc -l )We can also nest command substitutions. In a script you often want to use a variable to store the directory in which the script itself resides. There might be other scripts in this directory you want your script to execute, even if the script cds into another location. To pull this out, use the line:
# save scripts directory in the variable d d=$( dirname $( readlink -m $0 ) )Recall that in a unix script $0 refers to the script itself. The readlink command is a fancy way of getting the absolute path of our script and dirname gets the directory part of the path. Neat, eh?
Let's look at the first thing we said command substitution could do, using the output of a command as an argument. To head all files with extension .txt in a directory, the command is:
$ head *.txtWe could be unnecessarily verbose and do this with command substitution as:
$ head $( ls *.txt ) $ head $( find . -maxdepth 1 -name "*.txt" )You would never use these in practice, because there's a simpler way to do it. However, more often than not, command substitution is the shortcut. Let's say you want to look at myscript.pl and it's in your PATH but you can remember where it's located. Then you could use:
$ cat $( which myscript.pl )Command substitution is also very useful in loops. For example, seq prints a sequence of numbers, so:
$ for i in $( seq 1 3 ); do echo $i; done 1 2 3Question: What do the following do?
$ for i in $( cat file.txt | cut -f3 | sort -u ); do echo $i; done
$ for i in $( ls *.txt | grep -v apple ); do echo $i; doneAnswer: The first loops through all unique elements of the third column of file.txt. Here, it just echoes it, but you could do anything. The second loops through all .txt files in the cwd that do not contain the word apple. Note that we're combining command substitution with pipes!
After a long road, we're finally in a better position to understand the code we discussed above to change file suffixes. To recap, if we make three text files:
$ touch {1..3}.txtWe can change their extension from .txt to .html like so:
$ for i in {1..3}.txt; do j=$( echo $i | sed 's|\.txt|\.html|' ); cmd="mv $i $j"; echo "Run command: $cmd"; echo $cmd | bash; doneThis line features a trick: saving a command in a variable, cmd, allows us to echo it—showing the user what will be run—and then execute it by piping it into bash.
We can get as wacky as we like. For the first three directories in our PATH, the following tells us how many things are in each and how big each is:
$ for i in $( echo $PATH | tr ":" "\n" | head -3 ); do echo "*** "$i" ***"; echo "This folder has "$( ls $i | wc -l )" elements and is "$( du -sh $i | cut -f1 )" large"; echo; done *** /usr/local/sbin *** This folder has 0 elements and is 4.0K large *** /usr/local/bin *** This folder has 7 elements and is 32K large *** /usr/sbin *** This folder has 130 elements and is 8.6M large
Process SubstitutionWikipedia nails the definition of Process substitution:
....Let's take an example. Suppose the first line of your file is a header line, and you want to look at the tail of the file, but you also want to print the header. In that case, you could use:
$ cat <( head -1 file.txt ) <( tail file.txt )cat expects files as arguments, but we're getting around that with process substitution. Whatever's in the block:
<( )is treated as a file. Maybe this looks trivial to you, and you argue that you could do this just as well using:
$ head -1 file.txt; tail file.txtYou are correct. But what if you wanted to pipe all of this into another command (like column -t, which prints your file arranged into pretty columns)? Then you'd have to do it like this:
$ cat <( head -1 file.txt ) <( tail file.txt ) | column -tSo, is this the only way to do this? As long as I'm arguing with myself, I reiterate that bash is so elastic there's always another way to do something. Any ideas? Here's one answer:
$ { head -1 file.txt; tail file.txt; } | column -tCurly brackets create code blocks in bash, as in many other languages. In this case, the code in the curly brackets is executed first and everything is piped, together, into column -t.
How would you print the second column in a file twice? One way would be with awk, which we'll cover below:
$ cat test.txt | awk '{print $2"\t"$2}'However, you could also do this with process substitution:
$ paste <( cat test.txt | cut -f2 ) <( cat test.txt | cut -f2 )although the first choice is clearly better.
Sometimes you want to sort a file, but you don't want the sorting to scramble your file header. Here's how to sort on, say, the first column without touching your header:
$ cat <( head -1 temp.txt ) <( cat temp.txt | sed '1d' | sort -k1,1n )As a final example, suppose you have a simple script, test_script, which counts the lines in a file and echoes some text:
The first argument is a file you pass in to the script—say, it's 1.txt—so you could run it like this:
#!/bin/bash myfile=$1 len=$( cat $myfile | wc -l ) echo "Your file is $len lines long."
$ ./test_script 1.txt Your file is 11 lines long.But what if you've zipped all your files to save space:
$ gzip 1.txtThe program can't handle zipped input, but unzipping your files just to run them in this program is a pain. Process substitution to the rescue!
$ ./test_script <( gunzip --stdout 1.txt.gz ) Your file is 11 lines long.This gets at the marrow of what process substitution is really good at—avoiding the creation of temporary files.
If unix were a video game, piping would be level one, command substitution level two, and process substitution level three. Once you've gotten comfortable with all three, you've beaten at least one part of this game. Congratulations!
Interlude - Bell Laboratories 1982 Unix VideoNow it's time for a fun and educational interlude. In 1982, Bell Labs AT&T produced a video touting the merits of unix. It features funky turtlenecks and futuristic, yet dated, geometrical figures doing an odd dance number. I don't recognize some of the unix commands they use. Yet, to me the funniest thing about this video is how relevant many of the principles in it still are (once you get past the part about telephone switchboards). Check it out:
(Video credit: YouTube: UNIX: Making Computers Easier To Use -- AT&T Archives film from 1982, Bell Laboratories)
Processes and Running Processes in the BackgroundProcesses_23<<
htop can show us a traditional top output split-screened with a process tree. We see various users—root (discussed next), nginx, a popular web server, gives away. To echo a point made at the beginning of this article, this is one of the zillion doors basic command line competence opens.
sudo and the Root Usersudo.
awkawk, $1 is the notation for the first field, $2 is for second field, column 1 1 3 2 1
$ cat test.txt | awk '{print $2}' # print column, the commandThe take-home lesson is, you can do tons with awk, but you don't want to do too much. Anything that you can do crisply on one, or a few, lines is awk-able. I'll do some more involved examples below so you can get a better sense of awk scripting.
sedSed, like awk, is a full-fledged language that is convenient to use in a very limited sphere (GNU Sed Guide). I only use it for two things: (1) replacing text, and (2) deleting lines. Sed is often mentioned in the same breath as regular expressions (discussed below) although, like the rest of the world, I'd use Perl and Python when it comes to that. Nevertheless, let's see what sed can do.
Sometimes the first line of a text file is a header and you want to remove it. Suppose we have a file, test_header.txt, such that:
$ cat test_header.txt This is a header 1 asdf 2 asdf 2 asdfThen:
$. If we have a file, test_comment.txt, such that:
$ cat test_comment.txt 1 asdf # This is a comment 2 asdf # This is a comment 2 asdfWe can remove lines beginning with # like so:
$, the following replaces the first occurrence of kitty with X:
$ echo "hello kitty. goodbye kitty" | sed 's/kitty/X/' hello X. goodbye kittyUsing a vertical bar ( | ) as a separator, instead of a slash, is okay:
$ echo "hello kitty. goodbye kitty" | sed 's|kitty|X|' hello X. goodbye kittyTo replace all occurrences of kitty with X, we can do:
$ or directories on the command line. I often have occasion to use it in for loops. This example of changing file extensions should be very familiar by now:
$ touch file{1..3}.txt $ for i in file{1..3}.txt; do j=$( echo $i | sed 's|.txt|.html|'); mv $i $j; done $ ls file1.html file2.html file3.html
More awk ExamplesLet's do some in depth examples with awk. This section gets into gory details so, if you're just here to learn the standard command line, you can skip it with impunity.
Example 1
Suppose we have some files that start with the prefix myfile and we want to concatenate them together. However, in the resulting file, we want the first column to be the name of the file from which that row originated. We can accomplish this as follows:
$ for i in myfile*; do echo "*** "$i" ***"; cat $i | awk -v x=${i} '{print x"\t"$0}' >> files.concat.txt; doneExample 2
Suppose we have a text file of URLs, test_markup.txt:
$ cat test_markup.txt we want to convert them into HTML links. This is easy with awk:
$ cat test_markup.txt | awk '{print "<a href=\""$1"\">"$1"</a><br>"}' <a href=""></a><br> <a href=""></a><br> <a href=""></a><br>Notice that we've escaped the quote character with a slash where necessary.
Example 3
Here's an example from work: the other day I ran multiple instances of a script and had 500 input and output files. I wanted to check that the number of unique elements in the first column of each corresponding input and output file was the same. Here was my one-liner:
$ for i in {1..500}; do a=$( cat input${i}.txt | cut -f1 | sort -u | wc -l ); b=$( cat output${i}.txt | cut -f1 | sort -u | wc -l ); echo -e $i"\t"$a"\t"$b; done | awk '$2!=$3'Let's make this more readable:
$ for i in {1..500}; do a=$( cat input${i}.txt | cut -f1 | sort -u | wc -l ); b=$( cat output${i}.txt | cut -f1 | sort -u | wc -l ); echo -e $i"\t"$a"\t"$b; done | awk '$2!=$3' # print if col2 not equal to col3So, any time these numbers disagreed, awk printed the line.
Example 4
Now let's take a detour into the world of bioinformatics, a field in which studying sequencing data is one of the chief pursuits. (Because bioinformatics relies on numerous different standard, parsable file formats, it's perhaps the best Petri dish ever created for learning bash, Perl, Python, awk, and sed.) For this example, all you need to know is that a fasta file is one type of file format in which sequencing data is stored. In fasta format, every sequence has an ID line, which begins with > followed by some sequence, which is allowed to span multiple lines. For DNA, the sequence is comprised of the letters A C T G (also called base pairs or nucleotides). A fasta file of two genes could look like this:
$ cat myfasta.fa >GeneA ATGCTGAAAGGTCGTAGGATTCGTAG >GeneB ATGAACGTAA(if genes were this small) Suppose we want to create a file with ID vs length. In this example, it would be:
$ cat myfasta.fa | awk '{if ($1 ~ />/) {printf $1"\t"} else {print length}}' | sed 's|>||' GeneA 26 GeneB 10Note that length is a keyword in awk.
Another common chore is filtering a fasta file. Sometimes we want to ignore small sequences—say, anything 20 or fewer nucleotides—because either we don't believe they're real or because we'll have trouble aligning them. This is simply:
$ cat myfasta.fa | awk '{if ($0 ~ />/) {id=$0} else if (length > 20) {print id; print}}' >GeneA ATGCTGAAAGGTCGTAGGATTCGTAGTo be 100% accurate, the sequence portions of a fasta file can spill over onto more than one line and the above examples don't account for this. We can handle this by first piping our fasta file into:
$ cat myfasta.fa | awk 'BEGIN{f=0}{if ($0~/^>/) {if (f) printf "\n"; print $0; f=1} else printf $0}END{printf "\n"}'and then piping the result into what we have above.
Here is a more difficult problem. When the sequencing machine does its magic, sometimes it can't make a call what the base is, so instead of writing A C T or G it uses the character N to denote an unknown. Suppose you have a fasta file—perhaps the sequences are thousands of base pairs long—and you want to know where the coordinates of these stretches of Ns are. As a test case, let's look at the following miniature fasta file:
$ cat test.fa >a ACTGNNNAGGTNNNA >b NNACTGNNNAGGTNNIn the long tradition of one-liners, here's what I wrote to solve this problem:
$ cat test.fa | awk 'BEGIN{flag=0}{if ($0 ~ />/) {if (flag==1) {print nstart"\t"nend;}; print; pos=0; flag=0} else {for (i=1; i<=length; i++) { pos++; c=substr($0,i,1); if (c=="N" && flag==0) {nstart=pos; nend=pos; flag=1;} else if (c=="N") {nend=pos} else if (c!="N" && flag==1) {print nstart"\t"nend; flag=0}}}}END{if (flag==1) {print nstart"\t"nend;}}'Got that? Probably not, because the strength of one-liners has never been readability. Let's expand this line so we can see what it's doing:
Looks like we got the ranges right! Let's talk through this.
$ cat test.fa | awk 'BEGIN{flag=0} { if ($0 ~ />/) # ID line { if (flag==1) {print nstart"\t"nend;}; # print ID, set position to 0, flag to 0 print; pos=0; flag=0; } else # sequence line { # loop thro sequence for (i=1; i<=length; i++) { # increment position pos++; # grab the i-th letter c=substr($0,i,1); # set position if char == N # flag will raise hi if we hit an N char if (c=="N" && flag==0) { nstart=pos; nend=pos; flag=1; } else if (c=="N") { nend=pos } else if (c!="N" && flag==1) { print nstart"\t"nend; flag=0; } } # for loop }}END{if (flag==1) {print nstart"\t"nend;}}' >a 5 7 12 14 >b 1 2 7 9 14 15
In the case we're on an ID line, we reset our position variable and our flag. The flag is a boolean (meaning it will be either 1, hi, or 0, low) which we're going to set hi every time we see an N. This plays out in the following way: once we hit a sequence line, we're going to loop over every single character. If the character is an N and the flag is low—meaning the previous character was not an N—then we record this position, pos, as being both the start and end of an N streak: nstart=pos and nend=pos. If the character is an N and the flag is hi, it means the previous character was an N—hence, we're in the middle of a streak of Ns—so the start position is whatever it was when we saw the first N and we just have to update the end position. If the character is not an N but the flag is hi, it means the previous character was an N and we just finished going through a streak, so we'll print the range of the streak and set the flag low to signify we're no longer in a streak.
There's one more subtlety: what if the sequence line ends on an N character? Then we won't end up printing it because our logic only prints things the next time we see a non-N. To solve this issue, we add a line in the if (line == ID line) block to check if our flag is hi. If it is, we print the last-seen range before clearing the variables. And there's an even more subtle point: what if the last line of our file ends on an N? In this case, that fix won't work because we won't be hitting any more ID lines. To solve this, we use the END{ } block: if the flag is hi and we're done reading the file, we'll print the last-seen range. In this example, our fasta file was small and we could eyeball the N ranges but, with a monster file, we'd need to trust our awk rather than our eyes.
Example 5
Here's a final example, leaving the world of bioinformatics. Suppose you want to add numbers above each column at the top of a text file. If your file looks like this:
hello kitty kitty hello kitty kittythen the goal is to make it look like this:
1 2 3 hello kitty kitty hello kitty kittyEasy, right? It's actually not trivial because a long word in one of the columns is going to make it so you can't simply print the numbers separated by tabs if you want them to line up with the columns. To get the spacing right, you might need more than one tab in some cases. So, let's awk it:
$ cat file.txt | awk -F"\t" '{if (NR==1) { for (i=1; i<=NF; i++) {printf i; for (j=1; j<=int(length($i)/8); j++) {printf "\t"}; if (i==NF) {printf "\n"} else {printf "\t"}}; print $0 } else {print $0}}'Let's make this readable:
What's going on? First, we're going to use the first row only (NR==1) and any other row is printed as is. To number the columns, we iterate through the number of tab-delimited fields, NF. There's a word in the i-th field, and we add int(length($i)/8) extra tabs. This is because we need an new tab every eight characters: if the word is 6 letters long, we don't need any extra tabs, but if it's 12 letters we need one. Then for every field we add one tab unless we're on the last field (i==NF), in which case we add a newline. Finally, we print the first line as is.
$ cat file.txt | awk -F"\t" '{ if (NR==1) # if first line { # loop thro the number of fields for (i=1; i<=NF; i++) { # print number with no tab or newline printf i; # use the fact a tab is 8 characters # print extra tabs for long words for (j=1; j<=int(length($i)/8); j++) { printf "\t" }; # if last field, print newline; otherwise, print tab if (i==NF) { printf "\n" } else { printf "\t" } }; # print first line print $0 } else # if not first line, simply print { print $0 }}'
Regular Expressions and Globbing in BashRegular Expressions (regex for short) are a way of describing patterns in text—and once you've gone to the trouble of describing a pattern, you can write code to match it, extract some piece of it, or parse it in just about any way you like. Regex come up in so many walks of programming that it's critically important to understand the basics, even if you're not a guru.
What do the following have in common?
tttxc234 wer1 asfwaffffffff2342525
What do the following have in common?
xd2@joe.com carlos_danger@gmail.com hellokitty@yahoo.com
Bash can do regex—read about it on The Linux Documentation Project—but don't waste much time with it. The syntax is hairy and Perl and Python were born for this, so use them (as we'll discuss next). However, bash is good at something whose orbit isn't too far from regex and which we've already seen a lot of: globbing. By now, you're very familiar with the asterisk ( * ) as a wildcard:
$ touch A1f A2a A3c A4d A5a B5x # create files $ ls # list everything A1f A2a A3c A4d A5a B5x $ ls A{2..5}* # list files beginning with A2 through A5 A2a A3c A4d A5aAnd you know from above that these constructions are handy in loops. In the next section, to confuse you, we'll see that asterisk means something different in the regex context.
Command Line Perl and RegexWe've met the scripting language Perl already. Although it's falling out of favor these days—and it's definitely better to invest your time in Python if you're a beginning programmer (IMHO:)—Perl has always had a good reputation for regex. For us on the command line, it has another selling point: Perl fits easily into unix pipelines. You can make Perl run on the command line and execute code line by line using the flags -ne:
cat file.txt | perl -ne '{ some code }'This makes Perl behave just like awk—and it obeys some of the same conventions, such as using the BEGIN and END keywords. You can read more about Perl's command line options here and in even gorier detail here, but let's see how to use it. Suppose you have a text file and you want to format it as an HTML table:
$ cat test_table.txt x y z 1 2 3 a b cDoing this by hand would be pure torture. Let's do it with a one-liner on the command line:
$ cat test_table.txt | perl -ne 'BEGIN{print "<table border=\"1\">\n";}{chomp($_); my @line=split("\t",$_); print "<tr>"; foreach my $elt (@line) { print "<td>$elt</td>"; } print "</tr>\n";}END{print "</table>\n";}'iExpanding this for readability:
All we're doing here is embedding each line in a table row (tr) tag, and each field in a table data (td) tag, plus printing table tags at the beginning and end of the file.
$ cat test_table.txt | perl -ne 'BEGIN{print "<table border=\"1\">\n";}{ chomp($_); my @line=split("\t",$_); print "<tr>"; foreach my $elt (@line) { print "<td>$elt</td>"; } print "</tr>\n"; }END{print "</table>\n";}' <table border="1"> <tr><td>x</td><td>y</td><td>z</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>a</td><td>b</td><td>c</td></tr> </table>
If we have to deal with nontrivial regex on the command line, we'll be glad we're using Perl, not bash or awk. Somewhere off the internet, I stole this regex cheat sheet:
If we think of the above as nouns, we can think of the following as adjectives:If we think of the above as nouns, we can think of the following as adjectives:
To get a feeling for how to use these, let's take an example file such that:To get a feeling for how to use these, let's take an example file such that:
$ cat test.txt 889 tttxc234 wer1 CAT asfwaffffffff2342525Everything obeys the pattern non-digit string digit string except for 889, just digits, and CAT, just non-digits. Look at the following:
$ cat test.txt | perl -ne '{chomp($_); if ($_ =~ m/(\d*)/) {print $_,"\n";}}' 889 tttxc234 wer1 CAT asfwaffffffff2342525In Perl, the syntax:
some value =~ m/regular expression/tests for a match against a regular expression. Referring to our cheat sheet, the above command prints every row because every row has at least 0 digits. Let's change the asterisk to a plus sign:
$ cat test.txt | perl -ne '{chomp($_); if ($_ =~ m/(\d+)/) {print $_,"\n";}}' 889 tttxc234 wer1 asfwaffffffff2342525This prints everything with at least 1 digit, which is every row except CAT. Let's invert this and print the rows with non-digits:
$ cat test.txt | perl -ne '{chomp($_); if ($_ =~ m/(\D+)/) {print $_,"\n";}}' tttxc234 wer1 CAT asfwaffffffff2342525This prints everything with at least 1 non-digit, which is every row except 889. We can try to match a more specific pattern:
$ cat test.txt | perl -ne '{chomp($_); if ($_ =~ m/(\d+)(\D+)/) {print $_,"\n";}}' $This prints everything with the pattern at least 1 digit, at least 1 non-digit, which no rows follow. What about this?
$ cat test.txt | perl -ne '{chomp($_); if ($_ =~ m/(\D+)(\d+)/) {print $_,"\n";}}' tttxc234 wer1 asfwaffffffff2342525It prints everything with the pattern at least 1 non-digit, at least 1 digit, which three rows follow.
We can also grab pieces of our regular expression as follows:
$ cat test.txt | perl -ne '{chomp($_); if ($_ =~ m/(\D+)(\d+)/) {print $1,"\n";}}' tttxc wer asfwaffffffff
$ cat test.txt | perl -ne '{chomp($_); if ($_ =~ m/(\D+)(\d+)/) {print $2,"\n";}}' 234 1 2342525$1 refers to the piece in the first ( ), $2 the second, and so on.
Let's take another example, the one with emails. You have a file such that:
$ cat mail.txt xd2@joe.com malformed.hotmail.com malformed@@hotmail.com carlos_danger@gmail.com hellokitty@yahoo.comThen to get the strings that are appropriately formatted as emails, we could do the following:
$ cat mail.txt | perl -ne '{chomp($_); if ($_ =~ m/(\w+)@(\w+)/) {print $_,"\n";}}' xd2@joe.com carlos_danger@gmail.com hellokitty@yahoo.com
$ cat mail.txt | perl -ne '{chomp($_); if ($_ =~ m/(\w+)\@{1}(\w+)/) {print $_,"\n";}}' xd2@joe.com carlos_danger@gmail.com hellokitty@yahoo.comThese do the same thing, but we're being a little more explicit in the second case. Escaping the @ sign with a slash isn't a bad idea because in Perl @ can denote an array. If we wanted to grab lines with two @s, the syntax would be:
$ cat mail.txt | perl -ne '{chomp($_); if ($_ =~ m/(\w+)\@{2}(\w+)/) {print $_,"\n";}}' malformed@@hotmail.comQuestion: What would this do?
$ cat mail.txt | perl -ne '{chomp($_); if ( $_ =~ m/(\w+)(\@+)(\w+)/) {print $2,"\n";}}'Answer:
$ cat mail.txt | perl -ne '{chomp($_); if ( $_ =~ m/(\w+)(\@+)(\w+)/) {print $2,"\n";}}' @ @@ @ @Aside from doing matching and extracting pieces of patterns with regex, you can also do substitutions, use variables and logic, and more. Read more about Perl regex here and read about Python regex here.
Text Editors Revisited: VimBy now, you've accepted the command line into your heart. But something's still holding you back, slowing you down, sabotaging your true potential—keeping you from becoming the man or woman you want to be. This invisible drag on your abilities is the lack of a good text editor. We touched on the subject of text editors before but, now that you're a more advanced user, you've probably realized that you spend at least half of your time in the terminal editing code or text. For serious business, nano is woefully inadequate. The solution is to use either Vim, the subject of this section, or Emacs.
Borrowing a bit from my Vim wiki, Vim is a powerful text editor that allows you to do almost anything you can dream up in a text file. It has so many commands, you can almost think of it as a text editor-cum-programming language. One of the nicest things about Vim is that it's always available in your terminal. If you use a GUI text editor, like Sublime or Aquamacs, then every time you switch computers, you have to make sure you've installed the program. If you've
ssh-ed into a remote server and you're trying to edit a file with one of these GUI text editors, then you have to locally mount the server to edit the file—another headache. If these two reasons aren't compelling enough to switch to Vim, it's also a good editor in its own right.
The downside is that Vim isn't the easiest thing to learn, and it sometimes seems geared towards those with a love of the technical. But there is an extensive user manual, a Tips Wiki, and vim.org, which admirably states:
The most useful software is sometimes rendered useless by poor or altogether missing documentation. Vim refuses to succumb to death by underdocumentation.(The manual weighs in at over 250 pages—mission accomplished!) Vim is such a big subject that the goal of this section will simply be to get your feet wet and set you pointing in the right direction.
Here's a random snippet of the utility wc's source code (written in C) edited in Vim:
The yellow numbers on the left are line numbers, not part of the document. What about the word INSERT you see at the bottom? The first lesson of Vim is that it has modes. In insert mode, you write text into your document, just as in any other editor. But in normal mode, where you start when you open Vim, you issue commands to the editor. To leave normal mode and enter insert mode, you have various choices, including:
To get back into normal mode, use:
If you type a colon ( : ) in normal mode, you enter command mode (technically called command-line mode, but not to be confused with the unix command line) where you can enter syntactically more complex commands at the prompt. Delete the colon to return to normal mode. If you type a v in normal mode, you toggle visual mode, in which you can highlight text. For this section, I'll assume you're in normal mode (when this is not quite true, I'll use the notation :somecommand instead of saying, more ponderously, go into command-line mode and enter somecommand).
To save and/or quit, use:
Some basic commands to navigate through your file are:
Here are some basic copying (or "yanking") and pasting commands:
To undo or redo the previous command, use:
To find text in Vim, type a slash ( / ) followed by what you're searching for. To step through each instance of what you found, it's:
This completes the whirlwind tour. Consider yourself officially weaned off of nano. For further reading, I put together a quick and dirty Vim wiki here.
Example Problems on the Command LinePulling together everything we've learned, let's look at some examples of working on the command line. As usual, we'll meet some new commands as we go.
Problem 1
Question: How do we print the most recently modified (or created) file in the cwd?
Answer: ls has a -t flag, which sorts "by time modified (most recently modified first)", so the solution is simply:
$ ls -t | head -1Problem 2
Question: How do we print the number of unique elements in column 3 (delimiting on tab) of a text file? For example, suppose tmp.txt is:
$ cat tmp.txt 1 aa 3 1 34 z 1 f 32 2 3r z 2 d cc 3 d 34 x e cc x 1 zAnswer: We can accomplish this with a simple pipeline using the -u flag of sort to sort column 3 uniquely:
$ cat tmp.txt | cut -f3 | sort -u | wc -l 5Problem 3
Question: How do we print only the odd-numbered rows of a file? For example, suppose tmp.txt is:
$ cat tmp.txt aaa bbb ccc ddd eee fff ggg hhh iii jjjHint: Use awk.
Answer: Let's explicitly list the row number as well as the row number mod 2:
$ cat tmp.txt | awk '{print NR"\t"NR%2"\t"$0}' 1 1 aaa 2 0 bbb 3 1 ccc 4 0 ddd 5 1 eee 6 0 fff 7 1 ggg 8 0 hhh 9 1 iii 10 0 jjjNow the solution is obvious:
$ cat tmp.txt | awk 'NR%2==1' aaa ccc eee ggg iiiProblem 4
Question: Given two files, how do you find the rows that are only in one of them? For example, suppose file1.txt is:
$ cat file1.txt 1 200 324 95 10 a b cand file2.txt is:
$ cat file2.txt 3 1 200 324 95Every row in the first file is somewhere in the second file except for the rows with 10 and a b c.
Hint: Use uniq.
Answer: To find the rows that are unique to the first file, try:
$ cat file1.txt file2.txt file2.txt | sort | uniq -u 10 a b cEvery row in file2.txt is duplicated because we cat the file twice. And every row file1.txt and file2.txt share will appear at least 3 times. Then we pipe this into uniq -u which will output only unique rows for a sorted file.
Problem 5
My friend, Albert, gave me this elegant example. Here are the first 300 bases of chromosome 17 of the human genome (build GRCh37) in a file chr17_300bp.fa:
>17 dna:chromosome chromosome:GRCh37:17:1:81195210:1 REF AAGCTTCTCACCCTGTTCCTGCATAGATAATTGCATGACAATTGCCTTGTCCCTGCTGAA TGTGCTCTGGGGTCTCTGGGGTCTCACCCACGACCAACTCCCTGGGCCTGGCACCAGGGA GCTTAACAAACATCTGTCCAGCGAATACCTGCATCCCTAGAAGTGAAGCCACCGCCCAAA GACACGCCCATGTCCAGCTTAACCTGCATCCCTAGAAGTGAAGGCACCGCCCAAAGACAC GCCCATGTCCAGCTTATTCTGCCCAGTTCCTCTCCAGAAAGGCTGCATGGTTGACACACAQuestion: How would you count the number of As, Ts, Cs, and Gs in this sequence?
Hint: Use fold.
Answer: We can discard the identifier line with a grep -v ">". The command fold restricts the number of characters printed per line, allowing us to turn a row into a column, as in:
$ cat chr17_300bp.fa | grep -v ">" | fold -w 1 | head A A G C T T C T C ANow we can sort this file, so all the A, T, C, and G rows go together, and then count them with uniq -c:
$ cat chr17_300bp.fa | grep -v ">" | fold -w 1 | sort | uniq -c 73 A 100 C 63 G 64 TProblem 6
Changing a text file from one format into another is a common scripting chore. Suppose you have a file, example_data.txt, that looks like this:
,height,weight,salary,age 1,106,111,111300,62 2,124,91,79740,40 3,127,176,15500,46Question: How would you change its format into this:
1 height 106 2 height 124 3 height 127 1 weight 111 2 weight 91 3 weight 176 1 salary 111300 2 salary 79740 3 salary 15500 1 age 62 2 age 40 3 age 46?
These two different styles are sometimes called wide format data and narrow (or long) format data. (If you're familiar with the language R, the package reshape2 can toggle between these two formats).
Hint: download GNU datamash.
Answer: Taking this step by step, let's cut everything after the first comma-delimited field:
$ cat example_data.txt | cut -d"," -f2- height,weight,salary,age 106,111,111300,62 124,91,79740,40 127,176,15500,46Commas are hard to work with, so let's use a tab delimiter:
$ cat example_data.txt | cut -d"," -f2- | sed 's|,|\t|g' height weight salary age 106 111 111300 62 124 91 79740 40 127 176 15500 46Now we're going to transpose the data to make it easier to work with—one of the many great things GNU datamash does:
$ cat example_data.txt | cut -d"," -f2- | sed 's|,|\t|g' | datamash transpose height 106 124 127 weight 111 91 176 salary 111300 79740 15500 age 62 40 46Finally, we'll throw in a line of awk to finish the job:
awk '{for (i = 2; i <= NF; i++){print i-1"\t"$1"\t"$i}}'This loops from the second field to the last field and prints a row for each iteration of the loop. Scroll horizontally to see the one-liner:
$ cat example_data.txt | cut -d"," -f2- | sed 's|,|\t|g' | datamash transpose | awk '{for (i = 2; i <= NF; i++){print i-1"\t"$1"\t"$i}}' 1 height 106 2 height 124 3 height 127 1 weight 111 2 weight 91 3 weight 176 1 salary 111300 2 salary 79740 3 salary 15500 1 age 62 2 age 40 3 age 46If this seems a little messy, it is, and that's a cue to switch to a more powerful parsing language. Let's revisit this example when we discuss the Python shell below, so we can see how Python cuts through it like a knife through butter.
Problem 7
You should avoid using spaces in file names on the command line, because it can cause all sorts of annoyances. Use an underscore or dash instead.
Question: How many files and directories on your computer have spaces in their names?
Answer: To count every single file or directory on our computer, the command is:
$ sudo find / | wc -l 98912(I'm testing this on Ubuntu Server 14.04 LTS.) How many have a space in their names?
$ sudo find / | grep " " | wc -l 304Correct? Not quite, because this overcounts, as in:
$ sudo find / | grep " " | head -5 /sys/bus/pnp/drivers/i8042 aux /sys/bus/pnp/drivers/i8042 aux/bind /sys/bus/pnp/drivers/i8042 aux/00:06 /sys/bus/pnp/drivers/i8042 aux/uevent /sys/bus/pnp/drivers/i8042 aux/unbindBut we just want to count the directory or file the first time we see it, not recursively count all the non-space-containing children of a space-containing parent. We can do this as follows:
$ sudo find / | grep " " | awk -F"/" '$NF ~ / /' | wc -l 70This works by telling awk to print only the lines such that the last field (delimiting on slash) has a space in it. Here's an even simpler solution, via Albert:
$ sudo find / -name "* *" | wc -l 70Conclusion: only 0.07% of files and directories follow the poor naming convention of using a space.
Example Bash ScriptsWhen one-liners fail, it's time to script. When we were introduced to scripting above, we didn't have many tools in our toolkit. Now that we do, let's consider some example bash scripts—picking our battles for things bash can do more cleanly than Python or Perl.
Example 1
We've already seen the construction:
$ cat $( which myscript )which allows us to look at a script in our PATH without having to remember its exact location. The following example is courtesy of my friend, Albert, who packaged this up into a script called catwhich:
The -f file test operator, says The Linux Documentation Project, checks if the "file is a regular file (not a directory or device file)." The path /dev/null, where any potential error from which gets routed, is a special unix path that acts like a black hole—saving anything in there makes it disappear. Functionally, it just suppresses any error because we don't care what it is.
#!/bin/bash # cat a file in your path file=$(which $1 2>/dev/null) if [[ -f $file ]]; then cat $file else echo "file \"$1\" does not exist!" fi
There's a nearly identical version for vim, vimwhich:
Example 2
#!/bin/bash # vim a file in your path file=$(which $1 2>/dev/null) if [[ -f $file ]]; then vim $file else echo "file \"$1\" does not exist!" fi
In lab we often run scripts in parallel. Each instance of a script will produce two log files, one containing the stdout of the script and and one containing the stderr of the script. We sometimes use a convention of printing a [start] at the beginning of the stdout and an [end] at the finish. This is one way of enabling us to check if the job finished. An output log file might look like this:
[start] Some output ... [end]Here's a script, checkerror, that loops through all of the stdout log files (I assume they have the extension .o) in a directory and checks for these start and end tags:
We're again making use of /dev/null because we don't want grep to return the lines it finds—we just want to know if it's successful. We haven't encountered basename before. This simply gets the name of a file from a path, so we don't output the whole file path.
#!/bin/bash # 1st arg is logs directory logs=$1 # example: ./checkerror project/logs tot=0 # number of files scanned # loop thro .o files in logs directory for i in ${logs}/*.o*; do # get file name filename=$( basename $i ); # check for [start] and [end] tags if ! grep "\[start\]" $i > /dev/null; then echo -e "\n[error] no start tag: "${filename}; elif ! grep "\[end\]" $i > /dev/null; then echo -e "\n[error] no end tag: "${filename}; else # print a dot for each error-free file echo -n "." fi # increment total ((tot++)) done echo -e "\n[summary] $tot files scanned"
Example 3
The last example is one I wrote to test if the (bioinformatics) programs bwa, blastn, and bedtools are in the user's PATH:
If, for example, you're transferring a program with dependencies to somebody, this double-checks that they have all of the dependencies installed and accessible in their PATH. It works using the command which, which throws a bad exit code if its argument isn't found in the PATH. These lines might be something you'd see at the beginning of a script rather than a complete script in their own right.
#!/bin/bash echo "[checking dependencies]" # define dependencies dependencies="bwa blastn bedtools" for i in $dependencies; do if ! which $i > /dev/null; then echo "[error] $i not found" exit fi done
Using the Python Shell to do Math, and MoreI'm a new convert to Python and that's why I've leaned on Perl in some of the examples. However, these days it seems inescapable that Perl is the past and Python is the future. Python has many awesome features and one is the ability to run a Python shell simply by entering:
$ pythonYou can do a million things with this shell, but it's certainly the easiest way to do mathematics in the terminal. (Another convenient way is using the R shell, but you have to install R first.) For example:
$ python # open the Python shell >>> 234+234 468 >>> import math >>> math.log(234,3) 4.96564727304425 >>> math.log(234,2) 7.870364719583405 >>> math.pow(2,8) 256.0 >>> math.cos(3.141) -0.9999998243808664 >>> math.sin(3.141) 0.0005926535550994539You can read more about Python's math module here. If you want to do more sophisticated mathematics, you can install the NumPy package.
The Python command line is great not just for math but for many tasks where bash feels clumsy. Remember our parsing example above where we had a a file, example_data.txt:
,height,weight,salary,age 1,106,111,111300,62 2,124,91,79740,40 3,127,176,15500,46and we wanted to transform it into this:
1 height 106 2 height 124 3 height 127 1 weight 111 2 weight 91 3 weight 176 1 salary 111300 2 salary 79740 3 salary 15500 1 age 62 2 age 40 3 age 46If you don't know Python, skip this section. If you do, how can you do it in the Python shell? Let's start by opening the file and reading its contents:
>>> with open('example_data.txt', "r") as f: contents = f.read()Examine our variable contents:
>>> contents ',height,weight,salary,age\n1,106,111,111300,62\n2,124,91,79740,40\n3,127,176,15500,46\n'Let's convert this string into a list, by splitting on the newline character:
>>> contents.split('\n') [',height,weight,salary,age', '1,106,111,111300,62', '2,124,91,79740,40', '3,127,176,15500,46', '']Now lop off the empty field at the end:
>>> contents.split('\n')[:-1] [',height,weight,salary,age', '1,106,111,111300,62', '2,124,91,79740,40', '3,127,176,15500,46']Use list comprehension to split the elements of this list on the comma character:
>>> [x.split(',') for x in contents.split('\n')[:-1]] [['', 'height', 'weight', 'salary', 'age'], ['1', '106', '111', '111300', '62'], ['2', '124', '91', '79740', '40'], ['3', '127', '176', '15500', '46']]Now let's use a trick that if A is a list of lists, you can perform a matrix transpose with zip(*A):
>>> zip(*[x.split(',') for x in contents.split('\n')[:-1]]) [('', '1', '2', '3'), ('height', '106', '124', '127'), ('weight', '111', '91', '176'), ('salary', '111300', '79740', '15500'), ('age', '62', '40', '46')]Let's loop through this list:
>>> for j in zip(*[x.split(',') for x in contents.split('\n')[:-1]])[1:]: print(j) ('height', '106', '124', '127') ('weight', '111', '91', '176') ('salary', '111300', '79740', '15500') ('age', '62', '40', '46')We can transform any given tuple as follows:
>>> k = ('height', '106', '124', '127') >>> [str(y+1) + '\t' + k[0] + '\t' + z for y,z in enumerate(k[1:])] ['1\theight\t106', '2\theight\t124', '3\theight\t127']This is using list comprehension to meld the first element of the tuple, height, to each subsequent element and add a numerical index, as well. Let's apply this to each tuple in our list, and join everything with a newline to finish the job:
>>> for j in zip(*[x.split(',') for x in contents.split('\n')[:-1]])[1:]: ... print('\n'.join([str(y+1) + '\t' + j[0] + '\t' + z for y,z in enumerate(j[1:])])) 1 height 106 2 height 124 3 height 127 1 weight 111 2 weight 91 3 weight 176 1 salary 111300 2 salary 79740 3 salary 15500 1 age 62 2 age 40 3 age 46Whew - done!
tmuxThere's one last tool I strongly recommend you make into a habit. Imagine the following scenario: you're working in the terminal and you accidentally close the window or quit or it crashes. If you were logged in somewhere, you'll have to log in again. If you were in the middle of running a program, you'll have to start it again [1]. While your commands should be saved in history, if there was output on the screen you wanted to refer back to, it's lost forever. This is where tmux comes in. Regardless of whether or not you quit the terminal, your sessions are persistent processes that you can always access until the computer is shut off. You can get your exact terminal session back again: you're still logged in wherever you were and, moreover, you can see everything you typed in this window by simply scrolling up. If you happened to be running a program, no worries—it will still be going. For this reason, it's a good idea to make using tmux (or its old-school cousin, screen) a habit every time you're on the terminal, if only as insurance. tmux also allows you to access multiple terminal "windows" within the same terminal, err, window and more.
Let's get the terminology straight. In tmux there are:
- sessions
- windows
- panes
I'm showing off by logging into three different computers—home, work, and Amazon.
In tmux, every command starts with a sequence of keys I'll refer to as Leader. The leader sequence is Cntrl-b by default but I like to remap it to Cntrl-f [2]. Here are the basics. To start a new tmux session, enter:
$ tmuxTo get out of the tmux universe, detach from your current session using Leader d. To list your sessions, type:
$ tmux ls 0: 4 windows (created Fri Sep 12 16:52:30 2014) [177x37]This says we have one grouping of 4 virtual windows whose session id is 0. To attach to a session, use:
$ tmux attach # attach to the first session $ tmux attach -t 0 # attach to a session by idTo kill a session, use:
$ tmux kill-session -t 0 # kill a session by idHere's a small list of commands you can invoke within tmux:
See a longer list of commands here. tmux is amazing—I went from newbie to cheerleader in about 30 seconds!
Note: tmux does not come with your computer by default—you'll have to download it (see the the next section).
[1] You could circumvent this with nohup, which makes a program persist even if the terminal quits ↑
[2] You can rebind the Leader using the configuration file ~/.tmux.conf ↑
Installing Programs on the Command Line.) I have a quick gpg2 primer here.
Bash in the Programming Ecosystem (or When Not to Use Bash)All programming languages are the same. This statement is simultaneously true and not true. In the programming landscape, bash occupies a unique place. We've seen it's definitely not for heavy-duty coding. Using basic data structures, like arrays or hashes, or doing any kind of math is unpleasant in bash. Look at the horrible syntax for floating-point arithmetic (via Wikipedia):
result=$(echo "scale=2; 5 * 7 /3;" | bc)Bash's strength is system stuff, like manipulating files and directories. If you do write a bash script, it's often a wrapper—the glue which ties a bunch of programs together and bends them to your purpose. Many people would argue that you should seldom write a script in bash. Confine bash to the command line and use a modern scripting language if you want to script. Python and Perl can do more, have much friendlier syntax, and make it easy to call system commands.
However, if you're new to programming, start with unix because it will get you acquainted with important principles like input and output streams, permissions, processes, etc. faster than anything else. Furthermore, much of the material we covered above is not bash-specific. Perl is, in many ways, an extension of bash and it shares a lot of the same syntax—for file test operators, system calls with backticks, here documents, and more.
Concluding NotesAs you get deeper and deeper into unix, you may be getting the feeling that the GUI is just a painted facade—or that you're peering behind the clockface into the gears. This is true! If you think of your computer as a tool, you can do a lot more with it using unix. And given that millions of people spend half their lives in front of a computer, there are few downsides to having a greater mastery over this tool. Even if you're not doing something technical, technical questions have a way of insinuating themselves into the picture. This manual has been more about the principles of unix and hasn't introduced many of the most useful unix utilities. To learn about them, there's a reference at 100 Useful Command-Line Utilities.
So how do you go about learning unix? Just as reading a detailed book about violin won't transform you into a violinist, this article is of limited utility and defers to the terminal itself as the best teacher. You have to pay your dues and experience counts for a lot because there's so much to learn (I'm already a few years in and I learn things almost daily). Start using it and crash headfirst into problems. There's no substitute for having somebody to bother who knows it better than you do. Failing that, there's always Stackoverflow and the rest of the internet, which has become the greatest computer science manual ever compiled. In programming, I'm always surprised how much more a couple years of work taught me than a couple years of class, and perhaps this speaks volumes about the merits of apprenticeship versus classroom instruction.
Unix—with its power, elegance, and scope—is a modern marvel. If you know it and your friends don't, it's a bit like having been exposed to some awesome book or song that they haven't discovered yet. To see all the commands at your fingertips, type tab tab on the command line (there are over 2200 on my Mac!). Or do some reading for pleasure in:
$ man bash $ info coreutilsto remind yourself what you're working with. I bet you didn't think anything this cool came out of the 70s! :D
Acknowledgements and PostscriptI am graciously indebted to the following people, who contributed in ways big and small to this article:
Postscript, March 2015
I don't like remembering syntax and I forget what I've learned quickly. Thus this article started out as a memory aid—miscellaneous command line-alia for which I wanted a reference done in my own particular way, prejudices included. Its waistline expanded to its present (large) girth and it got a little play on the internet in early 2015. If I hadn't appreciated the importance of editors and fact-checkers, I do now—as the editing of this page was nerve-wrackingly crowded-sourced in real time. I've since corrected many of the errors people pointed out as well as polished and added sections, and the article is better for it.
If you've read this far, you know that this article is not, speaking in rigid literals, an introduction to unix. It's not about the nitty-gritty of how operating system kernels work. And it's not even about UNIX®, which is still a trademark—"the worldwide Single UNIX Specification integrating X/Open Company's XPG4, IEEE's POSIX Standards and ISO C" (say what!?), according to the official website. These days UNIX® refers to a detailed specification rather than software. This article, in contrast, is about command line basics. But it's not about all command lines, which would include rubbish like Windows Powershell. It's about unix-like command lines—i.e., command lines descended from the ancestral unix progenitor:
(Image credit: Wikipedia: Unix-like)
This is what I mean when I use "unix" as a colloquial shorthand. However, to begin the article by embroiling readers in these quagmires of terminology would turn them away in the first paragraph.
There were other comments but the funniest one came from my dad:
P.S. I see 2 keys at bottom of my keyboard that say, "command." Is this what all the fuss is about? I'm afraid if I touched them the computer would blow up like a roadside bomb! | https://www.oliverelliott.org/article/computing/tut_unix/ | CC-MAIN-2021-49 | refinedweb | 24,290 | 69.92 |
Debugging¶
When working with the API, chances are you’ll stumble upon bugs, get stuck and start wondering how to continue. Nothing to actually worry about – that’s normal – and luckily for you, Pyrogram provides some commodities to help you in this.
Caveman Debugging¶
The most effective debugging tool is still careful thought, coupled with judiciously placed print statements.
—Brian Kernighan, “Unix for Beginners” (1979)
Adding
print() statements in crucial parts of your code is by far the most ancient, yet efficient technique for
debugging programs, especially considering the concurrent nature of the framework itself. Pyrogram goodness in this
respect comes with the fact that any object can be nicely printed just by calling
print(obj), thus giving to you
an insight of all its inner details.
Consider the following code:
dan = app.get_users("haskell") print(dan) # User
This will show a JSON representation of the object returned by
get_users(), which is a
User instance, in this case. The output on your terminal will be something similar to this:
{ "_": "pyrogram.User", "id": 23122162, "is_self": false, "is_contact": false, "is_mutual_contact": false, "is_deleted": false, "is_bot": false, "is_verified": false, "is_restricted": false, "is_support": false, "is_scam": false, "first_name": "Dan", "status": { "_": "pyrogram.UserStatus", "user_id": 23122162, "recently": true }, "username": "haskell", "language_code": "en", "photo": { "_": " } }
As you’ve probably guessed already, Pyrogram objects can be nested. That’s how compound data are built, and nesting
keeps going until we are left with base data types only, such as
str,
int,
bool, etc.
Accessing Attributes¶
Even though you see a JSON output, it doesn’t mean we are dealing with dictionaries; in fact, all Pyrogram types are
full-fledged Python objects and the correct way to access any attribute of them is by using the dot notation
.:
dan_photo = dan.photo print(dan_photo) # ChatPhoto
{ "_": " }
However, the bracket notation
[] is also supported, but its usage is discouraged:
Warning
Bracket notation in Python is not commonly used for getting/setting object attributes. While it works for Pyrogram objects, it might not work for anything else and you should not rely on this.
dan_photo_big = dan["photo"]["big_file_id"] print(dan_photo_big) # str
AQADBAAD8tBgAQAEJjCxGgAEpZIBAAEBAg
Checking an Object’s Type¶
Another thing worth talking about is how to tell and check for an object’s type.
As you noticed already, when printing an object you’ll see the special attribute
"_". This is just a visual thing
useful to show humans the object type, but doesn’t really exist anywhere; any attempt in accessing it will lead to an
error. The correct way to get the object type is by using the built-in function
type():
dan_status = dan.status print(type(dan_status))
<class 'pyrogram.types.UserStatus'>
And to check if an object is an instance of a given class, you use the built-in function
isinstance():
from pyrogram.types import UserStatus dan_status = dan.status print(isinstance(dan_status, UserStatus))
True | https://docs.pyrogram.org/topics/debugging | CC-MAIN-2021-49 | refinedweb | 474 | 51.18 |
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Adding Behaviors to the Base Class8:49 with James Churchill
In this video, we'll review the solution to the first challenge and introduce our second challenge—adding behaviors to the MediaType base class.
Instructions
2nd Challenge
Move the
Loan()and
Return()methods and the
Loaneeand
OnLoanfields from the Album subclass to the MediaType base class.
Add a
GetDisplayText()method to any media type subclass that currently doesn't define that method.
To test your changes...
- Ensure that you're instantiating an instance of each of your media type subclasses in the Program.cs
Main()method.
- Call the
Loan()and
Return()methods on each media type subclass instance.
- Call the
GetDisplayText()method (on each media type subclass instance) after calling the
Loan()and
Return()methods..
Welcome back, how did you do? 0:00 Don't worry if you weren't able to complete the entire challenge. 0:02 After reviewing my solution, try again to complete the parts you didn't finish. 0:05 Let's walk through my solution. 0:10 To start, I added a MediaType.cs file to my 0:12 project in order to add a MediaType base class to my program. 0:15 File > New File, 0:19 then MediaType.cs. 0:22 I used the same Treehouse.MediaLibrary namespace that the other MediaType 0:27 classes use. 0:32 And I stubbed out the class. 0:38 Then I added a public field named Title of type string. 0:45 I finished my base class by adding the constructor, public, 0:53 then the name of the class, MediaType. 0:57 Followed by a set of parentheses and a set of curly braces. 1:00 I added to my constructor a title parameter of type string. 1:06 And initialized the title field using that parameter. 1:12 Next I updated my existing MediaType classes, Album, Book, and Movie, 1:18 to inherit from my new MediaType base class. 1:23 First, the Album class. 1:26 Just the the right of class name, add a space, a :, and another space. 1:31 Then the name of the base class, MediaType. 1:37 Then I updated the Book class, : MediaType, 1:40 and then the Movie class, : MediaType, 1:47 then to call the base class constructor from each of the MediaType subclasses, 1:55 I used the base keyword. 2:00 Let's start with the Album subclass. 2:01 Just to the right of the subclass's constructor parentheses, 2:07 add a : and a call to the base class constructor using the base keyword. 2:12 Sometimes it can help make the code a little bit more readable 2:18 by putting the call to the base class constructor on its own line. 2:22 Be sure to pass in the title parameter into the base class constructor call. 2:26 If you happen to have a MediaType subclass that didn't define a Title field, 2:34 you'll need to add a title parameter to your subclass constructor so 2:39 that you can pass it to the base class constructor. 2:43 And then I repeated that for the Book and Movie subclasses. 2:48 To save some typing, I'm gonna copy this line of code to the clipboard. 2:52 I'll save this file, then switch to the Book class. 2:56 I'll put my cursor right at the beginning of line 9, 3:00 right on the opening curly brace for the constructor method implementation, and 3:03 paste from the clipboard. 3:06 Save the files, and switch to the Movie class, and do the same thing there. 3:08 And lastly, I reviewed my MediaType subclasses and 3:14 removed all of the Title field definitions from those classes. 3:17 Let's start with the Movie class. 3:21 We can remove this line of code. 3:24 And down here in the constructor, we no longer need to set the Title field. 3:27 That's being handled in our base class. 3:31 Save the file, and switch to the Book class, and do the same thing. 3:34 We can remove the Title field here and the Title field initialization here. 3:38 Save the file, and switch to the Album class. 3:45 Remove the Title field and the Title field initialization, and save the file. 3:50 After I finished all those changes, I compiled and ran the program. 3:57 View > Show Console. 4:02 Then mcs *.cs -out:Program.exe 4:08 to name our binary, 4:15 && mono Program.exe. 4:18 And here's the expected output in the console, 4:23 which is the same output that we were receiving before we made these changes. 4:26 Well, at least we know that we didn't break anything 4:31 by adding the MediaType base class to our program. 4:34 The MediaType base class and my Album, Book, and 4:37 Movie subclasses form what's called a class hierarchy. 4:40 It can take a while to get comfortable with creating and 4:44 using class hierarchies, so don't worry. 4:46 If any part of this is confusing or still feels challenging, go back and 4:49 re-watch the videos from stage three of the C# objects course. 4:54 And keep practicing, you'll get it. 4:58 Now that we've defined our MediaType base class, let's add some behaviors to it. 5:01 In the previous practice session, we added behaviors to the Album : 5:05 MediaType sub-type by added methods to the Album class. 5:09 Ideally, those methods would be defined in our MediaType base class, 5:13 which would allow each of our MediaType subclasses to inherit those behaviors. 5:18 Let's review each of the methods to find in the Album subclass to see if any of 5:23 them are candidates for moving to the MediaType base class. 5:27 The GetDisplayText method, as the name suggests, 5:38 is used to get the display text for the MediaType item. 5:41 Notice that the method accesses the Title and Artist fields. 5:44 The Title field, which used to be defined in the Album class, 5:52 now lives in the MediaType base class. 5:56 This code continues to work fine, 5:59 as subclasses can access any non-private field defined in the base class. 6:01 The Artist field, though, is still defined in the Album class. 6:06 Unfortunately, this will prevent us from moving the GetDisplayText method 6:10 to the base class. 6:15 Why is that? 6:16 Well, while it's possible for 6:17 subclasses to access non-private base class fields, the opposite isn't true. 6:19 Base classes can't access fields defined in subclasses. 6:25 So if were to move the GetDisplayText method do the base class, 6:30 our code would no longer compile. 6:34 You might wonder why we wouldn't just move the Artist field into the base class 6:37 like we did with the Title field. 6:41 While each of our MediaType subclasses defined a Title field, 6:43 the Artist field is specific to the Album media item subtype. 6:46 Moving the Artist field to the base class would make it available to the Book and 6:51 Movie subtypes, which, from an object-oriented design perspective, 6:55 doesn't feel like the right thing to do. 7:00 For now, let's leave the GetDisplayText method defined in the Album class. 7:02 In a future course, you'll learn how another feature of object-oriented 7:07 programming, abstract classes and methods, can provide a solution to this problem. 7:11 See the teacher's notes for more information. 7:16 In addition to the GetDisplayText method, we also added the Loan and Return methods, 7:19 which are used to loan out and return items from and to our MediaLibrary. 7:25 Notice that the Loan and Return methods access the Loanee and 7:30 OnLoan fields here, here, and here. 7:34 Unlike the Artist field, though, the Loanee and 7:40 OnLoan fields aren't specific to the Album : MediaType subtype. 7:42 Ultimately, we want to be able to loan out any item from our MediaLibrary, 7:47 regardless of its subtype. 7:51 Given that, we can safely move the Loan and Return methods, 7:53 along with the Loanee and OnLoan fields, to the MediaType base class. 7:58 For your second challenge, move the Loan and Return methods and the Loanee and 8:03 OnLoan fields from the Album subclass to the MediaType bass class. 8:08 And to help support testing, add a GetDisplayText method 8:13 to any MediaType subclass that doesn't currently define that method. 8:16 And lastly, to test your changes, ensure that you're an instantiating an instance 8:21 of each of your MediaType subclasses in the program.cs file's main method. 8:26 Call the Loan and Return methods on each MediaType subclass instance. 8:32 And call the GetDisplayText method on each MediaType subclass instance 8:37 after calling the Loan and Return methods. 8:43 And that's the second challenge. 8:46 See you in just a bit. 8:48 | https://teamtreehouse.com/library/adding-behaviors-to-the-base-class | CC-MAIN-2020-40 | refinedweb | 1,617 | 72.26 |
STufaroMember
Content count52
Joined
Last visited
Community Reputation183 Neutral
About STufaro
- RankMember
[Solved] Thick (Constant-Width) Lines Using Quads
STufaro replied to STufaro's topic in Graphics and GPU ProgrammingJason, Thanks for the fast reply and the idea! It turns out that the point where the triangles cross will be the W = 0 point, so your thinking was spot-on and a lot more exact than mine [img][/img] (I was taking potshots in the dark hoping that the point I picked would keep the perspective--I'm glad I now know the reason). However, your reply inspired me to try something else, and [b]I managed to solve my problem![/b]: [url=""][/url]) Therefore, I needed to add a bit to my code: [CODE] if ((extrudeScale1 < 0) ^ (extrudeScale2 < 0)) { // just assume line direction won't be hurt by using X and Y float x1 = line1start.X; float x2 = line2start.X; float y1 = line1start.Y; float y2 = line2start.Y; float a1 = line1vec.X; float a2 = line2vec.X; float b1 = line1vec.Y; float b2 = line2vec.Y; if ((Math.Abs(lineDirection.Y) < 0.001f) && (Math.Abs(lineDirection.X) < 0.001f)) { // if the line is purely in the Z direction, however, we need to use Z instead of Y y1 = line1start.Z; y2 = line2start.Z; b1 = line1vec.Z; b2 = line2vec.Z; } else if ((Math.Abs(lineDirection.X) < 0.001f) && (Math.Abs(lineDirection.Z) < 0.001f)) { // and similarly, if purely in the Y direction, we need to use Z instead of X x1 = line1start.Z; x2 = line2start.Z; a1 = line1vec.Z; a2 = line2vec.Z; } float t1 = (y1 - y2 - b2 * ((x1 - x2) / a2)) / (b2 * a1 / a2 - b1); float x = line1vec.X * t1 + line1start.X; float y = line1vec.Y * t1 + line1start.Y; float z = line1vec.Z * t1 + line1start.Z; } [...[img][/img]). [img][/img] They're not exactly award-winning without a fair amount of AA, and even then they're pretty ugly. There may even still be some artifacts in there...but I think I'm ready to call them good-enough for my game [img][/img] Thanks again, Jason, for your help--without the help and encouragement of the GD community I'd have made far less progress on my project. Best regards, -- Steve
[Solved] Thick (Constant-Width) Lines Using Quads
STufaro replied to STufaro's topic in Graphics and GPU ProgrammingWell, after a little bit of struggling yesterday I've come up with a buggy, but somewhat-working, implementation. My basic steps are as follows:[list=1] [*][b]Get the vector of the line:[/b] [CODE]lineDirection = (lineStart - lineEnd)[/CODE] [*][b]Find our soon-to-be constructed quad's normal as:[/b] [CODE]quadNormal = cameraPosition - lineMidpoint[/CODE] Where lineMidpoint = ((lineStart + lineEnd) / 2). I reason this should be the quad's normal since the quad will always be facing the camera, like a billboard. [*][b]Get the direction along which we should extrude vertices from our line[/b], which is the cross product of lineDirection and quadNormal: [CODE]extrudeDirection = Vector3.Cross(lineDirection, quadNormal)[/CODE] Normalize extrudeDirection. [*][b]Get the W of lineStart and lineEnd by transforming them by the viewMatrix * projectionMatrix.[/b] [CODE]wStart = (Vector3.Transform(lineStart, viewMatrix * projectionMatrix)).W wEnd = (Vector3.Transform(lineEnd, viewMatrix * projectionMatrix)).W[/CODE] [*][b]Extrude vertices from the line along the extrudeDirection vector, in some multiple of the W.[/b] [CODE[/CODE] [*][b]Connect the vertices to form a quad.[/b] [/list] And therein lies the hitch, which took some unraveling for me. If you are far from the line, both W's will be positive, which is fine, since presumably you connected your four vertices to form a quad with the diagonal of the triangles being shared between them. Un-projected, this quad looks like a trapezoid, with bases on either side, and one base larger than the other to cancel out the W-divide. Everything works well. However, if you get close to the line and rotate the camera a bit to face one end, one vertex will go off-screen and behind the camera, and thus one of the W's will be negative. This mathematically legit, I've reasoned, but your vertices that you extrude will be created on opposite sides of the line. If you don't change the way your vertices are connected in this situation, your triangle's diagonals will cross, because on one side of the quad the vertices have been flipped over the line. The result is you get an extra "flap" of the triangle either below or above your line, which confused me to no end yesterday. In the below [s](high-quality rendering)[/s] diagram, the red section is what I'm talking about. [img][/img] To get rid of the red section, I adjusted the vertices of the triangles to the [b]point where the diagonals cross[/b] [b]when one of the W's was negative.[/b] That way, you'd get just the white part of the two triangles. (To get this point, I solve the equations of the two lines in 3D (since they're coplanar, they will intersect).) That seemed to solve the problem in one little test I did, but when I scaled up and made a bunch of lines for my in-game grid, problems galore popped up, including some of the same problems the D3DXLine class seems to have (it appears to negate the transforms when you get close), which is not a good sign. If anyone had the patience to read my essay on drawing lines with quads and has an idea on where in this process I went wrong, please do let me know--I'm very curious. I also don't want to abandon thick lines, but for now I'm just using a LINE_LIST to draw my grid. I'll keep us updated if I come up with anything else, too. Best, -- Steve
[Solved] Thick (Constant-Width) Lines Using Quads
STufaro posted a topic in Graphics and GPU ProgrammingHi all, I am making a 3D level editor for my game and would like to add grid lines, but ones better (namely, thicker) than the thin 1-px lines created by rendering a LINE_LIST. I've run across several posts using D3DXLine, and tried it myself, but found that the transforms were buggy, so I set out to make 3D lines from quads aligned to face the camera (i.e., billboards). I do not completely understand billboards, but I've been playing with them long enough to have a general feel of how they work and can create some on my own. I would like to keep the lines a constant thickness, no matter how close or far the camera is from them. I tried using an orthographic projection to no avail, and I've also tried doing a perspective divide manipulation (or rather, multiplication) on my billboard's vertices to find out how much I should scale them. No attempt so far I've made looks even remotely correct, and I think I'm just confusing myself trying to mess with different things for an easy solution... Can anyone outline the basic steps of how I would go about doing this (e.g., step 1, make quad vertices, step 2, rotate, step 3...etc.)? How would you solve this problem? An external link of someone solving the same problem, but without perspective (plus I'd rather not use a vertex shader and am having trouble understanding his assembly code): [url=""][/url] (Just a note--working in Direct3D9 via SlimDX and C#, so that's why I reference Direct3D-specific names, but I have no need for API-specific examples--anything should work for me.) Best regards, -- Steve ----- [size=5][b]Edit: SOLVED! And I'm very happy...See the following posts...[/b][/size]
How to tell if triangles enclose a volume
STufaro replied to STufaro's topic in Math and PhysicsEmergent, alvaro, These were two great answers and a great discussion to read--I must admit I'm not following completely on the math, but the methods you've suggested make sense to me. For the purposes of the game I'm writing, I am not concerned about the fringe case Klein bottle, but that is an interesting point since a Klein bottle doesn't enclose anything I really like the painting solution, though. When I find the time to implement it, I'll give it a shot and [hopefully remember to] post the results. Much thanks for the ideas--the contents of your posts and the support of this community gives me both the confidence and the willpower to finish what I started...(when I find the time!) Best, -- Steve.
Limit quaternion rotation speed
STufaro replied to BleuBleu's topic in Math and Physics[quote name='BleuBleu' timestamp='1298867108' post='4779960'] So, suppose I want to go from a rotation q1 to a rotation q2 and I don't want to rotate by more than x radians per frame. I tried this, but for some reason, it seem to introduce some unexpected rotations from time to time, any idea why? 1) Find delta rotation that will transform q1 into q2: delta = q2 * q1.Inverse() 2) Convert delta rotation to axis + angle 3) Clamp the angle to x 4) Reconstruct new (clamped) delta rotation 5) My final, clamped rotaiton should now be: delta * v1 Ideas? Suggestions? Thanks! -Mat [/quote] Mat, I'm not sure where the unexpected rotations come from--are you using Euler angles at any point? They might be because of a phenomenon known as gimbal lock--see this wiki article: [url="."].[/url] This happens when you go to Euler angles from quaternions (quaternions avoid the problem), because you have a series of rotations, and depending on which order you apply them (e.g., X-Y-Z, Z-X-Y), it may change things. That shouldn't affect axis-angle, though, but my hunch is the way to get around it is just keep everything as quaternions. I know that you can simply add two quaternions and divide them to "average" them out, resulting in a smoother transition. I had an application where there was a tank rolling over a heightmap--I noticed the tank "snapped" to the normals of each triangle it rolled over, so I averaged the normals between frames and smoothed the transitions a lot. [code] Quaternion approach (Quaternion initialRotation, Quaternion finalRotation) { return (initialRotation + finalRotation)/2; } [/code] If you keep feeding that back into itself after each frame, you'll get a fast movement at first and a slow movement toward the end, which looks nice. Using the same principle, you can get a quaternion somewhere between your initial and final: [code] Quaternion approach (Quaternion initialRotation, Quaternion finalRotation, float position) { // position between 0 and 1 return (1 - position) * initialRotation + position * finalRotation; } [/code] Correct me if I'm wrong, or let me know if that helps. Best of luck, -- Steve.
How to tell if triangles enclose a volume
STufaro posted a topic in Math and PhysicsHi all, I: [url=""][/url] [url=""][/url]: [img][/img]: [img][/img]" ), but it doesn't immediately take care of the other cases I want to allow for either. Might anyone be able to come up with a better method off the top of his/her head? I'm stumped on this one. Regards, -- Steve.
DX11 [slimDX] textures on the simpletriangle
STufaro replied to georges123's topic in Graphics and GPU ProgrammingYour HLSL shader that you posted -- is that the complete shader? You never defined "txDiffuse," so it'll tell you that it doesn't exist when it tries to compile the shader. You're going to want to take a look at Riemer's XNA or Managed DirectX tutorials for this problem; it's explained nicely. This has exactly what you're looking for: The basics as I understand them in DirectX 9 are this: You need to set up a shader with a texture sampler (tells the graphics card how to pick/generate pixels from the texture). You then set the texture in the shader in your C++ program, and the sampler figures out how to color the pixels from the texture you fed it and your pixel shader code. I don't know if it's exactly the same for Direct3D 11, but something tells me the HLSL interaction part should be similar. Best, - Steve.
Rotating Camera For Different Views
STufaro replied to duskndreamz's topic in Graphics and GPU ProgrammingMy brain is fuzzy and I haven't messed with computers in a while, but I'll take a random stab. You are rotating the camera 40 degrees one way and 40 degrees another way to produce 3 different views, and the camera has the same projection matrix for each view (as I understand it). I think you need to take a step back and look at that projection matrix. The way I would do it is this: your total FOV angle should be whatever you want it to be (across the three monitors). Let's say this is 180 degrees (that would mean the edges of the left and right monitors are lined up with your ears, I guess). I'd take 180 degrees and divide it by 3. I use that FOV angle in my projection matrix for each camera. Then I rotate each of the end cameras by the FOV angle left or right and get their view matrices (I think you have that part down, but 40 degrees is not the right number for the FOV angle you're using). What is your FOV angle? Remember you don't want the views to overlap, so the larger the FOV angle, the more you have to rotate each camera so the views sync up. As for the other stuff: The math gods may correct me if I'm wrong, but aspect ratio and resolution shouldn't matter. It should be all in the projection matrix as far as I know. I don't know that I helped and you might have already tried all that, but let me know if you have any other thoughts. I'm curious about this problem. Best, - Steve.
- Hodgman, I'm sorry I haven't been on GD Net as religiously as I would have liked to be to follow this! This is truly excellent, and I don't think anyone minds you treating this thread like a dev-blog. At least I don't :) So the sub-offset was the way to go--good find for working on the downsampled map! I think my curiosity about the specular value of the pixels might have been too much work per-pixel, so I'm very happy to see the downsampled map work in some way (even if it worked "as fast," it would still bug me that it was per-pixel for some reason). Thanks for keeping us posted on the technique--one day I'll write a game and look back to this :). I think your DOF blur implementation will complete it and give you a very convincing effect once you've tweaked it as necessary. Nice job! ratings++; -- Steve.
- Oh, I see; so each letter is in its own bitmap file? FillRect() is a GDI thing, not a DirectX-based function, am I right? I don't know where DirectX comes into this, but I have an idea for you if you're using Direct3D. I'd put all my letters in one bitmap, evenly spaced apart (or not--depends on what you want to do). Then I'd let 0 = A, 1 = B, 2 = C. Then I'd make a strip of vertices that's just a bunch of connected squares, with double vertices at each overlap. Then I'd put a letter on each square with texture coordinates. So, my bitmap file of the alphabet stores each letter as a 32x32 square let's say: A B C D E F G H I ... etc. I make a horizontal grid of vertices, with doubles on the overlapping edges of the individual squares I'm trying to form. 1 2/5 7/9 11 3 4/6 8/10 12 That's 3 square right there. Now I want to write "CAT"; I know C = 2, A = 0, T = 19. If I have 26 letters in my bitmap, I know that there is a texture coordinate of 1/26 between the letters (remember texture coordinates go from 0 to 1). Now I start setting some texture coordinates. C = 2. So I set the following texture coordinates (U, V) for each vertex for the letter C: 1: (2 * 1/26, 0) 2: (2 * 1/26, 1) 3: (3 * 1/26, 0) 4: (3 * 1/26, 1) A = 0. So for A: 5: (0 * 1/26, 0) 6: (0 * 1/26, 1) 7: (1/26, 0) 8: (1/26, 1) T = 19. 9: (19 * 1/26, 0) 10: (19 * 1/26, 1) 11: (20 * 1/26, 0) 12: (20 * 1/26, 1) And I'm done. Does that work for you, or do you need something in GDI?
- Have you tried using fonts?
Incorrect shader/normal issue in Directx
STufaro replied to kobaj's topic in Graphics and GPU ProgrammingExcellent! I've never had to deal with a coordinate system mix-up, but now I know what one looks like. And I know what you mean about long works in progress... Anyway, glad I could help throw stuff out there. -- Steve.
- Awesome effect. I love bokeh, so much that spent millions of dollars on building a depth of field adapter for my video camera so I could make grainy movies full of bokeh. You have an interesting approach here--more thinking than I would have put into this at first, but now that you are describing your problem, I'm having ideas. I know you say that you're not doing DOF blurring just yet. One thing I would like to mention--the blurs don't pick out the specular highlights, although it does seem that way sometimes. The blurs happen to the whole image, and you _notice_ the specular highlights because they most obviously get blurred against a dark background. In fact, the entire image behind your subject is being blurred with what Photoshop would call a "lens blur" (just a convolving filter like you plan to apply for your DOF blur). The size of the blur is a function of your depth of field and your distance only, not the luminosity, if I remember right (correct me if I'm wrong though!). Lens blur is imperfect though; take a look at this page on bokeh at Wikipedia, particularly the faux-bokeh shown at the bottom. You don't really get a choice of apertures, which I think is why we need your effect. You might have already known all that though--in which case, sorry I digress! Ultimately I think we need a way of blurring the specular highlights using your aperture shape, which are getting slightly muddled in your downsampling (and so a new pixel gets the chance to be "brightest" each time). This sounds simple, and I am not a shader pro or familiar with GLSL, but is there a way you can operate on the specular value of your stuff (input to the pixel shader maybe? I'm not sure where that comes together, to be honest!) and apply your effect to things with a specular value >0.5? I'm also not sure that that would work for light sources, though, which are also a wonderful source of bokeh blurs. One other thing--I notice your blurs from the floor are getting drawn in front of your character. Just out of curiosity, how are you going to stop that from happening (I'm still learning shaders bit by bit here, there's probably an awesomely easy way to do it, so sorry for the dumb questions!)? I might be going down the wrong path with that; it's getting late for me. Let us know how this turns out though, I'm very interested in this effect! -- Steve.
Incorrect shader/normal issue in Directx
STufaro replied to kobaj's topic in Graphics and GPU ProgrammingOkay, sorry for the late reply. The shader looks perfect--is this from Riemer's tutorial by any chance? :) A couple more questions I should have asked: 1. What's the orientation of the cube? (What's the camera and cube position? Or, the face on the top is in the X-Z plane, the face on the right is in the Y-Z plane, and the face on the left is in the X-Y plane, right?) 2. What's the other side of the cube look like? Can you move the camera there so we can see what that looks like? 3. You generated that corrected cube image outside your program, right? (Photoshop or something?) The answer to my second question is particularly important: I have a hunch that your two faces that you show rotating in your figure are actually correctly lit, and the one closest to us (on the left in your figure) is actually incorrect. If we get to the other side of the cube (rotate the camera 180 deg around the cube's Y axis) and find that the other face is dark, I would say both those faces have their normals pointing inwards. The light is on the other side of the face we see is lit, and the face you think is right actually has its normal pointing inwards toward the center of the cube (at the light) and is thus getting lit incorrectly. If the opposing face is dark, its normal is wrong too. Try flipping it and see what happens. (There's a chance that if one's flipped, they're all flipped, so stick a negative sign in front of them in your shader and see if things look right; if things look worse, undo that and try flipping them one by one in your code to find the bad one.) That was probably a bad explanation; if I had the art skills I would draw it. But does that make sense? You might have already done those things--sorry if I'm asking a lot of the same questions you've asked yourself! Just trying to get oriented. I'm interested in this kind of problem though, because it's the little gnat that bugs you when you're programming, maybe for a couple days, but when you realize your mistake (it can sometimes be a silly one, like a negative sign), you'll recognize the situation (or a similar one) later and know how to fix it immediately. In the meantime...let me try and come up with a picture to explain what I'm saying... Good luck! -- Steve.
Incorrect shader/normal issue in Directx
STufaro replied to kobaj's topic in Graphics and GPU ProgrammingI'm curious to see your shader. I think your vertex shader may be flipping things around. You can post it using either ['source]['/source] (get rid of the '). -- Steve. | https://www.gamedev.net/profile/106479-stufaro/?tab=idm | CC-MAIN-2018-05 | refinedweb | 3,861 | 68.91 |
#include <GA_SharedLoadData.h>
Class to hold shared data during the loading process.
Some primitive types store shared data between them. This class is used as an interface to retain data during the loading/saving process. It also Facilitates the delayed loading of this shared data.
Saving:
When saving, primitives will have a "pre-save" pass. During this pass, they can add "shared" data to the GA_SaveMap. The primitive can check to see if the data is already stored in the map, if not, it can add a GA_SharedLoadData to the map (given a unique key). A single JSON will be be saved. Subsequent primitives, should detect that the data is stored so that only a single copy of the shared data is saved in the map.
When the primitive saves its local data, it can make reference to the named shared data.
Dring loading time GA_SharedDataHandles are created to represent all the shared data. Primitives then ask the GA_LoadMap for a copy of these handles. Whenever the primitive needs the data it is requested from the shared data handle and returned as a GA_SharedLoadData
Definition at line 41 of file GA_SharedLoadData.h.
Returns the key that is used to refer to this shared data.
Implemented in GEO_PackedNameMap::LoadContainer. | http://www.sidefx.com/docs/hdk/class_g_a___shared_load_data.html | CC-MAIN-2018-30 | refinedweb | 208 | 66.23 |
in reply to Why I Hate Nested If-Else blocks
I use two general solutions, depending on how complex the problem is.
The first option is to use a table of function pointers:
%FLUT = (
'condition_1' => \&func_1,
'condition_2' => \&func_2,
'condition_3' => \&func_3,
);
$condition = ## reduce the input to a known condition
$FLUT{$condition}->(@args);
[download]
and since I happen to like object syntax, I have a simple little class that wraps function pointers up as objects:
package Command;
sub new {
my $type = shift;
my $O = shift;
bless $O, $type;
return ($O);
}
sub execute {
my $O = shift;
return ($O->( @_ ));
}
[download].
If a project involves serious branching, I'll occasionally roll my own linear state machine:;
[download]
This code comes from a larger project, where the parameter $model was itself an object. The Model was responsible for all the data in the program, and the Commands simply called sets of Model methods.
## _get_commands (nil) : listref
#
# each Machine has its own list of Commands that should be
# executed in response to the user's input. this routine returns
# a reference to that list.
#
[download]
=head1 FUNCTIONS ....
=head2 C<_get_commands (nil) : listref>
each Machine has its own list of Commands that should be
executed in response to the user's input. this routine returns
a reference to that list.
=cut
[download]
____________________________________________________** The Third rule of perl club is a statement of fact: pod is sexy.. | http://www.perlmonks.org/index.pl/jacques?node_id=136124 | CC-MAIN-2017-39 | refinedweb | 230 | 57.3 |
Configuring Centralized Cache Management in HDFS
Centralized cache management in HDFS is an explicit caching mechanism that allows users to specify paths to be cached by HDFS. The NameNode communicates with DataNodes and instructs them to cache specific blocks in off-heap caches.
Centralized and explicit caching has several advantages:
- Frequently used data is pinned in memory. This is important when the size of the working set exceeds the size of main memory, which is common for many HDFS workloads.
- Cluster memory is optimized because you can pin m of n block replicas, saving n-m memory. Before centralized pinning, repeated reads of a block caused all n replicas to be pulled into each DataNode buffer cache.
- Tasks are co-located with cached block replicas, improving read performance. Because the NameNode manages DataNode caches, applications can query the set of cached block locations when making task placement decisions.
- Clients can use the zero-copy read API, and incur almost no overhead, because each DataNode does a checksum verification of cached data only once.
Continue reading:
Use Cases
Centralized cache management is best used for files that are accessed repeatedly. For example, a fact table in Hive that is often used in JOIN clauses is a good candidate for caching. Caching the input of an annual reporting query is probably less useful, as the historical data might be read only once.
Centralized cache management is also useful for mixed workloads with performance service-level agreements (SLAs). Caching the working set of a high-priority workload insures that it does not contend for disk I/O with a low-priority workload.
Architecture
In this architecture, the NameNode is responsible for coordinating all the DataNode off-heap caches in the cluster. The NameNode periodically receives a "cache report" from each DataNode which describes all the blocks cached on a given DataNode. using Java and command-line APIs. The NameNode also stores a set of cache pools, which are administrative entities used to group cache directives together for resource management and enforcing permissions.
The NameNode periodically rescans the namespace and active cache directories to determine which blocks need to be cached or uncached and assigns caching to DataNodes. Rescans can also be triggered by user actions such as adding or removing a cache directive or removing a cache pool.
Currently, blocks that are under construction, corrupt, or otherwise incomplete are not cached. If a cache directive covers a symlink, the symlink target is not cached. Caching is currently done on a per-file basis (and not at the block-level).
Concepts
Cache Directive
A cache directive defines a path that should be cached. Paths can be either directories or files. Directories are cached non-recursively, meaning only files in the first-level listing of the directory are cached.
Directives have parameters, such as the cache replication factor and expiration time. Replication factor specifies the number of block replicas to cache. If multiple cache directives refer to the same file, the maximum cache replication factor is applied. Expiration time is specified on the command line as a time-to-live (TTL), a relative expiration time in the future. After a cache directive expires, it is no longer considered not used.
Cache pools are also used for resource management. Pools can enforce a maximum limit that restricts the aggregate number of bytes that can be cached by directives in the pool. Normally, the sum of the pool limits roughly equals the amount of aggregate memory reserved for HDFS caching on the cluster. Cache pools also track a number of statistics to help cluster users determine what is and should be cached.
Pools also enforce a maximum time-to-live. This restricts the maximum expiration time of directives being added to the pool.
cacheadmin Command-Line Interface
On the command-line, administrators and users can interact with cache pools and directives using the hdfs cacheadmin subcommand. Cache directives are identified by a unique, non-repeating 64-bit integer ID. IDs are not reused even if a cache directive is later removed. Cache pools are identified by a unique string name.
Cache Directive Commands
addDirective
Description: Add a new cache directive.
Usage: hdfs cacheadmin -addDirective -path <path> -pool <pool-name> [-force] [-replication <replication>] [-ttl <time-to-live>]
Where, path: A path to cache. The path can be a directory or a file.
pool-name: The pool to which the directive will be added. You must have write permission on the cache pool to add new directives.
force: Skips checking of cache pool resource limits.
replication: The cache replication factor to use. Defaults to 1.
time-to-live: Time period for which the directive is valid. Can be specified in seconds, minutes, hours, and days, for example: 30m, 4h, 2d. The value never indicates a directive that never expires. If unspecified, the directive never expires.
removeDirective
Description: Remove a cache directive.Usage: hdfs cacheadmin -removeDirective <id>
Where, id: The id of the cache directive to remove. You must have write permission on the pool of the directive to remove it. To see a list of PathBasedCache directive IDs, use the -listDirectives command.
removeDirectives
Description: Remove every cache directive with the specified path.
Usage: hdfs cacheadmin -removeDirectives <path>
Where, path: The path of the cache directives to remove. You must have write permission on the pool of the directive to remove it.
listDirectives
Description: List PathBasedCache directives.
Usage: hdfs cacheadmin -listDirectives [-stats] [-path <path>] [-pool <pool>]
Where, path: List only PathBasedCache directives with this path. Note that if there is a PathBasedCache directive for path in a cache pool that we do not have read access for, it will not be listed.
pool: List only path cache directives in that pool.
stats: List path-based cache directive statistics.
Cache Pool Commands
addPool
Description: Add a new cache pool.
Usage: hdfs cacheadmin -addPool <name> [-owner <owner>] [-group <group>] [-mode <mode>] [-limit <limit>] [-maxTtl <maxTtl>]
Where, name: Name of the new pool.
owner: Username of the owner of the pool. Defaults to the current user.
group: Group of the pool. Defaults to the primary group name of the current user.
mode: UNIX-style permissions for the pool. Permissions are specified in octal, for example: 0755. By default, this is set to 0755.
limit: The maximum number of bytes that can be cached by directives in this pool, in aggregate. By default, no limit is set.
maxTtl: The maximum allowed time-to-live for directives being added to the pool. This can be specified in seconds, minutes, hours, and days, for example: 120s, 30m, 4h, 2d. By default, no maximum is set. A value of never specifies that there is no limit.
modifyPool
Description: Modify the metadata of an existing cache pool.
Usage: hdfs cacheadmin -modifyPool <name> [-owner <owner>] [-group <group>] [-mode <mode>] [-limit <limit>] [-maxTtl <maxTtl>]
Where, name: Name of the pool to modify.
owner: Username of the owner of the pool.
group: Groupname of the group of the pool.
mode: Unix-style permissions of the pool in octal.
limit: Maximum number of bytes that can be cached by this pool.
maxTtl: The maximum allowed time-to-live for directives being added to the pool.
removePool
Description: Remove a cache pool. This also uncaches paths associated with the pool.
Usage: hdfs cacheadmin -removePool <name>
Where, name: Name of the cache pool to remove.
listPools
Description: Display information about one or more cache pools, for example: name, owner, group, permissions, and so on.
Usage: hdfs cacheadmin -listPools [-stats] [<name>]
Where, name: If specified, list only the named cache pool.
stats: Display additional cache pool statistics.
Configuration
Native Libraries
To lock block files into memory, the DataNode relies on native JNI code found in libhadoop.so. Be sure to enable JNI if you are using HDFS centralized cache management.
Configuration Properties
Required
- dfs.datanode.max.locked.memory: The maximum amount of memory a DataNode uses for caching (in bytes). The "locked-in-memory size" ulimit (ulimit -l) of the DataNode user also needs to be increased to match this parameter (see OS Limits). When setting this value, remember that you need space in memory for other things as well, such as the DataNode and application JVM heaps and the operating system page cache.
Optional
- dfs.namenode.path.based.cache.refresh.interval.ms: The NameNode uses this as the amount of milliseconds between subsequent path cache rescans. This calculates the blocks to cache and each DataNode containing a replica of the block that should cache it. By default, this parameter is set to 30000, which is 30 seconds.
- dfs.datanode.fsdatasetcache.max.threads.per.volume: The DataNode uses this as the maximum number of threads per volume to use for caching new data. By default, this parameter is set to 4.
- dfs.cachereport.intervalMsec: The DataNode uses this as the amount of milliseconds between sending a full report of its cache state to the NameNode. By default, this parameter is set to 10000, which is 10 seconds.
- dfs.namenode.path.based.cache.block.map.allocation.percent: The percentage of the Java heap which we will allocate to the cached blocks map. The cached blocks map is a hash map which uses chained hashing. Smaller maps may be accessed more slowly if the number of cached blocks is large; larger maps will consume more memory. By default, this parameter is set to 0.25 percent.
OS Limits
If you get the error, Cannot start datanode because the configured max locked memory size... is more than the datanode's available RLIMIT_MEMLOCK ulimit, the operating system is imposing a lower limit on the amount of memory that you can lock than what you have configured. To fix this, adjust the DataNode ulimit -l value. Usually, this value is configured in /etc/security/limits.conf; but varies depending on your operating system and distribution.
You have correctly configured this value when you can run ulimit -l from the shell and get back either a higher value than what you have configured with dfs.datanode.max.locked.memory, or the string unlimited, indicating that there is no limit. It is typical for ulimit -l to output the memory lock limit in KB, but dfs.datanode.max.locked.memory must be specified in bytes. | https://docs.cloudera.com/documentation/enterprise/6/6.2/topics/cdh_ig_hdfs_caching.html | CC-MAIN-2020-45 | refinedweb | 1,703 | 57.67 |
This C program performs matrix multiplication. In matrix multiplication, we take two matrices of order m*n and p*q respectively to find a resultant matrix of the order m*q where n is equal to p . Time Complexity of this algorithm is O(n3).
Here is the source code of the C program to perform matrix multiplication. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
#include <stdio.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];("Matrices with entered orders can't be multiplied with each other.");
}
}
return 0;
}
$ gcc matrix_multiply.c -o matrix_multiply $ ./matrix_multiply Enter the number of rows and columns of first matrix 3 3 Enter the elements of first matrix 1 2 0 0 1 1 2 0 1 Enter the number of rows and columns of second matrix 3 3 Enter the elements of second matrix 1 1 2 2 1 1 1 2 1 Product of entered matrices:- 5 3 4 3 3 2 3 4 5
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Reference Books in C Programming, Data Structures and Algorithms. | http://www.sanfoundry.com/c-program-perform-matrix-multiplication/ | CC-MAIN-2017-26 | refinedweb | 211 | 53.41 |
Opened 12 years ago
Closed 8 years ago
#2443 enhancement closed fixed (fixed)
Trial tutorial
Description (last modified by )
Trial is great, it needs a documentation for Twisted users, probably in the form of a tutorial. It should cover all the common usecases:
- return Deferred from test
- setUp/tearDown
- testing a protocol without creating a client/server
- cleanups after tests (
addCleanup)
- using task.Clock to test callLater/LoopingCall
I don't know though where should be the frontier between 'Trial tutorial' and 'unit-tests tutorial'.
Attachments (3)
Change History (53)
comment:1 Changed 12 years ago by
comment:2 Changed 12 years ago by
Also, thanks for doing this. If ever you are in Australia, I will buy you a beer.
comment:3 Changed 12 years ago by
I just want to point out that work on this has started in the trial-tutorial-2443 branch in doc/core/howto/trial.xhtml
comment:4 Changed 12 years ago by
OK, this is far from being complete, but I'd need some feedback. Comments and/or direct changes from native english speakers would be great :).
comment:5 Changed 12 years ago by
Changed 12 years ago by
comment:6 Changed 12 years ago by
Hi,
Generally speaking I think this tutorial is a very good idea. I've made a few random fixes (spelling, adding import lines, small improvements) that you'll find attached.
In its current form I think the document still has some rough edges. For someone not used to unit tests, I think it's not clear from reading the code snippets where they have to be inserted. Also, the "testing scheduling" and "code coverage" parts probably need to be made more understandable.
comment:7 Changed 12 years ago by
comment:8 follow-up: 9 Changed 12 years ago by....
comment:9 Changed 12 years ago by
Replying to terrycojones:....
That's great, thanks a lot for going so far. Sorry for this week-end, I'll be mostly available on IRC from mondy to friday 9-21 UTC.
comment:10 Changed 12 years ago by
I'm attaching a zip of an svn diff showing where I'm up to. It's quite incomplete but there are many changes. It now builds successfully (to html) when you run admin/process-docs.
Terry
Changed 12 years ago by
Snapshot of fleshing out of the tutorial. Highly incomplete.
comment:11 Changed 12 years ago by
Hi therve
doc/core/howto/listings/trial/calculus/test/test_{base,remote}.py should go away, as they're the original code examples.
You've taken the 'called' variable out of test_remote_2.py and as a result it's now identical to test_remote_3.py. So test_remote_3.py could go away too. I think this is a good simplification at that point in the tutorial. Maybe you intend to put something back into test_remote_2.py though to confirm that the callback has fired?
Here's a reminder that it would be nice to have the example code for talking to the RemoteCalculationProtocol class.
I'd like to add an example that addresses what I would like to do with trial. I have a web2 server and I want to test it. The current tutorial gives me some ideas about how to do that (e.g., use a proto_helpers.StringTransport for the transport), but I still don't know how to write the tests. This may seem like a Twisted thing (I mean it may seem like I want it because I don't know enough about Twisted), but I don't see any harm in another example. For me the point of revising the tutorial (apart from helping others etc) is to learn how to test my http server, and I don't yet know exactly how to do that.
I'm around for the next 2 hours, then away for 4, and will probably be up most of the night. I'd be happy to push all the way through revising the tutorial ASAP.
comment:12 Changed 12 years ago by
That's not in review for now.
comment:13 follow-up: 14 Changed 11 years ago by
I've seen recent activity in the associated branch for this ticket. @therve: are you actively working on this?
comment:14 Changed 11 years ago by
I've seen recent activity in the associated branch for this ticket. @therve: are you actively working on this?
I had a bunch of motivation last week or so. I removed some big errors, and made some cleanups. I think this is in a correct shape, but any comment is welcome :). I don't plan on working on it soon if I don't get some feedback.
comment:15 Changed 11 years ago by
comment:16 follow-up: 18 Changed 11 years ago by
thijs, do you think you could have a look at the current branch? I'd like to revive it.
comment:17 Changed 11 years ago by
The example with timeout (client_3.py) is not quite correct IMHO: RemoteCalculationClient.timeOut collides with TimeoutMixin.timeOut. As a result timeout is set right only for the first message after connect. For the rest of messages timeout is None. The following test case (added to test_client_3.py ) verifies that (fails) for me:
def test_timeout_2(self): def cb(x): #self.proto.timeOut=60 return self.proto.add(9, 4) d = self._test('divide', 14, 3, 4) d.addCallback(cb) self.clock.advance(60) return self.assertFailure(d, ClientTimeoutError)
It passes if I uncomment the commented line.
IMHO the proper solution would be to make TimeoutMixin.timeOut private i.e. change it to TimeoutMixin._timeOut.
comment:18 Changed 11 years ago by
comment:19 Changed 10 years ago by
This is a very nice tutorial and would be good to get it reviewed and published (btw, glyph recently did some fixes to this doc in [26254]).
I hope that my feedback (from beginner's point of view) can help.
Ch. "Making the tests pass": link to test_base_2 follows right after link to base_2.py and readers can misunderstand which file does "with the import changed" refer to (at least i did). Suggest to add some text before the link to test_base_2 (to visually separate two links) and clarify text about importing. E.g.:
The file test_base_2.py is a copy of test_base_1, changed to import base_2.
Ch. "Twisted specific testing": links to basic twisted tutorials or documentation would be helpful, for those who came to the tutorial w/o knowledge of twisted.
Ch. "Creating and testing the server": the part about "it's just used to" in the following sentence is unclear to me - "Note that the address and port passed can have any value, it's just used to have a valid address".
So far all examples were clear.
As for remainder of examples (starting from test_client_1.py), they caused major headaches and constant going back and forth between different code listings to get an idea of what is happening. It would help a lot if some comments were added to the code. For example, this bit of code from client_2.py took a while to understand:
d, callID = self.results.pop(0) callID.cancel() d.callback(int(line))
Finally, "please give use your feedback!" can be improved by adding an email address or a link to where people can send feedback. a typo fix: "use" -> "us".
comment:20 Changed 10 years ago by
CaptSolo, thanks very much for your comments.
I discussed this briefly with JP on IRC; since this has been in process-limbo for way too long, I'm going to treat your feedback here as a review, address the comments you've made, and merge it after I've done so.
comment:21 Changed 10 years ago by
comment:22 Changed 10 years ago by
comment:23 Changed 10 years ago by
comment:24 Changed 10 years ago by
comment:25 Changed 10 years ago by
comment:26 Changed 10 years ago by
OK, the last comment I find difficult to address directly. I guess this still isn't quite ready to merge. I'm going to put it into review to solicit some feedback, both on what's there and what I plan to do about it.
The code which CaptSolo suggests is confusing also recommends the use of
twisted.test.proto_helpers in third-party code.
As a result, I've added some notes about test packages and private attributes to CompatibilityPolicy. I don't want to encourage anyone to import any code out of a test package, since arguably the whole point of putting it in a test package is to avoid anyone importing it yet. There's not much point in having a policy and making decisions about it if our official documentation just says "nudge nudge, wink wink, nobody cares about the policy anyway".
My recommended course of action here is to replace the "twisted specific testing" portions of the tutorial with a much shorter, simpler section that simply explains returning a
Deferred and does a few brief examples using "real" I/O, explaining dirty reactor detection. I think this would test some very naive code which calls
getPage and
deferLater; no client-server hookup, just "You got this deferred, now what?".
An important thing I would emphasize in this section is that you shouldn't (can't) run the reactor in your tests, as you would in example code, that trial does it for you if it needs to.
I realize that this is not the current accepted best practice, but for people just learning how to do TDD, I feel it would be very useful. In many cases when introducing Twisted users to unit testing, they are facing an API which returns a Deferred, and they hit a wall. In some cases this Deferred is coming from a client implementation for which there is no Twisted, or even Python, server implementation. There's a feeling of immense power, almost glee, for these users, when they realize that they can just barrel on through and issue a request in the middle of their unit tests without learning anything else. (As a data point, all of these users that I'm still in touch with have since moved on to using transport mocks.) I think this is an important intermediate step for someone learning TDD, especially learning in the context of a poorly-tested existing system (which, unfortunately, it seems like what everyone does). It's important to keep things moving along as you write your tests and not constantly get stuck on the need to develop more test infrastructure, which is exactly what trial allowing you to return a Deferred does.
However, since we all know that this approach is fraught with peril, I think this section should clearly explain dirty reactor errors and the risks associated with intermittent network- and timing-related failures, and explain how some good test objects can help you improve any tests you write to return real-IO deferreds.
There should then be two more tickets: one for "make
proto_helpers public", one for "expand TDD with twisted tutorial to include documentation of how to use proto_helpers and task.Clock".
The tutorial can end with a link to that ticket, which can be replaced with a link to the new tutorial when the other ticket is finished.
So, to summarize:
- Remove
proto_helpersand
task.Clockportions of this tutorial.
- Add a new, shorter segment that just explains testing code which already calls existing high-level Deferred-returning APIs in test methods (and cleaning up after them), rather than on testing APIs which themselves create and manage Deferreds.
- File a ticket to make
proto_helperspublic.
- File a separate ticket to document using verified fakes for more reliable testing. Put the removed portions of this tutorial into that "part 2" document. ("Advanced Test-Driven Development with Twisted"). This ticket will depend on the
proto_helpersticket.
Please let me know what you think.
comment:27 Changed 10 years ago by
Remove
tearDownClass from the description (ZOMG we should not document that), add
addCleanup.
comment:28 Changed 10 years ago by
Okay. I just found which is about 1/3 of what this needs to do, but doesn't make much sense. (It starts by describing the temporary directories that trial creates? In the index it's referred to as "tips" for writing tests, rather than a guide? It doesn't actually include any examples?)
This branch should also replace that document in the index.
comment:29 Changed 10 years ago by
comment:30 Changed 10 years ago by
Assuming washort's not going to do it, since it's been a few weeks.
comment:31 Changed 10 years ago by
Some minor suggestions:
- (and in fact subclasses) doesn't add much to the introduction, and since it may end up being inaccurate soon, I think it should just be removed.
- If you're shell reports something like uses you're where it should use your
- First trial tells you how many tests it detected.: trial doesn't actually do this anymore :( And the sample output in the document doesn't include this information.
- In the list following The tests can be run by trial in multiple ways:, please strongly encourage the use of FQPN over filesystem paths. The former is much more reliable than the latter.
- In
base_3.py, please make the
raise TypeErroruse
()and include some information about what went wrong (just so that it is a good example of how to generate errors instead of a bad one, even though that's not the central point here)
- After the paragraph ending with By setting up and using a fake transport, we can write 100% reliable tests., I would add some more text about how it is also important to test network failures, but mocking out the transport also allows us to do that deterministically and keep it separate from the success code-path tests.
- Of course you can't let your users with this doesn't make sense - a word is missing or wrong or something?
- We just factor operations, everything else should be obvious. is a pretty awkward sentence. Perhaps just omit it. Although the pipelining support is a little bit non-obvious, and not tested. ;) Ignore that if you want, though.
- This one of the tough parts of Twisted - let's not go out of our way to suggest that Twisted is hard, at least not in the cases where it's not!
Clockmakes this really easy, as the document goes on to explain. I think the hard thing this sentence might have been referring to is that lots of existing APIs don't parameterize the clock. We can probably skip that here, since this is a document about how to do it right, not about all the things that do it wrong. :) Perhaps it would still be worth mentioning that if you find an API that doesn't parameterize it and you want to test it, you should first parameterize the clock.
- will finish in the clock stack. - I would instead say something like 'will finish before
clock.advancereturns..
- Passing an
IReactorTimeto
__init__is a bit better form than setting attributes, right? If you agree, please adjust the example to do it that way.
- This remove the need of a tearDown - remove should be removes
- in
remote_2.py, the
log.errcall should pass a value for the message parameter.
- The inline code in the Handling logged errors section has bad indentation.
test_client_2.pydoesn't benefit from the use of
StringTransportWithDisconnection(as opposed to just
StringTransport) as far as I can tell. Am I right? Switch to
StringTransportif so.
- If
test_client_3.pyused
StringTransportand checked
StringTransport.disconnecting, it wouldn't need to use
StringTransportWithDisconnectionor clobber
connectionLostlike it does, which I think would be better. As a bonus, combined with the previous point,
StringTransportWithDisconnectionwould no longer be used at all.
Aside from all that pretty simple stuff, I think the only reason not to merge this as-is is the point glyph raised about
proto_helpers previously. I don't think overlap with testing.html, removing
Clock, etc needs to be considered here. This is a big lump of new, good documentation. It's not the only possible lump of documentation, but that doesn't matter. File more tickets to write more, or something.
So, about
proto_helpers. If
StringTransport is the only thing that's used by these docs, then I think the thing to do is move
StringTransport out of the test package into a real package. Of course, this will involve writing unit tests for it. Unfortunately, I think this should happen first so that we don't have docs pointing people at
twisted.test APIs.
Aside from this and the above (fairly trivial, though not exactly short) list of points, I don't think anything else should block this from being merged.
comment:32 Changed 10 years ago by
comment:33 Changed 9 years ago by
I'd like to say that the tutorial is looking decent, but one thing which was left out was how to name modules to take advantage of running trial like this:
trial <package_name>.test
I couldn't find anywhere that specified that the modules within the test directory also had to have the "test" prefix on them to be found; this seems to just be assumed. I thought the "test" prefix only applied to the test methods in a TestCase class, until someone on the ML pointed out otherwise.
That's my two cents. Thanks.
comment:34 Changed 8 years ago by
For people looking to start using Twisted or start working on Twisted (important!), this is one of the most crucial pieces of documentation we don't have. I want to resolve the outstanding issues, but it would appear that relies on an agreement regarding the state of twisted.test—more specifically, the proto_helpers module and what needs to be done to either (a) accept that it's already basically public or (b) take the steps necessary to make it officially so.
I am more than happy to do what Glyph's reply suggests and talk about writings tests using the reactor and returned deferred's (I'd probably just use as an example and explain the key points). Additionally, his experience seems to corroborate what I feel about proto_helpers: it's an oft-necessary step in one's maturity as a Twisted Tester. As such, I don't feel like this document will be complete until it can safely talk about transport mocks—wherever they may be imported from!
So, like, let's get on this; four years is long enough. *cracks whip*
comment:35 Changed 8 years ago by
comment:36 follow-up: 37 Changed 8 years ago by
comment:37 follow-up: 38 Changed 8 years ago by
I'm a complete Twisted beginner. I'm writing a project containing both clients and servers, which is getting to the point where I want some unit tests. I checked out this branch, hoping to get some hints on how to use Twisted.
Glad to see this branch is getting some attention from the core devs; I see parent is dated less than an hour ago :)
The tutorial would flow more nicely if the example code was located in the tutorial itself, rather than a separate file you have to download and open in a text editor. However, the separate file is nice if I want to actually run the code. Maybe we should have both?
The tutorial should make clear that test source files need to have names that start with "test_". I was using names that didn't follow this convention and trial <packagename> couldn't find the tests (it just immediately passed because it ran zero tests.)
In test_remote_1.py, the test_* methods have a body of the form "return self._test(...)". This is confusing for two reasons:
(1) There is no explicit return from self._test. Of course, this means self._test returns None when the end of the body is reached. But using the return value of a function with no return statement gives programmers coming from strongly typed languages a peculiar gut-wrenching negative reaction.
(2) In general, unit tests should not return values; *even if* substantial changes were made to the tutorial code and self._test returned some meaningful value, using a return statement to pass this value on to the testing framework from test_* is pointless and confusing. AFAIK all the testing frameworks I've worked with (JUnit, PyUnit, unittest2, Trial) just throw away the return values from test_ methods.
You could even add something to this effect to the tutorial: "For most well-written tests (including all of the tests in this tutorial), assertions and exceptions are the sole communications between the testing framework and the test_ methods. Trial will ignore any value returned from a test_ method."
comment:38 Changed 8 years ago by
You could even add something to this effect to the tutorial: "For most well-written tests (including all of the tests in this tutorial), assertions and exceptions are the sole communications between the testing framework and the test_ methods. Trial will ignore any value returned from a test_ method."
I just realized this isn't true, if you return a Deferred :)
I would edit this incorrect observation out of my above comment, but apparently comment editing is not a feature supported by Trac...
comment:39 Changed 8 years ago by
binjured asked for a pronouncement on this, so:
proto_helpers is public (unfortunately). Other projects are using it. We support them. It's the only way to do what it does.
There should be a ticket to move it to a new namespace where it can be more widely publicized, but it's public for now. Documentation should stress that it the only module in this namespace which is public.
comment:40 Changed 8 years ago by
Based on skimming the ticket, my understanding of its current state:
- In order for this ticket to be put in final review, I think we just need to address comment #31 (items 11-16) and comment #33.
- Once merged, we should open ticket to move proto_helpers out of twisted.trial, and open ticket to add more comments and docstrings to the sample code in the howto (the latter is a good idea but not a blocker for this ticket).
comment:41 Changed 8 years ago by
Oh, and of course pre-review all the code samples and tests have to be run and ensured to work :)
Changed 8 years ago by
comment:42 Changed 8 years ago by
Issues fixed by the attached patch::
#31: 12-16 (11 is ambiguous to me; where are we setting attributes that we should pass IReactorTime?); #33; #39.
Tests are confirmed to work *as expected* (e.g. the first module is meant to fail), except for the failing test
test_remote_3.test_invalidParameters where
flushLoggedErrors() isn't doing its job for reasons I am unfamiliar with.
Patch created against
branches/trial-tutorial-2443-3. Cheers!
comment:43 Changed 8 years ago by
comment:44 Changed 8 years ago by
comment:45 Changed 8 years ago by
I talked with itamar about the Clock issue and we seem to agree that it's unintuitive to override
callLater() as it's being done and ultimately we should probably just remove
TimeoutMixin from the protocol so we can stop doing that. We're not sure that doing so necessitates holding up this particular issue, though. Thoughts?
comment:46 Changed 8 years ago by
(In [31493]) Some minor corrections and additions
- we have more tests now (in other words, this branch was two thousand tests old)
- tearDown is not run if setUp raises an exception
- but cleanup functions (functions passed to addCleanup) are
- Deferreds returned from cleanup functions are handled correctly
comment:47 Changed 8 years ago by
Sorry for the bother, but how do I remove myself from cc? I thought I did but I still receive notifications. Thank you ;)
comment:48 Changed 8 years ago by
comment:49 Changed 8 years ago by
I spoke to antoine out of band, and apologized for the fact that our issue tracker will not sending him email. We should take this as additional motivation to resolve this ticket quickly so he does not get too many more unwanted emails. :)
To that end:
- I made a couple tweaks, not the ones linked above, those are bogus and I reverted them. Instead, r31496, r31497, and r31498. Some for content, some for Sphinx. Please look them over, but I think they're fine.
- I think the
TimeoutMixinstuff is fine. When
TimeoutMixinsupports a better way to do this, we can document that instead.
This document looks good to me in its current state. Please add a .doc fragment and merge the branch! Also don't forget to file the tickets requested in earlier comments. Thank you!
I think the tutorial should be "Test-driven development with Twisted", not "How to use Trial". We don't want explain all the cool stuff that Trial can do, we want to show all the cool things that you can do do with Trial.
Although it's a little redundant, I reckon it's worth explaining how to do unit tests and the basics of test-driven development. Lots of people come to Twisted with only a little knowledge of Python, and the goal of this document should be to get them writing tests as quickly as possible. | https://twistedmatrix.com/trac/ticket/2443 | CC-MAIN-2019-09 | refinedweb | 4,265 | 71.04 |
I started web development using Java, basically during my studies at the university. When working on my bachelor degree thesis I needed a web server back-end system (to my mobile J2ME client); I decided to do it "right". Spring (especially Spring.Web) for the application server part and Hibernate for the object relational mapping. Although having quite a tough time getting up that initial learning curve, the result payed out so well: everything nicely decoupled and testable. I loved it. Then, when starting to work professionally as a .Net developer things got more painful...After my studies (parallel to continuing with the MSc) I started to work professionally as a .Net developer, getting in touch with Asp.net (WebForms). And that just felt so strange. "Postback", "ViewState",...it was like imposing the WinForms technology on top of the web. Where was the usual request/response pattern?? Testability?? Sure, you can, but you don't want to fight with all the necessary setup you need to deal with when testing an ASP.net WebForms Page. The only way is to ensure that you keep that logic at a minimum possible and to rather defer it to some business layer class which is completely web-agnostic and which then can definitely be tested. And indeed, this is what our internal framework/class-library helped us to do.
Now we decided to change that, seriously evaluating ASP.net MVC as our server-side technology. And that feels so much like returning home :). And I'm really satisfied what I've seen so far from Microsoft regarding MVC. They really seem to have gotten it right this time. Everything is clearly separated, abstracted, exchangeable and mainly, testable!
Consider this really dummy ASP.net MVC controller:
public class AccountController : Controllerand the corresponding (if also naive) test case:
{
...
[HttpPost]
public JsonResult Filter(Account account)
{
return Json(new List<Account>()
{
new Account()
});
}
...
}
[TestMethod]Now, isn't this simple??
public void TestFilter_FilterJuriStrumpflohner_ShouldReturnAccountInstance()
{
//Arrange
Account filterAccount = new Account()
{
Lastname = "Strumpflohner"
};
//Act
JsonResult result = new AccountController().Filter(filterAccount);
IList<Account> filterResult = result.Data as IList<Account>;
//Assert
Assert.AreEqual(1, filterResult.Count, "There should be only one result");
} | https://juristr.com/blog/2011/08/why-did-it-have-to-be-so-complicated/ | CC-MAIN-2018-05 | refinedweb | 359 | 52.26 |
PROLOGThis manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.
NAMEferror — test error indicator on a stream
SYNOPSIS
#include <stdio.h>
int ferror(FILE *stream);
DESCRIPTIONThe functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1‐2008 defers to the ISO C standard.
The ferror() function shall test the error indicator for the stream pointed to by stream.
The ferror() function shall not change the setting of errno if stream is valid.
RETURN VALUEThe ferror() function shall return non-zero if and only if the error indicator is set for stream.
ERRORSNo errors are defined.
The following sections are informative.
EXAMPLESNone.
APPLICATION USAGENone.
RATIONALENone.
FUTURE DIRECTIONSNone.
SEE ALSOclearerr(), feof(), fopen()
The Base Definitions volume of POSIX.1‐2008, <stdio . | https://jlk.fjfi.cvut.cz/arch/manpages/man/ferror.3p.en | CC-MAIN-2020-34 | refinedweb | 170 | 50.33 |
What... I dont understand... Do you have any coding issues?
Type: Posts; User: Niels van Ee
What... I dont understand... Do you have any coding issues?
The for loop is fine. What is inside wont get you further. Youll have to figure out how to get the power of your base, which is hard. If you keep trying youll get it sometime.
Please post code where your issue is. How can we help you if we dont have information? Please send the code you have problems with so we can help you.
But if i make a pattern (what i just read about) then it doesnt work. So that leaves that option (it doesnt work because we need the number we are trying to find but we havent found it yet)
which...
btw this is not even homework... this is for timing in a program im making.
Since I dont know about the Pattern class (and no good tutorials on it imo) i would need to go to that line and go to the second comma and start reading untill i find another comma? how would you set...
My question is:
Is it in any way, possible to go into a file and then when it comes to a line you specified it takes the input you want?
Like this:
192,160,2275,1,0,
|
I...
Well i dont know. Maybe a for loop?
For (blablabla; if blala;)
You know what i mean
Thanks i got it to work! it was that i used the variable 2 times which made it go on forever (the for loop) until the array stops.
Thanks :)
So I have been busy at some projects lately. One of them having this project
ill put up the full code and the part i have problems with:
package relax;
//importeverything
import...
Please put this in the right forum...
Thanks.
The forum "Java Networking" will try to help you ;).
If you put it over there and make an effort in posting you will get help.
Also read this.
Im...
I'm kind of a coding newb but i managed to make this:
import java.util.Scanner;
public class ReactionGame {
public static void main(String[] args) {
int Time = 0;
String s = null;
So i'm trying to help and not give the answer!
Basicly im just giving tips!
also just try to get the code you need from internet! NOT FROM ME ;P
47,92
Take the first number (4)
make that...
System.out.println("1")
System.out.println("2")
Etc.
This easy it is...
But im going to make a harder one at home.
Java is multifunctional. Scratch is a good starter but with more complicated stuff, java is the place to be
Java is "the most known language" in coding and when youre stuck youll find the most...
Tommorow there will be a link for the download.. going to sleep now! have a good day sir :)
Ehh I honestly dont know how to get a method... i just make alot of simple games... If you could explain me how I use a "Method" because I dont know.
EDIT: I got the Delay(int) from the internet...
So i was practesing with Scanner and delay...
This happened and i dont know whats wrong?
It has something to do with delay but i cant figure it out?
import java.util.Scanner;
public class...
I can give you a .jar if you want... I dont think it will work, but you might give it a shot. Just reply on this thread and I will make one!
Well what is the main problem with your question? I dont really understand. If you tell me what subjects you need help with I will help you.
System.out.println("need more info....)
;)
Bye
Sorry it's kinda hard and i don't want to rewrite the script etc etc. Good luck with the project! but now you know how to do it I suppose. Hope you can figure it out.
make a new boolean called "Again".(=true)
Then make a while before the program starts. ( While (Again = True)
after the program finishes you ask the scanner to do Y/N
Then when they say Yes make...
Well this is my first forum i will ever join...
I hope to have fun with all of you guys!
I'm a home-coder. Sorta like a hobby coder, I usually just code random calculating stuff. Such as my... | http://www.javaprogrammingforums.com/search.php?s=2a38541279126e032cf83f151942d9b7&searchid=1460995 | CC-MAIN-2015-14 | refinedweb | 743 | 94.76 |
#include <dense.h>
The class LinBox::Dense builds on this base.
Currently, only dense vectors are supported when doing matrix-vector applies.
Reimplemented in DenseMatrix, DenseMatrix< Field >, and DenseMatrix< Domain >.
The raw iterator is a method for accessing all entries in the matrix in some unspecified order. This can be used, e.g. to reduce all matrix entries modulo a prime before passing the matrix into an algorithm.
[inline]
Constructor.
Constructor from a matrix stream
Get a pointer on the storage of the elements
Get the number of rows in the matrix
Get the number of columns in the matrix
Element()
Resize the matrix to the given dimensions The state of the matrix's entries after a call to this method is undefined
Read the matrix from an input stream
Write the matrix to an output stream
Set the entry at the (i, j) position to a_ij.
Get a writeable reference to the entry in the (i, j) position.
Get a read-only reference to the entry in the (i, j) position.
Copy the (i, j) entry into x, and return a reference to x. This form is more in the Linbox style and is provided for interface compatibility with other parts of the library
Retrieve a reference to a row. Since rows may also be indexed, this allows A[i][j] notation to be used.
Compute column density
[protected] | http://www.linalg.org/linbox-html/classLinBox_1_1DenseMatrixBase.html | crawl-001 | refinedweb | 230 | 54.12 |
Before I even get started, a quick side note. I initially assumed I should write LINQ [all caps] since it is an acronym (from what I recall), but I decided to go with the .NET Framework namespace capitalization instead. I should have learned my lesson with AJAX or Ajax, or however you want to write it. ;)
Ok, back to the point. I've seen a couple of posts in the Infragistics forums lately asking about checkbox columns. You see, even though we put some snazzy selection feature into our grids, many end users have had the checkbox selection paradigm pounded into their heads for years. They're used to it, they like it, and they demand it from you the developer. The question becomes - is there an easy way to associate checkbox state with row selection?
Rather than have the checkbox toggle the grid's built-in selection mechanism, I think it makes more sense to treat the checked rows as you would have treated selected rows. The only complexity is getting a collection of checked rows. Now I use the term complexity loosely here, because getting the checked rows is really just a single for loop away. But something just feels clumsy about using a for loop to search through all the rows. What seems like a natural fit for me is Linq. You can use a Linq query to get a collection of rows from the grid based on their checked state. Here's an example of a method which does just that.
protected RowsCollection GetSelectedRows(UltraWebGrid grid){ var rows = from UltraGridRow row in grid.Rows where row.Cells.FromKey("check").Value!=null && ((bool)row.Cells.FromKey("check").Value)==true select row; return rows;}
On the outside this is a simple method that returns a RowsCollection. However, notice that on the inside there are some different ingredients. First of all, there's no semi-colons! Linq expressions can be broken up in to multiple lines, and do not require semi-colons. Aside from the return parameter (var rows) the expression has 3 parts just like a SQL query. In the first piece, we're defining the IEnumerable that we'll be iterating over, and assigning 'row' as the loop variable. Then we set up the 'where', which will act to filter out our results (just like in a SQL query), and we finally define the select statement which will decide what gets returned. In the example above we're simply returning the rows collection that is being created. But we could just as easily return a collection of objects, or even us anonymous types here to construct an object with specific properties we want. As an example:
var rows = from UltraGridRow row in grid.Rows where row.Cells.FromKey("check").Value!=null && ((bool)row.Cells.FromKey("check").Value)==true select new {ID=(int)row.Cell[0].Value, Value=row.Cell[1].Text}; return rows;
In the above example, rather than returning a rows collection, we're returning a collection of objects, where the object has 2 properties - ID and Value. Pretty powerful, and the syntax is short and sweet.
I used the checkbox selection problem as an example of where you can use Linq, but that certainly isn't the only place. I encourage you to try it out yourself. There are some great resources out there, including blog posts from Scott Gu, and plenty of documentation on MSDN. If you haven't been introduced to Linq yet, it's time you take the plunge. You'll be pleasantly surprised.
When. | http://weblogs.asp.net/tonylombardo/archive/2008/02.aspx | CC-MAIN-2014-15 | refinedweb | 593 | 65.01 |
I have two arrays, a1 and a2. Assume len(a2) >> len(a1), and that a1 is a subset of a2.
I would like a quick way to return the a2 indices of ...
len(a2) >> len(a1)
I have a numpy array with positive and negative values in.
a = array([1,1,-1,-2,-3,4,5])
This is a really simple question, but I didnt find the answer.
How to call an element in an numpy array?
import numpy as np
arr = np.array([[1,2,3,4,5],[6,7,8,9,10]])
print arr(1,1)
Let say that we have an array
a = np.array([10,30,50, 20, 10, 90, 0, 25])
if a[x] > 80 then perform funcA on a[x]
if 40 < ...
Is there an easy way to take the dot product of one element of an array with every other?
So given:
array([[1, 2, 3],
[4, 5, 6],
...
Hey.. I have run into a bit of a problem with my python code.. I have a set of values each for frequency and power-spectrum. I need to plot frequency v/s ...
I have a 2 dimensional NumPy array. I know how to get the maximum values over axes:
>>> a = array([[1,2,3],[4,3,1]])
>>> amax(a,axis=0)
array([4, 3, 3])
Out of curiosity, is there a specific numpy function to do the following (which would supposedly be faster):
a = np.array((0,2,4))
b = np.zeros(len(a) - 1)
for i in range(len(b)):
b[i] ...
I'm experiencing a problem with array indexing. Suppose you have an array a and another array b you want to use to use as index for a in order to assign ...
I have a numpy array and I want to force every element that is less than zero to be zero and every element above 255 will be forced down to 255.
eg. ...
I have a numpy array containing:
[1, 2, 3]
[1, 2, 3, 1]
I want to get the neighbors of the certain element in the numpy array. Lets consider following example
a = numpy.array([0,1,2,3,4,5,6,7,8,9]) | http://www.java2s.com/Questions_And_Answers/Python-Data-Type/numpy/element.htm | CC-MAIN-2013-20 | refinedweb | 368 | 75 |
HashSet class is a concrete implementation of Set interface. It creates a collection that uses a hash table for storage. Hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code. The hash code is then used as an index at which the data associated with the key is stored. The transformation of key into its hash code is performed automatically. You never see the hash code itself. The advantage of hashing is that it allows the execution time of basic operation, such as add(), contains(), remove(), and size() to remain constant even for large sets.
HashSet is not synchronized. If more than one thread wants to access it at the same time then it must be synchronized externally.
This code shows the use of HashSet. This will identify the number of duplicate words in a String. The String is passed as command line arguments.
Add() method of the HashSet add the object into the storage if it is not already present.
import java.util.*;
public class FindDups {
public static void main(String[] args) {
Set s = new HashSet();
for(int i=0; i<args.length;i++){
if(!s.add(args[i]))
System.out.println("Duplicate detected : " + args[i]);
}
System.out.println(s.size() + " distinct words detected : " + s );
}
}
Run the program: C:\> java FindDups i came i came i conquered
Output Screen :
Duplicate detected: i
Duplicate detected: i
4 distinct words detected : [came,saw,conquered,i] | http://www.java-tips.org/java-se-tips/java.util/how-to-use-hashset-2.html | crawl-001 | refinedweb | 253 | 57.67 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.