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
Opened 5 months ago Closed 7 days ago #29244 closed Cleanup/optimization (fixed) Paginator.count() may incorrectly silence AttributeError and TypeError Description (last modified by ) With this code: from django.contrib.postgres.search import SearchQuery, Value, Func from django.core.paginator import Paginator from django.db.models import F, TextField, DateTimeField, Models from django.utils import timezone class Entry(Model): text = TextField() published_on = DateTimeField(default=timezone.now()) class Headline(Func): function = 'ts_headline' output_field = TextField() def __init__(self, text, query, options=None): extra = {} expressions = [text, query] if options: opt_str = '' for key, value in options.items(): opt_str += f'{key}={value},' expressions.append(Value(opt_str[:-1])) super().__init__(*expressions, **extra) entries = Entry.objects.annotate( text_highlighted=Headline( F('text'), SearchQuery('house'), options={'HighlightAll': False}, ) ).order_by('-published_on') paginator = Paginator(entries, 20) # evaluates the queryset paginator.page(1) Passing options by dict to the Func subclass causes the count step for pagination to fail silently in paginator.py line 85 (1) which is in turn caused by a silenced TypeError during the hash in expressions.py line 372 (2). Then, because of the fallback to len on paginator.py line 90 (3) the entire queryset is evaluated instead of evaluating just the specified page (and in this specific case, calling ts_headline on every row instead of just the first page). The correct way of passing options using **options instead of options=None fixes this case, but the silent error and fallback to calling len on a queryset causes an unexpected expensive query when using pagination. (1) (2) (3) Change History (7) comment:1 Changed 5 months ago by comment:2 Changed 5 months ago by comment:3 Changed 5 months ago by Thanks for the tip. I've updated the links. For my use case, it would make sense to not call len on a queryset in paginator.py and instead surface the exception. The len fallback could be used only if the thing passed in is not a queryset. comment:4 Changed 5 months ago by It looks like the best solution would be to remove the try/except in Paginator.count(). AttributeError can be removed with hasattr(self.object_list, 'count') and TypeError with some checking that count is a method without any arguments. Perhaps a new function in django/utils/inspect.py would help with that. Do you have a proposal of how to address this? By the way, if you press the "y" key when viewing a GitHub page, you can get a link that includes a commit hash. Without that, the links can quickly go stale as line numbers change.
https://code.djangoproject.com/ticket/29244
CC-MAIN-2018-34
refinedweb
428
50.33
ubsan: NS _FOR _CSS _SIDES creates invalid Side values RESOLVED FIXED in Firefox 51 Status () People (Reporter: jseward, Assigned: mats) Tracking Firefox Tracking Flags (firefox51 fixed) Details Attachments (4 attachments, 5 obsolete attachments) Running an Ubsan'd build of the browser (-fsanitize=undefined) produces a large number of warnings like this: layout/style/nsCSSParser.cpp:11111:60: runtime error: load of value 4, which is not a valid value for type 'Side' layout/style/nsCSSParser.cpp:13432:60: runtime error: load of value 4, which is not a valid value for type 'Side' layout/style/nsCSSParser.cpp:11268:58: runtime error: load of value 4, which is not a valid value for type 'Side' layout/style/nsCSSParser.cpp:11291:58: runtime error: load of value 4, which is not a valid value for type 'Side' layout/style/nsCSSParser.cpp:11089:62: runtime error: load of value 4, which is not a valid value for type 'Side' layout/style/nsCSSParser.cpp:11073:60: runtime error: load of value 4, which is not a valid value for type 'Side' layout/style/nsCSSParser.cpp:13762:60: runtime error: load of value 4, which is not a valid value for type 'Side' This happens because of the NS_FOR_CSS_SIDES macro, which is used thusly: NS_FOR_CSS_SIDES (index) { AppendValue(aPropIDs[index], result.*(nsCSSRect::sides[index])); } That expands to for (mozilla::css::Side index = NS_SIDE_TOP; index <= NS_SIDE_LEFT; index++) { AppendValue(aPropIDs[index], result.*(nsCSSRect::sides[index])); } where static inline css::Side operator++(css::Side& side, int) { NS_PRECONDITION(side >= NS_SIDE_TOP && side <= NS_SIDE_LEFT, "Out of range side"); side = css::Side(side + 1); return side; } // Side constants for use in various places. enum Side { eSideTop, eSideRight, eSideBottom, eSideLeft }; #define NS_SIDE_TOP mozilla::eSideTop // 0 #define NS_SIDE_RIGHT mozilla::eSideRight #define NS_SIDE_BOTTOM mozilla::eSideBottom #define NS_SIDE_LEFT mozilla::eSideLeft // 3 So the problem is that, in the last iteration of the loop, with index == Side(mozilla::eSideLeft), we construct Side(4), and then exit the loop because the test Side(4) <= Side(3) fails. But the problem is that 4 isn't a valid value for "enum Side" and so the behaviour is indeed undefined. Right now I can't think of a sane way to fix this. One solution that does keep Ubsan happy is to iterate using an integer value, and only form the Side value inside the loop body: #define NS_FOR_CSS_SIDES(var_) \ for (int var_##_int = (int)NS_SIDE_TOP; \ var_##_int <= (int)NS_SIDE_LEFT; var_##_int++) { \ mozilla::css::Side var_ = mozilla::css::Side(var_##_int); The problem is that this gives an extra { that needs to be gotten rid of somehow. For experimentation I manually removed the { after all circa 70 uses of this macro just to see if the fix would work. This is ugly, makes the macro inconsistent with all the other NS_FOR_* macros, and causes the source files to have unbalanced { and }s, which confuses and slows down emacs greatly. So I'm not proposing this as a landable fix. That said, I would like to get this fixed somehow. For a startup and quit of the browser, this far and away the most commonly reported UBSan complaint. Maybe we could use a helper class that implicitly converts to Side? #define NS_FOR_CSS_SIDES(var_) for (mozilla::css::SideLoopHelper var_; var_.i <= NS_SIDE_LEFT; ++var_.i) and add in mozilla::css:: struct SideLoopHelper { SideLoopHelper() : i(NS_SIDE_TOP) {} operator Side() { MOZ_ASSERT(i >= NS_SIDE_TOP && i <= NS_SIDE_LEFT, "Out of range side"); return Side(i); } explicit operator Corner() { return Corner(Side(i)); } int32_t i; }; It's a bit ugly, but we don't need to change any other code. (In reply to Mats Palmgren (:mats) from comment #3) > Maybe we could use a helper class that implicitly converts to Side? Ah, nice suggestion. Here's a patch that does that, and it does indeed keep Ubsan happy. Compared to your suggestion: * the new class is called SideIterHelper * I added a start-value for the constructor, so as to avoid the asymmetry that the end value is visible in the #define but the start value isn't. * I added some comments. Attachment #8786670 - Attachment is obsolete: true Comment on attachment 8787140 [details] [diff] [review] bug1299379-2.cset >+ SideIterHelper(Side first_value) : i(first_value) {} Nit: camelCase and snake_case looks a bit odd on the same line. I suggest aFirstValue instead. Otherwise, it looks fine to me. Attachment #8787140 - Flags: feedback?(mats) → feedback+ (In reply to Mats Palmgren (:mats) from comment #5) Thanks! Ok, I'll fix the nit and get it tested. Would you be so kind as to upgrade the f+ to r+ so I can land it? Hmm, the patch doesn't build on Windows, due to errors like this: z:/task_1473089207/build/src/layout/generic/nsFrame.cpp(1301): error C2593: 'operator +' is ambiguous z:/task_1473089207/build/src/layout/generic/nsFrame.cpp(1301): error C2088: '+': illegal for struct z:/task_1473089207/build/src/layout/generic/nsFrame.cpp(1302): error C2593: 'operator +' is ambiguous z:/task_1473089207/build/src/layout/generic/nsFrame.cpp(1302): error C2088: '+': illegal for struct z:/task_1473089207/build/src/layout/generic/nsFrame.cpp(1304): error C2593: 'operator %' is ambiguous My C++-fu isn't good enough to know why. I presume that the 'operator +' it is referring to is to do with the "++var_.i" in the proposed new NS_FOR_CSS_SIDES macro, but apart from that I'm just guessing. Any suggestions? Flags: needinfo?(mats) It looks like the errors comes from these macros, which use + and % on "side_" and an integer value. I think adding an explicit Side(side_) should fix it. If there are other sites that does arithmetic like this then maybe we should try adding operator+(int32_t) etc to SideIterHelper instead... Flags: needinfo?(mats) What about simply adding a |eSideLimit| value to the Side enum? There are heaps of other enums in the codebase that have a limit value for this purpose. We have many switch-statements for these values so that would give a warning there instead. This seems to work fine locally for me with clang 3.8.0 on Linux. I pushed it to Try to see if works elsewhere: If it does, then we should probably just replace all NS_FOR_CSS_SIDES with this for-loop since it would make the code clearer. Comment on attachment 8788514 [details] [diff] [review] Alternative fix using builtin iterator Does it compile to the same thing with gcc, clang, and MSVC? (In reply to Mats Palmgren (:mats) from comment #11) > Created attachment 8788514 [details] [diff] [review] > Alternative fix using builtin iterator I would prefer this if it works. The previous scheme of having a SideIterHelper struct is proving difficult to get compiling with MSVC. (In reply to Mats Palmgren (:mats) from comment #11) > Created attachment 8788514 [details] [diff] [review] > Alternative fix using builtin iterator This keeps Ubsan happy, so +1 from my point of view. Attachment #8788514 - Attachment is obsolete: true Attachment #8788830 - Flags: review?(n.nethercote) (In reply to David Baron :dbaron: ⌚️UTC-7 from comment #12) > Does it compile to the same thing with gcc, clang, and MSVC?). Or are you worried about compatibility issues between compilers for range-based for-loops? Or something else? Assignee: nobody → mats Flags: needinfo?(dbaron) (In reply to Mats Palmgren (:mats) from comment #17) >). Yes, that's what I was worried about. And given that response I don't think we should land this patch. Flags: needinfo?(dbaron) Comment on attachment 8788830 [details] [diff] [review] Use builtin array iterator instead of NS_FOR_CSS_SIDES macro OK, I guess this is too slow then. FTR, since the whole kAllSides fits in one cache line I think we could make it one slow read at the most. From a static address so there is some room for ILP there. Attachment #8788830 - Attachment is obsolete: true Julian, does this fix the ubsan warning? (In reply to Mats Palmgren (:mats) from comment #20) > Created attachment 8788993 [details] [diff] [review] > Julian, does this fix the ubsan warning? Yes. It does. We have a dozen or so token pasting macros in various places so I think we should have a blessed one somewhere in mfbt instead. The assembler code with/without the patch is identical in an Opt build using clang 3.8.0 on Linux. Attachment #8788993 - Attachment is obsolete: true Comment on attachment 8789421 [details] [diff] [review] fix, v3 Review of attachment 8789421 [details] [diff] [review]: ----------------------------------------------------------------- I'm neither a layout/ nor an mfbt/ peer, and I already r+'d one patch in this bug that dbaron subsequently r-'d. So I will defer review here, sorry. Having said that, some comments: - Yikes! Sad that it requires something this ugly :( Esp. the MOZ_CONCAT(var_,__LINE__) name. - Having to declare a variable outside the loop is unfortunate. I guess it's because you can't declare two variables of different types within a loop header? - It'd be nice to remove some of the other pasting macros at the same time, or as a follow-up. (In reply to Nicholas Nethercote [:njn] from comment #23) > - Yikes! Sad that it requires something this ugly :( Esp. the > MOZ_CONCAT(var_,__LINE__) name. Yeah, it's ugly for sure. > - Having to declare a variable outside the loop is unfortunate. I guess it's > because you can't declare two variables of different types within a loop > header? Yes. > - It'd be nice to remove some of the other pasting macros at the same time, > or as a follow-up. I'll file a follow-up bug(s). Comment on attachment 8789421 [details] [diff] [review] fix, v3 Review of attachment 8789421 [details] [diff] [review]: ----------------------------------------------------------------- dbaron should probably review this, since he's already expressed some strong opinions about options here -- and this is a (necessarily) ugly enough hack that I'd rather he make the call, in his role as module owner. :) And I think this needs an MFBT reviewer (Waldo, maybe?) for the MacroArgs change. (I'll also admit to being unfamiliar-enough with macro arcana that I don't entirely understand the subtlety behind & need for MOZ_CONCAT/MOZ_CONCAT2, too.) ::: layout/style/nsStyleConsts.h @@ +19,5 @@ > typedef mozilla::Side Side; > } // namespace css > > +#define NS_FOR_CSS_SIDES(var_) \ > + int32_t MOZ_CONCAT(var_,__LINE__) = NS_SIDE_TOP; \ This #define needs some documentation to explain what it's doing, since it seems pretty arcane. Both at a high level (e.g. "creates a for loop that walks over the four mozilla::css::Side values"), and also explaining the idea behind & reason for the somewhat-arcane implementation here. @@ +22,5 @@ > +#define NS_FOR_CSS_SIDES(var_) \ > + int32_t MOZ_CONCAT(var_,__LINE__) = NS_SIDE_TOP; \ > + for (mozilla::css::Side var_; \ > + MOZ_CONCAT(var_,__LINE__) <= NS_SIDE_LEFT && \ > + ((var_ = mozilla::css::Side(MOZ_CONCAT(var_,__LINE__))), true); \ What is the ", true" doing here? I'm not clear on where/how that comes into play in this expression. Attachment #8789421 - Flags: review?(dholbert) → feedback+ I figured we should have a common definition of this macro somewhere in mfbt so we don't have to define it over and over again when needed. Attachment #8789421 - Attachment is obsolete: true Attachment #8790019 - Flags: review?(jwalden+bmo) (In reply to Daniel Holbert [:dholbert] from comment #25) > dbaron should probably review this, since he's already expressed some strong > opinions about options here -- and this is a (necessarily) ugly enough hack > that I'd rather he make the call, in his role as module owner. :) "David Baron :dbaron: ⌚️UTC-7 (busy September 14-25) <dbaron@dbaron.org> is not currently accepting 'review' requests." This uses an int32_t loop variable to avoid the UBSan warning. The value of that is then assigned to "var_" in the 2nd term of the && expr, hence the assignment only occurs for the valid Side values. The ",true" part is a comma expression to make the 2nd term not affect the loop condition, so the 2nd term effectively acts as an assignment inside the loop. The assembler code with/without the patch is identical in an Opt build using clang 3.8.0 on Linux. Attachment #8790022 - Flags: review?(dholbert) Comment on attachment 8790022 [details] [diff] [review] fix Review of attachment 8790022 [details] [diff] [review]: ----------------------------------------------------------------- OK, r=me I suppose -- though remember to switch the commit message back to "r=dholbert" (not dbaron) before landing. :) ::: layout/style/nsStyleConsts.h @@ +20,5 @@ > } // namespace css > > +// Creates a for loop that walks over the four mozilla::css::Side values. > +// We use an int32_t help variable to avoid causing an UBSan warning > +// (see bug 1299379). Thanks for adding this comment! Though, hmm, this is perhaps still a bit vague about what the problem is & why we're solving it this way. Maybe replace the last 2 lines here with this slightly-clearer (IMO) version (or something like it), which leaves fewer questions in the reader's mind: // We use an int32_t helper variable (instead of a Side) for our loop counter, // to avoid triggering undefined behavior just before we exit the loop (at // which point the counter is incremented beyond the largest valid Side value). Attachment #8790022 - Flags: review?(dholbert) → review+ (In reply to Mats Palmgren (:mats) from comment #28) > The assembler code with/without the patch is identical in an Opt > build using clang 3.8.0 on Linux. (Thank you for verifying that! That's I think the prime thing that dbaron was concerned with here -- the assembler code staying at the same level of complexity/expensiveness. So, this verification makes me feel more comfortable r+'ing this without his input on this final formulation of the fix.) Comment on attachment 8790019 [details] [diff] [review] Add MOZ_CONCAT macro in mfbt Review of attachment 8790019 [details] [diff] [review]: ----------------------------------------------------------------- ::: mfbt/MacroArgs.h @@ +12,5 @@ > #define mozilla_MacroArgs_h > > +// Concatenates pre-processor tokens in a way that can be used with __LINE__. > +#define MOZ_CONCAT2(x,y) x##y > +#define MOZ_CONCAT(x,y) MOZ_CONCAT2(x,y) Space after all the commas, spaces around ##. I'm not wholly convinced this is the best place for this, at least not with line 8's description, but good enough for now. Attachment #8790019 - Flags: review?(jwalden+bmo) → review+ Prior r+ aside, and to return to this bug's original issue. Given some of the shadowing/bracing horrors discussed in comments, requiring tiptoeing around at length in proposed solutions, why are we still using a macro here? C++11 added lambda expressions. We have full compiler support for them everywhere. js/src uses a boatload of them, especially in the frontend. They exist, they're reliable, you can use them. This seems like a case tailor-made for a higher-order function: template<typename ForCssSide> static inline void ForAllCssSides(ForCssSide forSide) { // Or do int+casting to enumerate the sides. It doesn't matter. static constexpr allSides[] = { eSideTop, eSideRight, eSideBottom, eSideLeft }; for (css::Side side : allSides) forSide(side); } An example like this: NS_FOR_CSS_SIDES(side) { // Clamp negative calc() to 0. aPadding.Side(side) = std::max(mPadding.ToLength(side), 0); } would simply convert to this: ForAllCssSides([&aPadding, this](css::Side side) { // Clamp negative calc() to 0. aPadding.Side(side) = std::Max(mPadding.ToLength(side), 0); }); Skimming uses, there are a few uses this wouldn't support -- those that really want to early-exit. It *appears* all of those are really asking, "is this property true of all sides?" So you could have an alternate function for those: template<typename Predicate> static inline bool TestAllCssSides(Predicate pred) { // Or do int+casting to enumerate the sides. It doesn't matter. static constexpr allSides[] = { eSideTop, eSideRight, eSideBottom, eSideLeft }; for (css::Side side : allSides) { if (!pred(side)) return false; } return true; } And then this: NS_FOR_CSS_SIDES(ix) { if (mBorderStyle[ix] != aNewData.mBorderStyle[ix] || mBorderColor[ix] != aNewData.mBorderColor[ix]) { return nsChangeHint_RepaintFrame; } } would transform into this (feel free to inline the lambda into its one use if desired): auto borderRemainsSame = [this, &aNewData](css::Side side) { return mBorderStyle[side] == aNewData.mBorderStyle[side] && mBorderColor[side] == aNewData.mBorderColor[side]; }; if (!TestAllSides(borderRemainsSame)) return nsChangeHint_RepaintFrame; Macros for NS_FOR_CSS_SIDES's purposes are anachronistic. And by not using them, you avoid a bunch of the shadowing discussions in this bug, you don't have extra braces, &c. You should use lambdas for this now! I suggested using an array + builtin iterator in attachment 8788830 [details] [diff] [review]. Unfortunately, it was deemed too slow, per comment 18. FTR, I did check the optimized assembler for the ForAllCssSides above; it reads the Side values through a pointer, so has the same problem. Pushed by mpalmgren@mozilla.com: Add MOZ_CONCAT for preprocessor token pasting. r=waldo Iterate Sides using an int32_t instead to avoid UBSan warning. r=dholbert Thank you for perservering with this trickier-than-expected bug, Mats. It'll be a big help with Julian's UBSan investigations, which is a good thing. I should say also that it *should* be a full and complete fix to add a final enum _LIMIT value. C++11's description of the values in an enum type says basically it's the smallest N-bit integer sufficient to hold all the enumerators. Here those are 0,1,2,3 -- so simply adding a 4 would make values 0-7 valid and would mean operator+ wouldn't create an invalid Side value. But I don't know whether code is switching on Sides such that adding another initializer would be undesirable. > But I don't know whether code is switching on Sides such that adding > another initializer would be undesirable. Mats said that in comment 10. I took a look and there weren't that many switches -- a dozen or so -- and some already had code to handle out-of-bad values. But, eh, it didn't seem that important. Status: NEW → RESOLVED Closed: 3 years ago Resolution: --- → FIXED Target Milestone: --- → mozilla51
https://bugzilla.mozilla.org/show_bug.cgi?id=1299379
CC-MAIN-2019-30
refinedweb
2,915
55.64
Find Questions & Answers Can't find what you're looking for? Visit the Questions & Answers page! Hi All Requirement: If Point 1 not possible on PI 7.0 then we have to implement point 2 ----------------------------------------------------------------------------------------------------------------- Point1: Where PI has to pick PDF file from AL11 and encode it to Base64 then pass it to one of the field in WSDL. In my other project we are using Java mapping which executes successfully on PI 7.11 and converts any input file to Base64.Our JDK version is 1.5 so we have compiled jar file on 1.5 in NWDS. Now the issue is on PI 7.0 with JDK 1.3.I have compiled same program on jdk 1.3 and when try to export it throws Syntax error while reading import javax.xml.bind.DatatypeConverter; Please let me know what could be the issue? Can you please help me out with any UDF for Base64 conversion? ----------------------------------------------------------------------------------------------------------------------- Point2: Pick Base64 encoded file from AL11 and pass it to one of the field in WSDL. From SDN I found that we need Java mapping to pass entire file to a single field of Source structure and map it to Target WSDL. When I RUN java program same issue with jdk 1.3 it throws syntax error for few import classes.Where as same java program will not throw any error with Jdk 1.6. Thanks in advance!! you get import erros in 7.0 because of the all standard jars are not available in 7.0 which were later included in 7.1> . So take the missing jars and import them as imported archives in 7.0 along with your java mappings. Thank you Manoj I will try this and let you know the result. Hi Manoj How can we import multiple jars in Imported archive? when I try to import second jar file it is replacing first one.Please guide me. Regards anitha Did u try to create a multiple imported archives ? Dont replace the existing one
https://answers.sap.com/questions/76306/filebase64-to-soap-async-scenario-in-pi-70.html
CC-MAIN-2018-09
refinedweb
338
86.81
I'm trying to use Nevow to build a site which displays the results of a series of SQL queries. It looks good so far, I have the basic site structure all sorted out in my mind (it's *very* impressive how quick that was in Nevow). Before I flesh things out much further, I want to add some authentication - basically, "guest" users will be able to see a limited subset of the data. Adding authentication including a "login" form in the sidebar (a bit like Roundup does) was again very easy. I basically cribbed from the existing examples. But there are a few things I's now like to add: 1. Ultimately, I want to proxy the app through Apache, so I was using the Virtual Host Monster. Im ny original, unauthenticated, application, I added a "vhost" child to the main application resource, and that was it. I can no longer do that, as the resource is wrapped in a guard.SessionWrapper, which doesn't have a putChild method. I'm not clear that I want the vhost child to be authenticated anyway - what I *think* I want is for "/" to be authenticated, but "/vhost" not to be. Or do I? Any suggestions?'ve scanned the various examples, both in the distribution and in the Nevow sandbox, but nothing seems to do what I want. Can anyone give me some pointers? <off on a tangent> This is the sort of area where the lack of documentation really hurts. Examples are great (and the wealth of Nevow examples is realy nice) but there's a lack of "general principle" documentation to make it easy to generalise the example code. My best example of this is that I can't work out what to return from a render_* method - should it be a function, or a string, or a stan tree, or what? I suspect that by the magic of interfaces, the answer is "anything that can be adapted to an ISomething" (which needs further documentation to say what standard adapters from string, sequence, whatever to ISomething exist) - but it's not stated anywhere, which makes writing render_* methods an exciting exercise in experimentation :-) At the other end of the scale, the source is really too low-level to follow for this sort of thing (I have tried). Is there any documentation effort for Nevow going on anywhere? I'd happily contribute, although it would more likely be in the form of questions than answers at the moment :-) </off on a tangent> FWIW, I attach my driver script below, in case it clarifies my authentication question above. -------------- next part -------------- from twisted.application import internet from twisted.application import service from twisted.web import static from nevow import appserver from nevow import vhost from nevow import guard from nevow import inevow from twisted.cred import portal from twisted.cred import checkers from twisted.cred import credentials from testapp.web import pages # Authorisation setup. # First we need a realm, which provides requestAvatar # TODO: need NotLoggedIn, LoggedIn and noLogout class MyRealm: """A simple implementor of cred's IRealm. For web, this gives us the LoggedIn page. """ __implements__ = portal.IRealm def requestAvatar(self, avatarId, mind, *interfaces): for iface in interfaces: if iface is inevow.IResource: # do web stuff if avatarId is checkers.ANONYMOUS: resc = pages.BasePage() else: resc = pages.BasePage(avatarId) resc.realm = self return (inevow.IResource, resc, resc.logout) raise NotImplementedError("Can't support that interface.") # Now create a portal to our realm realm = MyRealm() portal = portal.Portal(realm) # Create a checker for a static list of test users myChecker = checkers.InMemoryUsernamePasswordDatabaseDontUse() myChecker.addUser("user","password") myChecker.addUser("fred", "flintstone") # Register our checker, and an anonymous user checker, with the portal portal.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous) portal.registerChecker(myChecker) application = service.Application('testapp') # Instead of the application resource being the base page, it becomes a # SessionWrapper round the portal we created. The base page is part of the # realm - see above... # appResource = pages.BasePage() appResource = guard.SessionWrapper(portal) #appResource.putChild('robots.txt', static.File('static/robots.txt')) # SessionWrapper doesn't have a putChild method... #vResource = vhost.VHostMonsterResource() #appResource.putChild('vhost', vResource) webServer = internet.TCPServer(8080, appserver.NevowSite(appResource)) webServer.setServiceParent(application) # vim:ft=python: -------------- next part -------------- Paul -- The scientific name for an animal that doesn't either run from or fight its enemies is lunch. -- Michael Friedman
http://twistedmatrix.com/pipermail/twisted-web/2004-October/000799.html
CC-MAIN-2013-20
refinedweb
724
57.37
March 28th, 2014 • Issue #199 • Archives • Press Room We have not forgotten about you (yet)! Anton (talk) ) 09:50, March 30, 2014 (UTC) I am impressed by the amount of things you can do with HTML tags! Anton (talk) Ѧ 13:28 30-Mar-14 Very nice, and well-documented! But your choice for the default is ugly. Spıke Ѧ 00:31 16-Apr-14 edit Section numbering on UN:HAX PS--Forgive me if I've asked this before, but what sorcery is suppressing the section numbering of UN:HAX? Spıke Ѧ 21:53 14-Apr-14 It is caused by either of the two examples of <DynamicPageList>. What's odd is that none of the three pages in the list seem to be suppressing their own section numbering. Spıke Ѧ 12:36 19-Apr-14 - Forum, forum, forum. Never really understood the point of NiceQuote! ) 19:10, April 30, 2014 (UTC) - Oh, I see the Knowledge Base works now (and I've just read your message on Simsie's talk page). Anton (talk) Ѧ 14:54 8-Jun-14 edit SFV VFS is open again, in case you are interested! Anton (talk)) 15:47, August 14, 2014 (UTC) - Move done. Not sure if I should have left that redirect behind or not though. -- Simsilikesims(♀GUN) Talk here. 17:00, August 14, 2014 (UTC) - The fact that he is an Admin indeed doesn't mean he is the only one. But separately, that naming convention (UnSignpost:UnSignpost) can't be optimal! Spıke Ѧ 11:06 17-Aug-14 edit So you really are an admin now Please accept my belated congratulations. I'm sorry to see that it's temporary, because I have a selfish belief that it should be permanent. (Am I brown nosing again?) -– Llwy-ar-lawr • talk • contribs • 00:28, August 23, 2014 (UTC) - Yeah - eventually one of us will get around to removing that status. - The sad truth is I'm here so rarely it makes no sense for me to be a permanent admin. It was handy for a particular purpose though. • Puppy's talk page • 02:24 pm 28 Aug 2014 - Lots of the permanent admins are here more rarely than you. -– Llwy-ar-lawr • talk • contribs • 16:49, August 28, 2014 (UTC) edit Forum:I think I fixed the sprite Llwy has JS code to deal with Wikia's new "info icon." She has code to deal with some of our nagging Table of Contents issues that doesn't do anything for me; I have code that does, only it isn't good, and she has tested in more environments than I have. Would you please visit there? Spıke Ѧ 22:52 30-Aug-14 edit Deletion survivor categories Llwy and I concur at Uncyclopedia talk:Votes for deletion#Redlinked deletion survivor categories that categories for deletion survivors are unnecessary; and it is a continuing chore to create them. Please visit that page and concur or defend them. Spıke Ѧ 22:55 19-Sep-14 edit Here's a very special UnSignpost November 9th, 2014 • Issue #202 • Archives • Press Room edit Editing under the influence Judging from your Change Summaries (and after a trip to Google), I recommend you get some sleep and not use your new ability to unblock yourself. Spıke Ѧ 15:30 3-Dec-14 edit Template:FA Very well, though I don't understand your Change Summary. But it seems I had reverted Simsie, whose Summary said to look at her talk page (where there is nothing) or yours (except it isn't clear where any archives live). Spıke Ѧ 23:09 8-Dec-14 - It came about due to my playing around with a couple of articles prior to them becoming FA, and as a result one of my "test" pages ended up on the front page as feature. The way that FA used to work was that if a featured article was transcluded into another page, it also transcluded the FA template, along with the links/categories that showed the article as a feature due to our DPL tricks. That change you were looking at stops the links/categories from being transcluded a second time, so that only the original article ends up as a feature, not any other pages that transclude it. - It was a conversation held ages ago. It's a little hacky in the way that it works, but it works without going through an even more complex FA process. it's also works well for dealing with nested templates that play with categories. • Puppy's talk page • 11:36 pm 08 Dec 2014 Transcluding an entire article into another one? Countermanding side effects with deliberately miscoded tags? This is just unwise, but I don't insist. I don't know when the conversation was held, but the change I inadvertently reverted was made in Oct-13, and again, there should be some way to find your archives to learn the context. Spıke Ѧ 23:53 8-Dec-14 edit Liberal Party of Australia Nice that you dropped by! Would you please review Anon's massive dump into this article from some other wiki that has templates we don't? Spıke Ѧ 01:35 8-Mar-15 - The article prior to these edits has a lot of randumbo and cruft. While there's some randumbo here, it is actually a huge improvement on what was there prior. The editor is obviously wiki savvy - my guess is from Wikipedia based on those templates. I'm happy with the edits. Frosty previously did a lot of work on Tony Abbott, who is the leader of that party, so if he's around he may have another perspective. • Puppy's talk page • 04:24 am 08 Mar 2015 OK, then I'll mark his edits Patrolled and invite him to register, thanks. Spıke Ѧ 04:48 8-Mar-15 edit Miss me? Miss me? DAP Dame Pleb Com. Miley Spears (talk) 03:42, April 2, 2015 (UTC) - My heart has been rent into a thousand pieces while you've been away. • Puppy's talk page • 07:34 am 02 Apr 2015 - Only a thousand? Hugs! My first article here in almost five years is UnNews:Obama plans to get millions of girls. But I'm adopter/admin/bureaucrat of Discordia.wikia.com. DAP Dame Pleb Com. Miley Spears (talk) 04:22, April 3, 2015 (UTC) - I'm rarely here at all any more. Too busy doing nothing of value in the real world. • Puppy's talk page • 10:32, April 30, 2015 (UTC) - Time to get off the radio:42, April 30, 2015 (UTC) - The real world sucks. That's why I plan to go to college until I retire. DAP Dame Pleb Com. Miley Spears (talk) 04:22, May 2, 2015 (UTC) - PuppyOffTheRadio jyust doesn't have the same ring. Although I've handed in my notice at work, so I may be unemployed soon - which means more time on here. - And I didn't get no real education. The only reason I didn't drop out of high school is that just waiting out the time seemed like less effort. • Puppy's talk page • 05:44 am 02 May 2015 edit Springtime Surprise! assignment Your article to write (by 23:59 UTC 3-May) is Bedspring. Spıke Ѧ 13:28 28-Apr-15 edit Selfie vandal If you don't stop vandalizing your own user page I'm going to report you to....I don't know. DAP Dame Pleb Com. Miley Spears (talk) 05:02, May 4, 2015 (UTC) - Goddamn vandals! I'll deal with this! • Puppy's talk page • 09:26 am 05 May 2015 edit Conjoined class selector Thanks for commenting at Template talk:Recent. It was the linear gradient thing where my old browser needed the -moz prefix; for rounded borders, it doesn't. In my version of MediaWiki:Common.css of 22:36 UTC 24-May (undone), I tried to select for all pages in the UnNews space that are being viewed (as opposed to edited or having their history viewed). I selected: body.ns-102.action-view H1.firstHeading { display: none !important } ...as the new UnNews masthead takes the place of the Uncyclopedia page title that is normally the <H1>. ns-102 is the UnNews namespace, and action-view is a class of the BODY of any page you are simply viewing. I've found a claim that specifying two classes was in CSS 2.1, which even my old browser has. But this edit seemed to disable the entire rule for me. It might be that one can combine multiple [class~=...] clauses, but it might also be that you have a simpler answer. Spıke Ѧ 00:17 25-May-15 Never mind, it's working now! My confusion seems to come from Wikia stickiness; there is a delayed effect when you edit the system CSS. Spıke Ѧ 10:04 25-May-15 - I knew there was something CSS3 that Firefox 3.4/3.5 was funky with. As for the latter thingy, glad it sorted itself, as my very quick code read earlier didn't present any reason I could see for any issues. I wonder if purging after edit would be effective for CSS pages. • Puppy's talk page • 03:59 am 26 May 2015 edit User:Caram/DiezelSun This article looks like the product of Google Translate, but there is a lot of crap in userspace, and voters don't have the energy to get through the current VFD page, much less police userspace, even at the request of a new username who might or might not be the author. So I removed your {{VFD}} (as you didn't open a ballot anyway). 13:03 Must have missed)}" >20:57 21-Jun-15 edit Active Admin Want to add yourself to the active admin:46, July 7, 2015 (UTC) - Given I make about one edit a week, it'd be an overstatement to call me active. Especially if a newbie was asking me for help. • Puppy's talk page • 09:10 pm 07 Jul 2015 edit Hall of shame Hi Puppy, just to let you know I marked two amendments this morning to Uncyclopedia:Hall of Shame/PuppyOnTheRadio as patrolled. Assumed it was your good self as an i.p. editing as it seemed to be updating the entry, not vandalism. --EStop (talk) 07:40, July 31, 2015 (UTC) - Yep - t'was me. I'm not a racist, but... is a creation of my short lived sock C2H6O, which is more annoying to type properly than PuppyOnTheRadio. And I really should log in when editing. Pup - And now C₂H₆O has 3 features under his (or her) name. Which means one feature for every 3.75 days of activity. Whereas I have one for every 56 days. (S)he's not getting any credit for it though! The previous edit was signed by PuppyOnTheRadio, but he is too lazy to create a signature yet. 10:48 am 31 Jul 2015 edit Things you can find Hint. It is not a rubber dog collar. --:20, July 31, 2015 (UTC) - It's the tail that concerns me more. The previous edit was signed by PuppyOnTheRadio, but he is too lazy to create a signature yet. 10:33 am 31 Jul 2015 edit Section numbering Nice to see you checking back in. I followed your revert at your Featured Article with an explanation to the young vandal and a one-day ban. Section numbering has been broken for about a week. (Just before it went away entirely, it started to work at UN:HAX, where we discussed that something about the DPL examples on that page had been breaking it.) I filed a bug report and Sannse stated: "The section numbering in articles preference was removed a while back, it was rarely used and so depreciated." Unfortunately, we are in the business of imitating Wikipedia and not tracking what Bronies wikis rarely use. It would take 15 lines of JavaScript/jQuery to put it back. I can do $("H1 H2 H3 H4 H5").each() from memory but would have to go back to the book to code the rest; it might come to you more quickly. At that point, of course, we now have to beg to Wikia to put the result into MediaWiki:Uncyclopedia.js. Care to:12 28-Aug-15 - I'm just about to fall asleep, as I've spent the last couple days moving house, and have more to do tomorrow. I'd probably have to go to book as well, tbh. Is it that it has been killed by Wikia, or has there been a change to global preferences that we can switch back on? The previous edit was signed by PuppyOnTheRadio, but he is too lazy to create a signature yet. 02:20 pm 28 Aug 2015 - Also, I thought we had admin protect on features for the day of feature. That article was only autoconfirmed protect. The previous edit was signed by PuppyOnTheRadio, but he is too lazy to create a signature yet. 02:21 pm 28 Aug 2015 Romartus does the featuring, but autoconfirmed is the protection I have noticed for FAs, during their featuring and afterward. We allow FAs to be edited to be "brought up-to-date" but Romartus has been especially active in reverting 28-Aug-15 - Do FAs need to be brought up-to-date on the day of feature? I'm asleep anyway. The previous edit was signed by PuppyOnTheRadio, but he is too lazy to create a signature yet. 02:34 pm 28 Aug 2015 I think FAs are presumed to be exactly up-to-date on the day of feature (which now lasts a week or so). Regarding the JavaScript, screw it: I am prevented from even editing my own Uncyclopedia.js.:36 28-Aug-15 I could not even do the above right from memory! But here is some code that works. Ideally it should be in a function so my variables don't interfere if other variables of the same name exist globally.:24 28-Aug-15 /* JavaScript to prepend section numbers to every heading on the page. */ var hh2 = 0, hh3 = 0, hh4 = 0, hh5 = 0; $("H2,H3,H4,H5").each(function(index, element) { /* The page name is an H1. Ignore user H1s in the article. */ /* Also ignore "From Uncyclopedia..." and the heading on the Table of Contents. */ if ((element.id == "siteSub") || (hh2 == 0 && $(this).text() == "Contents")) return true; switch (element.tagName) { case "H2": hh2 = hh2 + 1; hh3 = 0; hh4 = 0; hh5 = 0; s = hh2+" "; break; case "H3": hh3 = hh3 + 1; hh4 = 0; hh5 = 0; s = hh2+"."+hh3+" "; break; case "H4": hh4 = hh4 + 1; hh5 = 0; s = hh2+"."+hh3+"."+hh4+" "; break; case "H5": hh5 = hh5 + 1; s = hh2+"."+hh3+"."+hh4+"."+hh5+" "; break; }; $(this).prepend(s); }) - I'm glad I slept on it. Very clean coding, but would have taken me far too long to get to the same result. (Js has never been my forte.) The previous edit was signed by PuppyOnTheRadio, but he is too lazy to create a signature yet. 11:36 pm 28 Aug 2015 [Replace code above and my description of improvements, with improved code above.] And are you familiar with SQL?:20 1-Sep-15 - I haven't used SQL since 1991, so I'd have to say no. The previous edit was signed by PuppyOnTheRadio, but he is too lazy to create a signature yet. 09:38 pm 01 Sep 2015 edit Uncyclopedia:At A Glance This dashboard by Dr. Skullthumper has a component at {{Uncyclopedia:At A Glance/usertalk}} that tracks activity on user talk pages. There is a comment on the talk page that it would be cute to have a box that lists the most recently created talk pages (that is, new Uncyclopedians who have just been welcomed). Can you clone and modify the DPL in this template to do:34 24-Nov-15 - DPL list of user talk pages by creation date? Definitely do-able. Without looking, I'm assuming it's currently using modified date as a sortorder. Changing that to created date should be the ticket. Let me have a look this evening my time - should have something by tomorrow. The previous edit was signed by PuppyOnTheRadio, but he is too lazy to create a signature yet. 05:56 am 24 Nov 2015 - Odd. <forum>is similar but slightly different to <dpl>. So the change in ordermethod would work with DPL (I think), but not working with forum. Trying to change the tags though is stopping my edits saving, from what I can see. It may be a phone edit issue though, so I'll either get it fixed quickly when I'mon a PC, or I'll end up recreating the DPL from scratch. Hmmm… The previous edit was signed by PuppyOnTheRadio, but he is too lazy to create a signature yet. 08:43 am 24 Nov 2015 - Okay - long story short. Technically it works. In practise, the servers die when they try to run the background SQL that (I think) is trying to sort all the user pages based on first edit date. So it may be possible, but I'm not sure how. The previous edit was signed by PuppyOnTheRadio, but he is too lazy to create a signature yet. 10:37 am 24 Nov 2015 edit Request For Rename Tim Quievryn wrote me today on whether to delay or proceed with restricting page-move to Rollbackers and Admins, and I said all active Admins reacted positively. (See Forum:Page-move restricted.) You might want to start toying with your project to automate such:19 19-Dec-15 edit Template:VFDr That seems to have done it, thanks! I would have had to go back to the books for a couple hours to come up with that formulation.:08 21-Jun-16 - It's nice when the first attempted solution works. The previous edit was by PuppyOnTheRadio (Talk). 17:18, June 21, 2016 (UTC) Indeed, more than a couple hours, as I would not have attacked the problem "Is there another way to generate {" but "How can this page be recoded to not have <nowiki> inside <inputbox>.":52 21-Jun-16 - That'd be fairly easy. Once you remove the inputbox all you're left with is the need for a link to add section with preload. Add the topic header into the preload text, add ?preload= to your link, and Bob's your father's brother. - I did play with that as an option when rejigging VFD. I would probably have opted for a new page inputbox like VFH does if it had come to that though. That would add a few extra pre-populate options (so bringing it to a single template). It would have involved moving to individual pages per nomination, so DPL to have the VFD page have the same functionality, and a different archive system, which would effectively auto-archive. We decided against that when we had the inputbox option working though. The previous edit was by PuppyOnTheRadio (Talk). 23:39, June 21, 2016 (UTC) edit OneRingworld Image Is there a chance that there's a higher-res version of the One Ringworld picture you posted back in the day knocking around, and that you still have it? We wanted to print up a copy as a present for a friend. Properly attributed, of course. :) LisardggY - Not signed in. Sadly no. This was a quick and dirty chop done using MS paint, of all things. I stole two images and stuck them together, and added a gold colored ovoid. Can't recall where I got the source images. PuppyOnTheRadio edit Mother Fucker Thanks for trying to make something of this article. However, can you do nothing with my segue into Movies other than revert:41 16-Aug-16 - Sorry - that was unintentional. All I wanted to do was remove the Cosby line and change Blessed to Holy. I'm not sold on the movie concept - seems another concept added in without adding to the whole IMO - but was happy to see how it panned out. The Grandmotherfucker part doesn't fit with the main concept either. The only concept I can see really gaining ground is expanding to be a parody of Mother Theresa, but it's a one hit joke that I ca't see stretching - qv Big Butte Creek. The previous edit was by PuppyOnTheRadio (Talk). 21:12, August 16, 2016 (UTC) edit Template:Title Would you please look at this and the related JavaScript code in MediaWiki:Common.js? I may have broken the template when I edited Common to use jQuery. Expert3222 notes that it doesn't work if the desired title is italic (as we do all over the place with names of shows and songs).:40 24-Aug-16 edit Return of the Pup Good to see you are writing again Pup. I like Old Testament Law, I don't think it needs a Pee Review? Go for:15, September 10, 2016 (UTC) - Second positive review that has so far. thanks. Maybe I'm just expecting something more - maybe longer. I might leave it for a week or so and come back to it. 11:29, September 10, 2016 (UTC)
http://uncyclopedia.wikia.com/wiki/User_talk:PuppyOnTheRadio?t=20130211095945
CC-MAIN-2016-44
refinedweb
3,565
73.07
Conditional formatting lost Hi, i've an issue with openpyxl 2.2.5. Conditinal formatting is lost just after loading a workbook and saving it without even changing any data. I've attached sample files. The file is even 3kb smaller afterwards. from openpyxl import load_workbook sFileName = 'test.xlsx' ws = load_workbook(filename = sFileName) ws.save(filename = sFileName) The problem is that the original file uses extensions to conditional formatting that are not covered in the specification. In this case all the conditional formatting is embedded as an extension. Which version of Office are you using? You might want to check the compatibility settings. I'm using Office Professional Plus 2010 Excel Version 14.0.7151.5001 (32-Bit) I've just discovered that images are also lost. Images have always been lost when processing files. That will hopefully change in a future version. I think the formatting can be retained if the rule is expressed differently. Isn't it specified here?: Looks like it works with conditional format "cell value" instead of "specific text". Yes, it's specified as an extension. If only it were as easy as supporting an additional tag. However, Excel does this by creating the extension and the format in one place at linking to it from another. This is tricky to manage, though we'll hopefully get round to it one day. If you look at the code it uses, almost anything would be preferable to it. Compare: classic formatting: Excel 2010+ We should add warnings for this kind of extension. Warn when unsupported extensions are used. Partially resolves #493 → <<cset e2a85c0c8ee7>>
https://bitbucket.org/openpyxl/openpyxl/issues/493
CC-MAIN-2020-24
refinedweb
267
61.33
How to Speed up Pandas by 4x with one line of code While Pandas is the library for data processing in Python, it isn't really built for speed. Learn more about the new library, Modin, developed to distribute Pandas' computation to speedup your data prep. Pandas is the go-to library for processing data in Python. It’s easy to use and quite flexible when it comes to handling different types and sizes of data. It has tons of different functions that make manipulating data a breeze. The popularity of various Python packages over time. Source But there is one drawback: Pandas is slow for larger datasets. By default, Pandas executes its functions as a single process using a single CPU core. That works just fine for smaller datasets since you might not notice much of a difference in speed. But with larger datasets and so many more calculations to make, speed starts to take a major hit when using only a single core. It’s doing just one calculation at a time for a dataset that can have millions or even billions of rows. Yet most modern machines made for Data Science have at least 2 CPU cores. That means, for the example of 2 CPU cores, that 50% or more of your computer’s processing power won’t be doing anything by default when using Pandas. The situation gets even worse when you get to 4 cores (modern Intel i5) or 6 cores (modern Intel i7). Pandas simply wasn’t designed to use that computing power effectively. Modin is a new library designed to accelerate Pandas by automatically distributing the computation across all of the system’s available CPU cores. With that, Modin claims to be able to get nearly linear speedup to the number of CPU cores on your system for Pandas DataFrames of any size. Let’s see how it all works and go through a few code examples. How Modin Does Parallel Processing With Pandas Given a DataFrame in Pandas, our goal is to perform some kind of calculation or process on it in the fastest way possible. That could be taking the mean of each column with .mean(), grouping data with groupby, dropping all duplicates with drop_duplicates(), or any of the other built-in Pandas functions. In the previous section, we mentioned how Pandas only uses one CPU core for processing. Naturally, this is a big bottleneck, especially for larger DataFrames, where the lack of resources really shows through. In theory, parallelizing a calculation is as easy as applying that calculation on different data points across every available CPU core. For a Pandas DataFrame, a basic idea would be to divide up the DataFrame into a few pieces, as many pieces as you have CPU cores, and let each CPU core run the calculation on its piece. In the end, we can aggregate the results, which is a computationally cheap operation. How a multi-core system can process data faster. For a single-core process (left), all 10 tasks go to a single node. For the dual-core process (right), each node takes on 5 tasks, thereby doubling the processing speed. That’s exactly what Modin does. It slices your DataFrame into different parts such that each part can be sent to a different CPU core. Modin partitions the DataFrames across both the rows and the columns. This makes Modin’s parallel processing scalable to DataFrames of any shape. Imagine if you are given a DataFrame with many columns but fewer rows. Some libraries only perform the partitioning across rows, which would be inefficient in this case since we have more columns than rows. But with Modin, since the partitioning is done across both dimensions, the parallel processing remains efficient all shapes of DataFrames, whether they are wider (lots of columns), longer (lots of rows), or both. A Pandas DataFrame (left) is stored as one block and is only sent to one CPU core. A Modin DataFrame (right) is partitioned across rows and columns, and each partition can be sent to a different CPU core up to the max cores in the system. The figure above is a simple example. Modin actually uses a Partition Manager that can change the size and shape of the partitions based on the type of operation. For example, there might be an operation that requires entire rows or entire columns. In that case, the Partition Manager will perform the partitions and distribution to CPU cores in the most optimal way it can find. It’s flexible. To do a lot of the heavy lifting when it comes to executing the parallel processing, Modin can use either Dask or Ray. Both of them are parallel computing libraries with Python APIs, and you can select one or the other to use with Modin at runtime. Ray will be the safest one to use for now as it is more stable — the Dask backend is experimental. But hey, that’s enough theory. Let’s get to the code and speed benchmarks! Benchmarking Modin Speed The easiest way to install and get Modin working is via pip. The following command installs Modin, Ray, and all of the relevant dependencies: pip install modin[ray] For our following examples and benchmarks, we’re going to be using the CS:GO Competitive Matchmaking Data from Kaggle. Each row of the CSV contains data about a round in a competitive match of CS:GO. We’ll stick to experimenting with just the biggest CSV file for now (there are several) called esea_master_dmg_demos.part1.csv, which is 1.2GB. With such a size, we should be able to see how Pandas slows down and how Modin can help us out. For the tests, I’ll be using an i7–8700k CPU, which has 6 physical cores and 12 threads. The first test we’ll do is simply reading in the data with our good’ol read_csv().. Not too shabby for just changing the import statement! Let’s do a couple of heavier processes on our DataFrame. Concatenating multiple DataFrames is a common operation in Pandas — we might have several or more CSV files containing our data, which we then have to read one at a time and concatenate. We can easily do this with the pd.concat() function in Pandas and Modin. We’d expect that Modin should do well with this kind of an operation since it’s handling a lot of data. The code is shown below. In the above code, we concatenated our DataFrame to itself 5 times. Pandas was able to complete the concatenation operation in 3.56 seconds while Modin finished in 0.041 seconds, an 86.83X speedup! It appears that even though we only have 6 CPU cores, the partitioning of the DataFrame helps a lot with the speed. A Pandas function commonly used for DataFrame cleaning is the .fillna() function. This function finds all NaN values within a DataFrame and replaces them with the value of your choice. There’s a lot of operations going on there. Pandas has to go through every single row and column to find NaN values and replace them. This is a perfect opportunity to apply Modin since we’re repeating a very simple operation many times. This time, Pandas ran the .fillna() in 1.8 seconds while Modin took 0.21 seconds, an 8.57X speedup! A caveat and final benchmarks So is Modin always this fast? Well, not always. There are some cases where Pandas is actually faster than Modin, even on this big dataset with 5,992,097 (almost 6 million) rows. The table below shows the run times of Pandas vs. Modin for some experiments I ran. As you can see, there were some operations in which Modin was significantly faster, usually reading in data and finding values. Other operations, such as performing statistical calculations, were much faster in Pandas. Practical Tips for using Modin Modin is still a fairly young library and is constantly being developed and expanded. As such, not all of the Pandas functions have been fully accelerated yet. If you try and use a function with Modin that is not yet accelerated, it will default to Pandas, so there won’t be any code bugs or errors. For the full list of Pandas methods that are supported by Modin, see this page. By default, Modin will use all of the CPU cores available on your machine. There may be some cases where you wish to limit the number of CPU cores that Modin can use, especially if you want to use that computing power elsewhere. We can limit the number of CPU cores Modin has access to through an initialization setting in Ray since Modin uses it on the backend. import ray ray.init(num_cpus=4) import modin.pandas as pd When working with big data, it’s not uncommon for the size of the dataset to exceed the amount of memory (RAM) on your system. Modin has a specific flag that we can set to true, which will enable its out of core mode. Out of core basically means that Modin will use your disk as overflow storage for your memory, allowing you to work with datasets far bigger than your RAM size. We can set the following environment variable to enable this functionality: export MODIN_OUT_OF_CORE=true Conclusion So there you have it! Your guide to accelerating Pandas functions using Modin. Very easy to do by changing just the import statement. Hopefully, you find Modin useful in at least a few situations to accelerate your Pandas functions. Related:
https://www.kdnuggets.com/2019/11/speed-up-pandas-4x.html
CC-MAIN-2020-24
refinedweb
1,604
72.46
Andi. I think it would, in fact, be well suited to either type ofcommunication model, even concurrently (e.g. an intra-vm ipc channelresource could live right on the same bus as a virtio-net and avirtio-disk resource)> Wouldn't they typically have a default route anyways and be able to talk to each > other this way? > And why can't any such isolation be done with standard firewalling? (it's known that > current iptables has some scalability issues, but there's work going on right> now to fix that). > vbus itself, and even some of the higher level constructs we apply ontop of it (like venet) are at a different scope than I think what youare getting at above. Yes, I suppose you could create a private networkusing the existing virtio-net + iptables. But you could also do thesame using virtio-net and a private bridge devices as well. That is notwhat we are trying to address.What we *are* trying to address is making an easy way to declare virtualresources directly in the kernel so that they can be accessed moreefficiently. Contrast that to the way its done today, where the modelslive in, say, qemu userspace.So instead of havingguest->host->qemu::virtio-net->tap->[iptables|bridge], you simply haveguest->host->[iptables|bridge]. How you make your private network (ifthat is what you want to do) is orthogonal...its the path to get therethat we changed.> What would be the use cases for non networking devices?>> How would the interfaces to the user look like?> I am not sure if you are asking about the guests perspective or thehost-administators perspective.First now lets look at the low-level device interface from the guestsperspective. We can cover the admin perspective in a separate doc, ifneed be.Each device in vbus supports two basic verbs: CALL, and SHMint (*call)(struct vbus_device_proxy *dev, u32 func, void *data, size_t len, int flags);int (*shm)(struct vbus_device_proxy *dev, int id, int prio, void *ptr, size_t len, struct shm_signal_desc *sigdesc, struct shm_signal **signal, int flags);CALL provides a synchronous method for invoking some verb on the device(defined by "func") with some arbitrary data. The namespace for "func"is part of the ABI for the device in question. It is analogous to anioctl, with the primary difference being that its remotable (it invokesfrom the guest driver across to the host device).SHM provides a way to register shared-memory with the device which canbe used for asynchronous communication. The memory is always owned bythe "north" (the guest), while the "south" (the host) simply maps itinto its address space. You can optionally establish a shm_signalobject on this memory for signaling in either direction, and Ianticipate most shm regions will use this feature. Each shm region hasan "id" namespace, which like the "func" namespace from the CALL methodis completely owned by the device ABI. For example, we have might haveid's of "RX-RING" and "TX-RING", etc.From there, we can (hopefully) build an arbitrary type of IO service tomap on top. So for instance, for venet-tap, we have CALL verbs forthings like MACQUERY, and LINKUP, and we have SHM ids for RX-QUEUE andTX-QUEUE. We can write a driver that speaks this ABI on the bottomedge, and presents a normal netif interface on the top edge. So theactual consumption of these resources can look just like another otherresource of a similar type.-Greg[unhandled content-type:application/pgp-signature]
https://lkml.org/lkml/2009/4/1/166
CC-MAIN-2017-34
refinedweb
579
61.97
15 March 2011 10:10 [Source: ICIS news] SINGAPORE (ICIS)--Some Japanese petrochemical companies are planning to pull staff out of their Tokyo offices due to heightened fears of a nuclear radiation leak, sources close to the companies said on Tuesday. Sumitomo Chemical was said to be planning to evacuate its Tokyo-based office staff by Tuesday evening. "They might be forced to work from home, and might not be able to come in the office for the rest of the week or even longer," a source said. Sources said other petrochemical companies were also planning evacuations due to the heightened risks of a radiation leak from the Fukushima Daiichi nuclear plant. However, staff at Mitsui & Co might have to stay in the office, industry sources said. "It’s too dangerous to get out,” a source close to the company said. According to a Reuters report, the World Health Organisation has said that “?xml:namespace> A trader in Additional reporting by Gabriela Wheeler, Leslie Tan
http://www.icis.com/Articles/2011/03/15/9443864/some-japanese-petrochemical-firms-plan-staff-pull-out-from-tokyo.html
CC-MAIN-2015-06
refinedweb
165
59.64
Post Syndicated from Ben Nuttall original! Pin factories – take your pick GPIO Zero started out as a friendly API on top of the RPi.GPIO library, but later we extended it to allow other pin libraries to be used. The pigpio library is supported, and that includes the ability to remotely control GPIO pins over the network, or on a Pi Zero over USB. This also gave us the opportunity to create a “mock” pin factory, so that we could emulate the effect of pin changes without using real Raspberry Pi hardware. This is useful for prototyping without hardware, and for testing. Try it yourself! As well as the pin factories we provide with the library (RPi.GPIO, pigpio, RPIO, and native), it’s also possible to write your own. So far, I’m aware of only one custom pin factory, and that has been written by the AIY team at Google, who created their own pin factory for the pins on the AIY Vision Kit. This means that you can connect devices to these pins, and use GPIO Zero to program them, despite the fact they’re not connected to the Pi’s own pins. If you have lots of experience with RPi.GPIO, you might find this guide on migrating from RPi.GPIO to GPIO Zero handy. Ultrasonic distance sensor We had identified some issues with the results from the DistanceSensor class, and we dealt with them in two ways. Firstly, GPIO Zero co-author Dave Jones did some work under the hood of the pins API to use timing information provided by underlying drivers, so that timing events from pins will be considerably more accurate (see #655). Secondly, Dave found that RPi.GPIO would often miss edges during callbacks, which threw off the timing, so we now drop missed edges and get better accuracy as a result (see #719). The best DistanceSensor results come when using pigpio as your pin factory, so we recommend changing to this if you want more accuracy, especially if you’re using (or deploying to) a Pi 1 or Pi Zero. Connecting devices A really neat feature of GPIO Zero is the ability to connect devices together easily. One way to do this is to use callback functions: button.when_pressed = led.on button.when_released = led.off Another way is to set the source of one device to the values of another device: led.source = button.values In GPIO Zero v1.5, we’ve made connecting devices even easier. You can now use the following method to pair devices together: led.source = button Read more about this declarative style of programming in the source/values page in the docs. There are plenty of great examples of how you can create projects with these simple connections: Testing An important part of software development is automated testing. You write tests to check your code does what you want it to do, especially checking the edge cases. Then you write the code to implement the features you’ve written tests for. Then after every change you make, you run your old tests to make sure nothing got broken. We have tools for automating this (thanks pytest, tox, coverage, and Travis CI). But how do you test a GPIO library? Well, most of the GPIO parts of our test suite use the mock pins interface, so we can test our API works as intended, abstracted from how the pins behave. And while Travis CI only runs tests with mock pins, we also do real testing on Raspberry Pi: there are additional tests that ensure the pins do what they’re supposed to. See the docs chapter on development to learn more about this process, and try it for yourself. pinout You may remember that the last major GPIO Zero release introduced the pinout command line tool. We’ve added some new art for the Pi 3A+ and 3B+: pinout also now supports the -x (or --xyz) option, which opens the website pinout.xyz in your web browser. Zero boilerplate for hardware The goal of all this is to remove obstacles to physical computing, and Rachel Rayns has designed a wonderful board that makes a great companion to GPIO Zero for people who are learning. Available from The Pi Hut, the PLAY board provides croc-clip connectors for four GPIO pins, GND, and 3V3, along with a set of compatible components: Since the board simply breaks out GPIO pins, there’s no special software required. You can use Scratch or Python (or anything else). New contributors This release welcomed seven new contributors to the project, including Claire Pollard from PiBorg and ModMyPi, who provided implementations for TonalBuzzer, PumpkinPi, and the JamHat. We also passed 1000 commits! Watch your tone As part of the work Claire did to add support for the Jam HAT, she created a new class for working with its buzzer, which works by setting the PWM frequency to emit a particular tone. I took what Claire provided and added some maths to it, then Dave created a whole Tones module to provide a musical API. You can play buzzy jingles, or you can build a theremin: GPIO Zero theremin from gpiozero import TonalBuzzer, DistanceSensor buzzer = TonalBuzzer(20) ds = DistanceSensor(14, 26) buzzer.source = ds …or you can make a siren: GPIO Zero TonalBuzzer sine wave from gpiozero import TonalBuzzer from gpiozero.tools import sin_values buzzer = TonalBuzzer(20) buzzer.source = sin_values() The Tones API is a really neat way of creating particular buzzer sounds and chaining them together to make tunes, using a variety of musical notations: >>> from gpiozero.tones import Tone >>> Tone(440.0) >>> Tone(69) >>> Tone('A4') We all make mistakes One of the important things about writing a library to help beginners is knowing when to expect mistakes, and providing help when you can. For example, if a user mistypes an attribute or just gets it wrong – for example, if they type button.pressed = foo instead of button.when_pressed = foo – they wouldn’t usually get an error; it would just set a new attribute. In GPIO Zero, though, we prevent new attributes from being created, so you’d get an error if you tried doing this. We provide an FAQ about this, and explain how to get around it if you really need to. Similarly, it’s common to see people type button.when_pressed = foo() and actually call the function, which isn’t correct, and will usually have the effect of unsetting the callback (as the function returns None). Because this is valid, the user won’t get an error to call their attention to the mistake. In this release, we’ve added a warning that you’ll see if you set a callback to None when it was previously None. Hopefully that will be useful to people who make this mistake, helping them quickly notice and rectify it. Update now Update your Raspberry Pi now to get the latest and greatest GPIO Zero goodness in your (operating) system: sudo apt update sudo apt install python3-gpiozero python-gpiozero Note: it’s currently syncing with the Raspbian repo, so if it’s not available for you yet, it will be soon. What’s next? We have plenty more suggestions to be working on. This year we’ll be working on SPI and I2C interfaces, including I2C expander chips. If you’d like to make more suggestions, or contribute yourself, find us over on GitHub. The post GPIO Zero v1.5 is here! appeared first on Raspberry Pi.
https://noise.getoto.net/author/ben-nuttall/
CC-MAIN-2021-39
refinedweb
1,254
62.07
. Oops! [Line 1, Column 0] Invalid root element, expected (namespace uri:local name) of (), found (:feed Posted:Dec also in the camp that would like the raw data, perhaps via CSV so we could plug it into a spreadsheet and do different looks of the data More control of axis-scales would be good. (Similar to kelseymh's earlier post.) Could Instructables traffic be subcategorized as an option? I also agree with kelseymh, downloadable .csv files would be very useful for real analysis. Increasing the resolution of traffic sources would allow some testing of writting strategies. Perhaps downloadable reports could contain extra resolution? How about tracking forum posts, answers? I'm not sure if it'll help me write better Instructables (That seems to just take practice. And proofreading.) but it will help me promote them better. (Speaking of... Would love to see more referrers information on this magic new stats page.) Something I just noticed: I have some (seemingly random) data points missing on the 3-month chart. In the attached image I'm missing data for Dec 10-12 on the blue line and Dec 3-7 on the green line. But only in the 3-month view. The data is there in the 1-month view. It looks like it might be some point culling in the charting package, but it feels weird. I like looking at ibles which have been featured on lifehacker or gizmodo and seeing the massive spike, The attatched image is the maker tin after being featured (on both i think) I also think a little counter showing the total views of all instructables would be handy. It was great for about 10 min then it died with the same thing as Doctor What. Really good though this would be a fantastic pro feature :) ERROR 500: PageResult values not set 1) The "by traffic sources" doesn't seem to work. It just fails back to a default presentation of three of my I'bles, regardless of what I've checked or not. 2) Being able to choose a date range, for example to focus on some viewing spike in the past, would be nice (and ought to be easy :-). 3) Getting a dump of the raw data currently being displayed, e.g., as a CSV file, would let number crunchers like me play our own games. It also means that you wouldn't have to implement all of the proper statistical analysis stuff (mean, variance, etc.). 4) Why did you choose to have a separate dangling "go" hyperlink, rather than simply making each I'bles title a link? L I'm not sure the data helps me to "author better Instructables." It might be that if I were writing with the goal of lots of views, this might influence what I chose to publish or not. Thanks! :D (time to move on to our next plan ;) ) But it seems fine now. That spike came from "other" (as in "other than a search engine or within Instructables"), so I guess I got featured elsewhere. Most curious... (Did I mention I really, really like it?) :D awesome new feature.
http://www.instructables.com/community/Stats/C4X0QI9G4D61R8Q
CC-MAIN-2015-18
refinedweb
524
71.85
Help for Adobe FormsCentral ReplacementAsked by aclayman93 on January 26, 2015 at 01:22 PM I am having trouble importing the form below. Also, can my form be embedded like the current form? Thanks in advance! import form adobe forms central - JotForm Support Thank you for contacting us. Please submit your form URL (listed below) via the next page.*THkQkGZ6A We will send you an email once the import is done. If you have not already, there is a great way to transfer your forms from Adobe to our system so that your business does not even feels that there was anything happening with Adobe. Interested? I bet you are so here is the link to read more about it: Import Both Your Forms and Responses in a Single Step from Adobe FormsCentral I must warn you that reading the blog is the hardest thing to do that is related to this tool, so be prepared for the good times using it :)
https://www.jotform.com/answers/503631-Import-Help-for-Adobe-FormsCentral-Replacement
CC-MAIN-2016-50
refinedweb
162
76.56
Did! Join the conversationAdd Comment I tried /module:export /module:name as shown in the CppCon talk with Update 1 RTM leads to stuff like "not yet implemented"… But in the CppCon talk GDR told us that this "export feature" got good feedback in Microsoft… @Yupei, C++ Modules are included in Update 1, but they are still an experimental feature. We'll be publishing a blog post later this week that explains how to use modules in detail. Fix the bug in CRT (_sntscanf_s & DDX_Text) before extend features! I appreciate a lot more robustness than many features not well tested! As the updates now (may) contain new features, are there ABI-incompatibility issues between VS 2015 and VS 2015 Update 1 (i.e. will binaries compiled with VS 2015 Update 1 be fully compatible with binaries from VS 2015)? What about binaries compiled with VS 2015 Update 1 using C2/Clang and binaries compiled with VS 2015? @Yupei From my experience, most likely you are trying to use while compiling for x64, it seems like modules work only for win32, hopefully it will be clarified in blog post. Please do 'plan' to support ISO C99 complex.h: connect.microsoft.com/…/c99-complex-number-support — my_complex.cpp compile as: cl /TP my_complex.cpp — #include <stdio.h> #include <complex> int main() { std::complex<double> z1 = 1.0; std::complex<double> z2 = 2.0; printf("values: Z1 = %.2f + %.2fitZ2 = %.2f %+.2fin", z1, z1, z2, z2); return 0; } — works just fine! But — my_complex.c compile as: cl /TC my_complex.c — #include <stdio.h> #include <complex.h> int main() { double complex z1 = 1.0; double complex z2 = 2.0; printf("values: Z1 = %.2f + %.2fitZ2 = %.2f %+.2fin", creal(z1), cimag(z1), creal(z2), cimag(z2)); return 0; } —- throws errors! @Mats Taraldsvik: I know for a fact that because c2 is responsible for the codegen, then it will always be binary compatible with code compiled with cl(c1xx). This is by sheer virtue of the same backend doing the code generation for both compilers. For ABI compatibility, I really doubt that Microsoft would allow any ABI changes to occur between updates. @Jakko: Install the Clang/C2 stuff, select C99 standard, ???, profit? Will there be a blogpost about using "C++ Core Guidelines (NuGet packages)."? It's pretty hard to understand howt to do that at this point. @Darran Rowe, thanks. But we prefer using VC tool chain due to many advantages (over this minor disadvantage of using C++11 complex). @Darran Rowe: Thanks. I know that previously, there haven't been ABI breaking changes in updates. However, the previous policy was also to not include e.g. C++ standard conformance improvements in updates, so I would like to know if the policy on ABI breaking changes in updates has changed? :) This because it allows me, as an eager consumer of new experimental stuff (like modules) ;) , to update Visual Studio on my machine and experiment, while the other members on my team (if they stay without updating) are unaffected. How to use core checker? I have downloaded this package and what do I need to do next? @Predelnik, @Denis: Yes, there will be a blog post soon about using the C++ Core Checkers. It's pretty easy though: once you install the NuGet package in your project, just enable Code Analysis in the project properties (last item on the properties page.) The C++ Core Checkers will then run with the regular code analysis checkers when you build. @Mats Taraldsvik, @Jakko: Darran Rowe's comments are spot-on. With regards to conformance changes in updates: we need to make our compiler conform to the standard, but we also don't want to make any breaking changes. When we do make breaking changes we try to make them source breaking only (not ABI or binary breaking) and with off-by-default warnings when possible. You can see the list of Update 1 compiler breaking changes here: msdn.microsoft.com/…/mt612856.aspx @Mats Taraldsvik: Well, until we get an official response from Microsoft, then we can only speculate. But from the features that are left to implement, there are none which would really cause the name mangling system to really change. So the real problem is whether the STL gets modified, since that is where the real breakage between VC versions has normally been. @Jakko: Well, if it helps any, the Clang/C2 only changes one specific part of the toolset. When you run cl.exe, then it does the parsing of the source using c1.dll or c1xx.dll, it then passes this output to c2.dll which does the code generation. What the Clang/C2 stuff does is replaces the very first bit, the source code parsing with c1.dll or c1xx.dll with the clang frontend, it still uses c2.dll as the code generator. Of course, the rest of the toolset will also be the same and it will output the codeview (pdb) files as debug output too. So using this Clang/C2 integration will produce object files that are binary compatible with those compiled with cl.exe, it is just aimed at cross platform development where you want to use the same compiler to ensure source compatibility. @Darran Rowe, I understand the anthem 'Clang is unprecedentedly the best compiler ever' and VC compilers are old school and faulty. But on VisualC blog, indirectly proposing the notion that Visual C team at Microsoft should never implement full set of ISO C99 features and everyone should ride the clang bandwagon is not very helpful. One may bring up the same argument for any C++14/C++17 feature which clang has implemented first. This way VC will never evolve in terms of standard libraries implementation. VisualC team should realize the requirement from consumer space and provide the missing C standard library regardless of alternative solutions, why? because it is an 'ISO standard'. To discuss llvm/Clang features, lets use the related Google blogs/forums. This place is to encourage the work that VC team has done, wishes/gripes that 'users of VC' might have and future expectation of 'VC users'. I personally avoid Google vs. Microsoft childish debates and have no hidden motive to change people mind about their technology choice, as I use technology stacks from both organization based on the platform and project I am working on. Both have done excellent work in different areas. Any ETA for an implementation of the TR optional class. I was sort of hoping it would be in update one but I guess not! squaloghepardo: Did you report that CRT bug on Connect? What's the bug number? Mats Taraldsvik, Darran Rowe: We are trying very, very hard to preserve binary compatibility in the STL, even as we're delivering post-RTM fixes for the first time since 2010 SP1, and (in Update 2) post-RTM features for the first time since 2008 SP1. David Hunter: No ETA for optional yet. We're currently focused on catching up with what's already been voted into the C++17 Working Paper. You'll see more Technical Specifications implemented over time (we've already got Filesystem, and part of Concurrency will be next). Please update the web compiler here: webcompiler.cloudapp.net Dear Microsoft, I installed Update 1 RTM last Tuesday and dared to set Options->Text Editor->C/C++->Experimental->Browsing/Navigation->Enable New Database Engine to "True". As a result the following "features" in the context menu of the code editor do not work any longer: Peek Definition, Go To Definition, Go To Declaration, Find All References, and View Call Hierarchy. The key commands don't work either. For example, the Peek Definition window now just says "Error / A definition for the symbol '(null)' could not be located.". The other four "features" do exactly nothing. So far, so bad. But it gets worse: when I set the option back to what is was before ("False"), the problem remains! How can that be? Uninstalling Update 1 does not help. Uninstalling and reinstalling VS with Update 1 does not help. I can try what I want, these features just do not work any longer. Microsoft, I demand to know how I can get these things back. I don't have the time and nerve to fumble around any longer. Any ETA for string_view / string_span? [COMPILER BUG] The MSFT DX12 Samples do not compile anymore in release mode and give an internal compiler error! Steps to reproduce: -Download DX12 MiniEngine from: github.com/…/DirectX-Graphics-Samples -Open .MiniEngineModelViewerModelViewer_VS14.sln with VS2015 SP1 -Set Configuration to Release -Compile! Gives: program files (x86)microsoft visual studio 14.0vcincludexmemory0(909):> CL!InvokeCompilerPass()+0x2d4bd 1> CL!DllGetC2Telemetry()+0xae663 ps: I did't submit a bug report through msconnect yet… I'll do so later. I also receive a similar ICE from this Update 1 in one of my own projects: 1>c:program files (x86)microsoft visual studio 14.0vcincludeforward_list(1155):> link!InvokeCompilerPass()+0x2d4bd 1> link!DllGetC2Telemetry()+0xae663 1> I spent sometime trying to come with a sample I could submit without submitting the whole project. The error is in a library header so I can't exactly edit that. The only way around it was to stop using forward_list and switch to list. @Jakko: Actually, I think you have gotten the wrong end of the stick. First, I'm not proposing anything, directly or otherwise. Secondly, Clang/C2 is actually created by Microsoft themselves, and it is installable via VS. The reason behind this is that it allows people to write cross platform apps (for Android, iOS and Windows Mobile) much easier, and for Windows targets, it then allows you to use the full Visual Studio tool set to debug/profile it. For targeting the desktop target, if you install the Clang/C2 then it will provide a selectable platform toolset named "Clang 3.7 with Microsoft CodeGen (v140_clang_3_7)". So this is fully supported by Microsoft themselves, and I have also seen them state that the usage of Clang front end is useful as a stopgap to be able to use features that are currently unavailable in VC. As for the cl frontend, that isn't going anywhere. It isn't losing support and it is going to keep being updated. Microsoft have clearly stated that they are going to fully support all of the C++ standards, including the TSs. But they have also clearly stated that they have needed to rewrite the compiler internals to get it to be fully conformant. Also, for the full C11 conformance, again, where did I even imply that Microsoft shouldn't complete their support? I was just giving a solution to a problem that works today. @ STL: connect.microsoft.com/…/bug-in-sntscanf-s camhusmj38: Does your ICE repro without LTCG (/GL)? If so, can you repro it with a preprocessed file? If so, you can submit the preprocessed file + command line. Darran Rowe: You said "Microsoft have clearly stated that they are going to fully support all of the C++ standards, including the TSs." but that isn't entirely correct. Yes, we're trying to achieve complete conformance to C++11/14/17. But Technical Specifications aren't Standards, and we haven't promised to implement every TS. We might hold off on implementing some TSes until their contents are voted into the Standard's Working Paper, and we might not implement some TSes at all (to pick a random example, we might or might not implement Transactional Memory). not squaloghepardo: That _sntscanf_s() bug (VSO#144368/Connect#1773279) has been fixed in the Universal CRT maintained by Windows, which will arrive in a VS 2015 Update. I've pinged our CRT maintainer, James McNellis, since he knows when the next UCRT update will appear in VS. @ STL Thanks for your reply. It is kinda sad tho that the fix is not in this update since the bug got fixed in early October, that is three months ago… I fear that the next update for VS and therefore the bugfix will not be in the near feature, aka wait at least for another few months :( @STL: Thank you for the suggestion, I was able to reproduce it with just the precompiled header, the command line and a simple test function. connect.microsoft.com/…/internal-compiler-error The error is in a different header now. @Darran Rowe, this is so unfortunate that you are trying to help but it keeps turning out to be as hindrance for people requesting for C-related features, aimed for VisualC team. The situation is this: 1. I am requesting VisualC team to 'consider' implementing an C99 feature (complex.h) of ISO standard in VC compiler and in reply, you are proposing alternative solution to use Clang. If you search google or github 'C99 microsoft' you will find enormous references to this kind of statements 'microsoft has clearly stated that they will never implement c99..', but after 16 years, they did! So I hope in next 16 years they will implement the rest of the standard with some parts of c11 as well. But if audience keep interrupting / shooting down any C-related request proposed to VisualC guys with 'use clang' argument (which is kind of rude BTW), that will delay things even further which is not good for anyone's business. 2. Like I mentioned previously, I use Clang for Unix development. I use VC for Windows development. Not everyone has same workflow and you can't generalize whole world's workflows. The requirement/feature-request is to have ISO 'C' standard implemented in VC compilers in addition to ISO 'C++' standard. If this is not their priority at this point in 2015, let that be on the record. This is my viewpoint. If history has taught us anything, many people appreciate when any team at Microsoft embrace some ISO standard and nobody admires when they deny with any justification. @Jakko: Well, it really seems you are either trying to find the worst in what I write without actually knowing my standpoint, or just totally ignoring what I have written. But lets just look at the core issue here of C support. I do not know how you managed to equate my suggestion as the VC team to not complete C11 support. In fact, I am wondering if you are using my posts as a way to try to drag out your point. I have historically been for Visual C++ to complete the C support too. Secondly, I clearly also stated that the use of Clang/C2 was a STOPGAP measure. The dictionary definition of stopgap is "A temporary way of dealing with a problem or satisfying a need", in other words, my suggestion was to use the Clang frontend until the VC frontend can compile C11 features. The real implication here is that I not only am hopeful that they will complete C11 support in the future, but I actually want them to. Thirdly, if you want to know the VC team's view latest mention of C11 support, then channel9.msdn.com/…/038 is when they broached the subject last. I'll let you watch that to discover what they said themselves. Finally, you mentioned a change in workflow. Have you actually checked the actual Visual Studio tooling? Well, either way as a major thing to take away, statements like "your best bet is to use xxx" is not the same thing as "Microsoft shouldn't implement newer C standards". When people say that, normally it is purely based on the current state of things, nothing more. Also, to repeat myself, I am definitely not trying to say that the VC team shouldn't implement the newer standards. If you took my suggesting that you use Clang right now as rude, then I apologise, but as I have hopefully made clear that I only ever wanted to mean that it is your current best work around, and nothing more. @Darran Rowe, I am trying to make my view point clear as well and not dragging it. Perhaps at some point in future when some future C++ standard require C11 by reference, then they might consider it. But for the remaining C99 feature which C++11/14 does not require at this point (such as complex.h), I hope they will consider those for sake of completing the ISO standard. Thanks for the link and clarifications. Hi, is there a way to disable the installation of IncrediBuild? We already have an IncrediBuild 7.1 system running, but with a different patch level. We cannot easily upgrade our whole IncrediBuild cluster and I would make experiments with Visual Studio 2015 without IncrediBuild? Thanks and Regards, Fp Any small bones to throw to us C++/CLI developers in Update 1? constexpr Breaking change: With Update-1 RC and earlier, the following code was fine: static constexpr char * const monthName[] = {"JANUARY", "FEBRUARY", "MARCH" …. "DECEMBER"}; const char *pszMonth = monthName[n]; int c = strcmp(psz, pszMonth); with Update-1 RTM, the value of pszMonth is "JANU" instead of a pointer to "JANUARY". The workaround is to change constexpr to cosnt, as in: static const char * const monthName[] = {"JANUARY", "FEBRUARY", "MARCH" …. "DECEMBER"}; @STL: I missed your last comment directed at me. Thanks for the correction. I assumed that striving for full standards conformance also extended to the TSs. I also meant to thank you for the information that you trying to preserve binary compatibility in the STL. If you already have installed Visual Studio 2015, then is "Update 1" available as a quickly installed upgrade, or do you have to reinstall? If you have to reinstall everything, are you losing settings or are they kept? @Tom it's available as an update. Whether you would consider it "quickly installed" depends on what you mean by "quickly". It's not complicated to install, but it's not fast either. Please, someone from MSFT at least acknowledge @Karsten's issue. I'm experiencing the same, and this is on a completely fresh Win10 install + VS2015 (Update 1 pre-applied). This is really a devastating issue, as I don't want to reinstall Windows yet again just to work around it, but IntelliSense and go-to-definition in particular are largely the reason I use an IDE instead of an editor in the first place. This _needs_ to be addressed.
https://blogs.msdn.microsoft.com/vcblog/2015/12/01/visual-studio-2015-update-1-is-here/
CC-MAIN-2018-26
refinedweb
3,067
64.41
[SOLVED] Qt 5: handling of CSS imports in QtHelp Hi, I use QtHelp for my application's help. It's all very simple HTML and CSS code. In my help's home page, I link a CSS file as follows: @<link href="res/stylesheet.css" rel="stylesheet" type="text/css"/>@ Then, in my res/stylesheet.css file, I import another CSS file as follows: @@import "/doc/res/common.css";@ /doc is the root folder for my application's help and it's how QtHelp (in Qt 4.8) used to require the import to be done (see this "previous thread of mine":. However, now, the above @import statement just doesn't work, meaning that my application's help doesn't get styled anymore. So, was I doing the right thing before and/or have things changed in Qt 5? What is certain is that if I include my CSS code directly in res/stylesheet.css, then everything is fine, telling me that the issue is with @import... Anyway, any help would be much appreciated... Cheers, Alan. FWIW, I just came back to the above issue and found out what happened. Basically, the syntax changed (?) between Qt 4 and Qt 5. So, rather than having: @@import "/doc/res/common.css";@ We should now have: @@import "qthelp://namespace/virtualFolder/doc/res/common.css";@ Now, I wish it had been documented somewhere...
https://forum.qt.io/topic/23202/solved-qt-5-handling-of-css-imports-in-qthelp
CC-MAIN-2018-39
refinedweb
229
77.33
11, 2019 DONALD J. TRUMP, Plaintiff,v.COMMITTEE ON WAYS AND MEANS, UNITED STATES HOUSE OF REPRESENTATIVES, et al., Defendants. MEMORANDUM OPINION CARL J. NICHOLS UNITED STATES DISTRICT JUDGE On July 8, 2019, New York's governor signed the Tax Returns Released Under Specific Terms Act (“TRUST Act”) into law. Am. Compl., Dkt. 30, ¶ 61; see also N.Y. Tax Law § 697(f-1), (f-2) (2019) (codifying the TRUST Act). The TRUST Act amends New York's tax laws to authorize the chairperson of one of three congressional committees, including the House Committee on Ways and Means, to request the New York state tax returns of the President of the United States, among other elected officials. Tax § 697(f-1). If that request is made in writing and certain requirements are met, the Commissioner of the New York State Department of Taxation and Finance (“Commissioner”) is required to produce the records to the relevant committee. Id. To date, no committee chairperson has made such a request. On July 23, 2019, however, citing concerns that the Chairman of the House Ways and Means Committee might soon attempt to employ the TRUST Act to procure his New York returns, Donald J. Trump filed this action. See generally Compl., Dkt. 1. Mr. Trump alleges that any request made for his state tax returns would violate Article I of the U.S. Constitution and the Rules of the U.S. House of Representatives. Id. ¶¶ 69-72. And he alleges that the TRUST Act violates the First Amendment because it was enacted to discriminate and retaliate against his politics and speech. Id. ¶¶ 73-76. Mr. Trump also filed an Emergency Application for Relief Under the All Writs Act. Dkt. 6; see also 28 U.S.C. § 1651 (2018) (permitting courts to “issue all writs necessary or appropriate in aid of their respective jurisdictions”). Mr. Trump's Emergency Application seeks to preserve the status quo by preventing the disclosure of his state tax returns while the Parties litigate the legality of a request for them, if and when such a request is made. Following briefing and argument on the Emergency Application, as well as submissions from the Parties regarding how the case should proceed, the Court largely adopted the New York Defendants' proposal that the Court “rule on [their personal jurisdiction and venue] defenses as a threshold matter in consideration for which the Commissioner [would] voluntarily agree to defer responding to any Committee request for a period of one week following the Court's ruling.” Joint Status Report, Dkt. 22, at 4. The Court thus ordered that (1) the New York Defendants could, on an expedited basis, move to dismiss the Complaint for lack of personal jurisdiction and improper venue; (2) the New York Defendants would not transmit any of Mr. Trump's tax information that Chairman Neal might request while that motion is pending and for a period of one week from the day of the Court's decision on the motion; and (3) the New York Defendants would notify the Court if Chairman Neal made such a request during that same period. Order (Aug. 1, 2019), Dkt. 25, at 3-4. Thereafter, the New York Defendants moved to dismiss for lack of personal jurisdiction and improper venue, and that motion is fully briefed. See generally N.Y. Defs.' Mot. to Dismiss Am. Compl. for Lack of Personal Jurisdiction & Improper Venue (“Mot.”), Dkt. 36; Pl.'s Mem. of P. & A. in Opp'n to N.Y. Defs.' Mot. (“Opp'n”), Dkt. 37; N.Y. Defs.' Reply Mem. of Law in Further Supp. of Their Mot. (“Reply”), Dkt. 39. For the reasons that follow, the Court concludes that it does not presently have jurisdiction over either New York Defendant. Mr. Trump bears the burden of establishing personal jurisdiction, but his allegations do not establish that the District of Columbia's long-arm statute is satisfied here with respect to either Defendant. Mr. Trump has also not demonstrated that jurisdictional discovery is warranted. Mr. Trump may renew his claims against the New York Defendants should future events trigger one or more provisions of the D.C. long-arm statute, and he may, of course, sue either New York Defendant in another forum (presumably in New York). I. Background New York law generally requires that state tax returns be held confidentially and permits their disclosure in only certain enumerated exceptions. See, e.g., Tax § 697(e) (secrecy requirement); id. § 697(f) (permitting disclosure to cooperate with certain U.S. and state proceedings). The TRUST Act adds another exception. It authorizes the chairpersons of the Committee on Ways and Means of the U.S. House of Representatives (“Committee”), the Committee on Finance of the U.S. Senate, and the Joint Committee on Taxation to request from the Commissioner “any current or prior year [state tax] reports or returns” of “the president of the United States, vice-president of the United States, member of the United States Congress representing New York state” or other public official enumerated in the statute. Id. § 697(f-1). Such a request must “certif[y] in writing”: (1) that the requested tax “reports or returns have been requested related to, and in furtherance of, a legitimate task of the Congress”; (2) that the requesting committee has “made a written request to the United States secretary of the treasury for related federal returns or return information, pursuant to 25 U.S.C. [§] 6103(f)”; and (3) that any inspection or submission to another committee or to the full U.S. House of Representatives or Senate be done “in a manner consistent with federal law.” Id. § 697(f-2). Assuming the request includes those certifications, the Commissioner must produce the requested returns with redactions for “any copy of a federal return (or portion thereof) attached to, or any information on a federal return that is reflected on, such report or return.” Id. § 697(f-1). On July 23, 2019, following media reports of increasing pressure on Chairman Neal to request Mr. Trump's state tax returns, see Compl. ¶¶ 6, 62-68, Mr. Trump filed this action against New York Attorney General Letitia James, Commissioner Michael R. Schmidt (collectively, “New York Defendants”), and the Committee. See generally Id. Mr. Trump asserts two claims. In Count I, he claims that a request under the TRUST Act would violate Article I of the U.S. Constitution and the Rules of the House because the request for his New York state tax returns would lack a legitimate legislative purpose. Am. Compl. ¶¶ 73-76. In Count II, Mr. Trump claims that the TRUST Act itself violates the First Amendment and that the Committee and New York Defendants would violate his First Amendment rights by employing it to produce his state tax returns to the Committee. Id. ¶¶ 77-81. Count II is the only claim asserted against the New York Defendants. Id. Mr. Trump also filed an Emergency Application for Relief Under the All Writs Act, asking the Court “to preserve the status quo” to prevent his claims from becoming ripe and then moot almost instantaneously without notice to him or the Court, thereby depriving the Court of jurisdiction. Mem. of P. & A. in Supp. of Pl.'s Emergency Appl. for Relief Under the All Writs Act, Dkt. 6-1, at 5-6. Following briefing and oral argument on the Emergency Application, the Court ordered the Parties to meet and confer in light of the Court's stated goals of (1) “ensuring that Mr. Trump's claims do not become moot before they can be litigated”; (2) “treading as lightly as possible, if at all, on separation of powers and Speech or Debate Clause concerns”; and (3) “adjudicating . . . this dispute only when it is actually ripe and has a fuller record than presently exists.” July 29, 2019 Hr'g Tr., Dkt. 23, at 53-54; see Min. Order (July 29, 2019). The Parties were unable to reach agreement and instead filed alternative proposals for how the case should proceed. The New York Defendants, for their part, proposed that the Commissioner would not respond to any request for Mr. Trump's tax returns while the Court considered and ruled on their forthcoming motion to dismiss for lack of personal jurisdiction and improper venue. Joint Status Report, Dkt. 22, at 4. The Court largely adopted this proposal and, on August 1, 2019, ordered that (1) the New York Defendants could move to dismiss the Complaint for lack of personal jurisdiction over them and for improper venue on an expedited basis; (2) “during the pendency of the New York Defendants' Motion and for a period of one week from the Court's decision . . ., the New York Defendants shall not deliver to the Committee any information concerning Mr. Trump that may be requested by Chairman Neal under the TRUST Act”; and (3) the New York Defendants shall notify the Court if Chairman Neal made a request during that same one-week time period. Order (Aug. 1, 2019), Dkt. 25, at 3-4. After the New York Defendants filed their initial Motion to Dismiss, Mr. Trump filed an Amended Complaint that asserts the same two substantive claims as his original Complaint, but adds as defendants Chairman Neal and Andrew Grossman, the Committee's Chief Tax Counsel, and adds factual allegations related to the New York Defendants' connections to this forum. See generally Am. Compl. The New York Defendants renewed their Motion to Dismiss on August 29, 2019. II. Legal Standard A federal court has jurisdiction over a defendant “who is subject to the jurisdiction of a court of general jurisdiction in the state where the district court is located.” Fed.R.Civ.P. 4(k)(1)(A). Thus, if a District of Columbia court could exercise jurisdiction over the New York Defendants, then so can this Court. E.g., West v. Holder, 60 F.Supp.3d 190, 193 (D.D.C. 2014). There are two types of personal jurisdiction: “[1] general or all-purpose jurisdiction[] and [2] specific or case-linked jurisdiction.” Goodyear Dunlop Tires Operations, S.A. v. Brown, 564 U.S. 915, 919 (2011). “For an individual, the paradigm forum for the exercise of general jurisdiction is the individual's domicile.” Daimler AG v. Bauman, 571 U.S. 117, 137 (2014). Specific jurisdiction, on the other hand, “aris[es] out of or relate[s] to the defendant's contacts with the forum.” Id. at 127 (quoting Helicopteros Nacionales de Colombia, S.A. v. Hall, 466 U.S. 408, 414 n.8 (1984)). With respect to specific jurisdiction, the Court “must engage in a two-part inquiry: . . . first examine whether jurisdiction is applicable under the [D.C.] long-arm statute and then determine whether a finding of jurisdiction satisfies the constitutional requirements of due process.” GTE New Media Servs. Inc. v. BellSouth Corp., 199 F.3d 1343, 1347 (D.C. Cir. 2000) (citation omitted). The D.C. long-arm statute authorizes specific jurisdiction “over a person, who acts directly or by an agent, as to a claim for relief arising from” certain contacts that person may have with the forum. D.C. Code § 13-423(a) (2019). As relevant here, a defendant's contacts with the District of Columbia can establish specific jurisdiction if the claim arises from the defendant's: (1) transacting any business [i] regularly does or solicits business, [ii] engages in any other persistent course of conduct, or [iii] derives substantial revenue
http://dc.findacase.com/research/wfrmDocViewer.aspx/xq/fac.20191111_0001414.DDC.htm/qx
CC-MAIN-2020-40
refinedweb
1,909
55.13
Tutorial: Building Redux in TypeScript with Angular Reading Time: 29 minutes tl;dr – In this post we’ll be looking at a data-architecture pattern called Redux. In this post we’re going to discuss: - the ideas behind Redux, - build our own mini version of the Redux Store and - hook it up to Angular. You can get the completed code here You can try the demo here For many Angular projects we can manage state in a fairly direct way: We tend to grab data from services and render them in components, passing values down the component tree along the way. Managing our apps in this way works fine for smaller apps, but as our apps grow, having multiple components manage different parts of the state becomes cumbersome. For instance, passing all of our values down our component tree suffers from the following downsides: Intermediate property passing – In order to get state to any component we have to pass the values down through inputs. This means we have many intermediate components passing state that it isn’t directly using or concerned about Inflexible refactoring – Because we’re passing inputs down through the component tree, we’re introducing a coupling between parent and child components that often isn’t necessary. This makes it more difficult to put a child component somewhere else in the hierarchy because we have to change all of the new parents to pass the state State tree and DOM tree don’t match – The “shape” of our state often doesn’t match the “shape” of our view/component hierarchy. By passing all data through the component tree via props we run into difficulties when we need to reference data in a far branch of the tree State throughout our app – If we manage state via components, it’s difficult to get a snapshot of the total state of our app. This can make it hard to know which component “owns” a particular bit of data, and which components are concerned about changes Pulling data out of our components and into services helps a lot. At least if services are the “owners” of our data, we have a better idea of where to put things. But this opens a new question: what are the best practices for “service-owned” data? Are there any patterns we can follow? In fact, there are. In this post, we’re going to discuss a data-architecture pattern called Redux which was designed to help with these issues. We’ll implement our own version of Redux which will store all of our state in a single place. This idea of holding all of our application’s state in one place might sound a little crazy, but the results are surprisingly delightful. Redux If you haven’t heard of Redux yet you can read a bit about it on the official website. Web application data architecture is evolving and the traditional ways of structuring data aren’t quite adequate for large web apps. Redux has been extremely popular because it’s both powerful and easy to understand. Data architecture can be a complex topic and so Redux’s best feature is probably its simplicity. If you strip Redux down to the essential core, Redux is fewer than 100 lines of code. We can build rich, easy to understand, web apps by using Redux as the backbone of our application. But first, let’s walk through how to write a minimal Redux and later we’ll work out patterns that emerge as we work out these ideas in a larger app. There are several attempts to use Redux or create a Redux-inspired system that works with Angular. Two notable examples are: ngrxis a Redux-inspired architecture that is heavily observables-based. angular2-reduxuses Redux itself as a dependency, and adds some Angular helpers (dependency-injection, observable wrappers). Here we’re not going to use either. Instead, we’re going to use Redux directly in order to show the concepts without introducing a new dependency. That said, both of these libraries may be helpful to you when writing your apps. Redux: Key Ideas The key ideas of Redux are this: - All of your application’s data is in a single data structure called the state which is held in the store - Your app reads the state from this store - This store is never mutated directly - User interaction (and other code) fires actions which describe what happened - A new state is created by combining he old state and the action by a function called the reducer. If the above bullet list isn’t clear yet, don’t worry about it – putting these ideas into practice is the goal of the rest of this post. Table of Contents - Core Redux Ideas - Storing Our State - A Messaging App - Using Redux in Angular - Planning Our App - Setting Up Redux - Providing the Store - Bootstrapping the App - The AppComponent - What’s Next - What’s Next - References Core Redux Ideas What’s a reducer? Let’s talk about the reducer first. Here’s the idea of a reducer: it takes the old state and an action and returns a new state. A reducer must be a pure function. That is: - It must not mutate the current state directly - It must not use any data outside of its arguments Put another way, a pure function will always return the same value, given the same set of arguments. And a pure function won’t call any functions which have an effect on the outside world, e.g. no database calls, no HTTP calls, and no mutating outside data structures. Reducers should always treat the current state as read-only. A reducer does not change the state instead, it returns a new state. (Often this new state will start with a copy of old state, but let’s not get ahead of ourselves.) Let’s define our very first reducer. Remember, there are three things involved: - An Action, which defines what to do (with optional arguments) - The state, which stores all of the data in our application - The Reducerwhich takes the stateand the Actionand returns a new state. Defining Action and Reducer Interfaces Since we’re using TypeScript we want to make sure this whole process is typed, so let’s setup an interface for our Action and our Reducer: The Action Interface Our Action interface looks like this: interface Action { type: string; payload?: any; } Notice that our Action has two fields: typeand payload The type will be an identifying string that describes the action like INCREMENT or ADD_USER. The payload can be an object of any kind. The ? on payload? means that this field is optional. The Reducer Interface Our Reducer interface looks like this: interface Reducer<T> { (state: T, action: Action): T; } Our Reducer is using a feature of TypeScript called generics. In this case type T is the type of the state. Notice that we’re saying that a valid Reducer has a function which takes a state (of type T) and an action and returns a new state (also of type T). Creating Our First Reducer The simplest possible reducer returns the state itself. (You might call this the identity reducer because it applies the identity function on the state. This is the default case for all reducers, as we will soon see). let reducer: Reducer<number> = (state: number, action: Action) => { return state; }; Notice that this Reducer makes the generic type concrete to number by the syntax Reducer<number>. We’ll define more sophisticated states beyond a single number soon. We’re not using the Action yet, but let’s try this Reducer just the same. Running the examples in this post You can find the code for this post on Github. In this first section, these examples are run outside of the browser and run by node.js. Because we’re using TypeScript in these examples, you should run them using the commandline tool ts-node, (instead of nodedirectly). You can install ts-nodeby running: npm install -g ts-node Or by doing an npm installin the angular2-redux-chatdirectory and then calling ./node_modules/.bin/ts-nodet For instance, to run the example above you might type (not including the $): $ cd angular2-redux-chat/minimal/tutorial $ npm install $ ./node_modules/.bin/ts-nodet 01-identity-reducer.ts Use this same procedure for the rest of the code in this post until we instruct you to switch to your browser. Running Our First Reducer Let’s put it all together and run this reducer: interface Action { type: string; payload?: any; } interface Reducer<T> { (state: T, action: Action): T; } let reducer: Reducer<number> = (state: number, action: Action) => { return state; }; console.log( reducer(0, null) ); // -> 0 And run it: $ cd code/redux/redux-chat/tutorial $ ./node_modules/.bin/ts-node 01-identity-reducer.ts 0 It seems almost silly to have that as a code example, but it teaches us our first principle of reducers: By default, reducers return the original state. In this case, we passed a state of the number 0 and a null action. The result from this reducer is the state 0. But let’s do something more interesting and make our state change. Adjusting the Counter With actions Eventually our state is going to be much more sophisticated than a single number. We’re going to be holding the all of the data for our app in the state, so we’ll need better data structure for the state eventually. That said, using a single number for the state lets us focus on other issues for now. So let’s continue with the idea that our state is simply a single number that is storing a counter. Let’s say we want to be able to change the state number. Remember that in Redux we do not modify the state. Instead, we create actions which instruct the reducer on how to generate a new state. Let’s create an Action to change our counter. Remember that the only required property is a type. We might define our first action like this: let incrementAction: Action = { type: 'INCREMENT' } We should also create a second action that instructs our reducer to make the counter smaller with: let decrementAction: Action = { type: 'DECREMENT' } Now that we have these actions, let’s try using them in our reducer: let reducer: Reducer<number> = (state: number, action: Action) => { if (action.type === 'INCREMENT') { return state + 1; } if (action.type === 'DECREMENT') { return state - 1; } return state; }; And now we can try out the whole reducer: let incrementAction: Action = { type: 'INCREMENT' }; console.log( reducer(0, incrementAction )); // -> 1 console.log( reducer(1, incrementAction )); // -> 2 let decrementAction: Action = { type: 'DECREMENT' }; console.log( reducer(100, decrementAction )); // -> 99 Neat! Now the new value of the state is returned according to which action we pass into the reducer. Reducer switch Instead of having so many if statements, the common practice is to convert the reducer body to a switch statement: let reducer: Reducer<number> = (state: number, action: Action) => { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; // <-- dont forget! } }; let incrementAction: Action = { type: 'INCREMENT' }; console.log(reducer(0, incrementAction)); // -> 1 console.log(reducer(1, incrementAction)); // -> 2 let decrementAction: Action = { type: 'DECREMENT' }; console.log(reducer(100, decrementAction)); // -> 99 // any other action just returns the input state let unknownAction: Action = { type: 'UNKNOWN' }; console.log(reducer(100, unknownAction)); // -> 100 Notice that the default case of the switch returns the original state. This ensures that if an unknown action is passed in, there’s no error and we get the original state unchanged. Q: Wait, all of my application state is in one giant switchstatement? A: Yes and no. If this is your first exposure to Redux reducers it might feel a little weird to have all of your application state changes be the result of a giant switch. There are two things you should know: - Having your state changes centralized in one place can help a ton in maintaining your program, particularly because it’s easy to track down where the changes are happening when they’re all together. (Furthermore, you can easily locate what state changes as the result of any action because you can search your code for the token specified for that action’s type) - You can (and often do) break your reducers down into several sub-reducers which each manage a different branch of the state tree. We’ll talk about this later. Action “Arguments” In the last example our actions contained only a type which told our reducer either to increment or decrement the state. But often changes in our app can’t be described by a single value – instead we need parameters to describe the change. This is why we have the payload field in our Action. In this counter example, say we wanted to add 9 to the counter. One way to do this would be to send 9 INCREMENT actions, but that wouldn’t be very efficient, especially if we wanted to add, say, 9000. Instead, let’s add a PLUS action that will use the payload parameter to send a number which specifies how much we want to add to the counter. Defining this action is easy enough: let plusSevenAction = { type: 'PLUS', payload: 7 }; Next, to support this action, we add a new case to our reducer that will handle a 'PLUS' action: let reducer: Reducer<number> = (state: number, action: Action) => { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; case 'PLUS': return state + action.payload; default: return state; } }; PLUS will add whatever number is in the action.payload to the state. We can try it out: console.log( reducer(3, { type: 'PLUS', payload: 7}) ); // -> 10 console.log( reducer(3, { type: 'PLUS', payload: 9000}) ); // -> 9003 console.log( reducer(3, { type: 'PLUS', payload: -2}) ); // -> 1 In the first line we take the state 3 and PLUS a payload of 7, which results in 10. Neat! However, notice that while we’re passing in a state, it doesn’t really ever change. That is, we’re not storing the result of our reducer’s changes and reusing it for future actions. Storing Our State Our reducers are pure functions, and do not change the world around them. The problem is, in our app, things do change. Specifically, our state changes and we need to keep the new state somewhere. In Redux, we keep our state in the store. The store has the responsibility of running the reducer and then keeping the new state. Let’s take a look at a minimal store: class Store<T> { private _state: T; constructor( private reducer: Reducer<T>, initialState: T ) { this._state = initialState; } getState(): T { return this._state; } dispatch(action: Action): void { this._state = this.reducer(this._state, action); } } Notice that our Store is generically typed – we specify the type of the state with generic type T. We store the state in the private variable _state. We also give our Store a Reducer, which is also typed to operate on T, the state type this is because each store is tied to a specific reducer. We store the Reducer in the private variable reducer. In Redux, we generally have 1 store and 1 top-level reducer per application. Let’s take a closer look at each method of our State: - In our constructorwe set the _stateto the initial state. getState()simply returns the current _state dispatchtakes an action, sends it to the reducer and then updates the value of _statewith the return value Notice that dispatch doesn’t return anything. It’s only updating the store’s state (once the result returns). This is an important principle of Redux: dispatching actions is a “fire-and-forget” maneuver. Dispatching actions is not a direct manipulation of the state, and it doesn’t return the new state. When we dispatch actions, we’re sending off a notification of what happened. If we want to know what the current state of the system is, we have to check the state of the store. Using the Store Let’s try using our store: // create a new store let store = new Store<number>(reducer, 0); console.log(store.getState()); // -> 0 store.dispatch({ type: 'INCREMENT' }); console.log(store.getState()); // -> 1 store.dispatch({ type: 'INCREMENT' }); console.log(store.getState()); // -> 2 store.dispatch({ type: 'DECREMENT' }); console.log(store.getState()); // -> 1 We start by creating a new Store and we save this in store, which we can use to get the current state and dispatch actions. The state is set to 0 initially, and then we INCREMENT twice and DECREMENT once and our final state is 1. Being Notified with subscribe It’s great that our Store keeps track of what changed, but in the above example we have to ask for the state changes with store.getState(). It would be nice for us to know immediately when a new action was dispatched so that we could respond. To do this we can implement the Observer pattern – that is, we’ll register a callback function that will subscribe to all changes. Here’s how we want it to work: - We will register a listener function using subscribe - When dispatchis called, we will iterate over all listeners and call them, which is the notification that the state has changed. Registering Listeners Our listener callbacks are a going to be a function that takes no arguments. Let’s define an interface that makes it easy to describe this: interface ListenerCallback { (): void; } After we subscribe a listener, we might want to unsubscribe as well, so lets define the interface for an unsubscribe function as well: interface UnsubscribeCallback { (): void; } Not much going on here – it’s another function that takes no arguments and has no return value. But by defining these types it makes our code clearer to read. Our store is going to keep a list of ListenerCallbacks let’s add that to our Store: class Store<T> { private _state: T; private _listeners: ListenerCallback[] = []; Now we want to be able to add to that list of _listeners with a subscribe function: subscribe(listener: ListenerCallback): UnsubscribeCallback { this._listeners.push(listener); return () => { // returns an "unsubscribe" function this._listeners = this._listeners.filter(l => l !== listener); }; } subscribe accepts a ListenerCallback (i.e. a function with no arguments and no return value) and returns an UnsubscribeCallback (the same signature). Adding the new listener is easy: we push it on to the _listeners array. The return value is a function which will update the list of _listeners to be the list of _listeners without the listener we just added. That is, it returns the UnsubscribeCallback that we can use to remove this listener from the list. Notifying Our Listeners Whenever our state changes, we want to call these listener functions. What this means is, whenever we dispatch a new action, whenever the state changes, we want to call all of the listeners: dispatch(action: Action): void { this._state = this.reducer(this._state, action); this._listeners.forEach((listener: ListenerCallback) => listener()); } The Complete Store We’ll try this out below, but before we do that, here’s the complete code listing for our new Store: class Store<T> { private _state: T; private _listeners: ListenerCallback[] = []; constructor( private reducer: Reducer<T>, initialState: T ) { this._state = initialState; } getState(): T { return this._state; } dispatch(action: Action): void { this._state = this.reducer(this._state, action); this._listeners.forEach((listener: ListenerCallback) => listener()); } subscribe(listener: ListenerCallback): UnsubscribeCallback { this._listeners.push(listener); return () => { // returns an "unsubscribe" function this._listeners = this._listeners.filter(l => l !== listener); }; } } Trying Out subscribe Now that we can let store = new Store<number>(reducer, 0); console.log(store.getState()); // -> 0 // subscribe let unsubscribe = store.subscribe(() => { console.log('subscribed: ', store.getState()); }); store.dispatch({ type: 'INCREMENT' }); // -> subscribed: 1 store.dispatch({ type: 'INCREMENT' }); // -> subscribed: 2 unsubscribe(); store.dispatch({ type: 'DECREMENT' }); // (nothing logged) // decrement happened, even though we weren't listening for it console.log(store.getState()); // -> 1 Above we subscribe to our store and in the callback function we’ll log subscribed: and then the current store state. Notice that the listener function is not given the current state as an argument. This might seem like an odd choice, but because there are some nuances to deal with, it’s easier to think of the notification of state changed as separate from the current state. Without digging too much into the weeds, you can read more about this choice here, here, and here. We store the unsubscribe callback and then notice that after we call unsubscribe() our log message isn’t called. We can still dispatch actions, we just won’t see the results until we ask the store for them. If you’re the type of person who likes RxJS and Observables, you might notice that implementing our own subscription listeners could also be implemented using RxJS. You could rewrite our Storeto use Observables instead of our own subscriptions. In fact, we’ve already done this for you and you can find the sample code in the file code/redux/redux-chat/tutorial/06b-rx-store.ts. Using RxJS for the Storeis an interesting and powerful pattern if you’re willing to us RxJS for the backbone of our application data. Here we’re not going to use Observables very heavily, particularly because we want to discuss Redux itself and how to think about data architecture with a single state tree. Redux itself is powerful enough to use in our applications without Observables. Once you get the concepts of using “straight” Redux, adding in Observables isn’t difficult (if you already understand RxJS, that is). For now, we’re going to use “straight” Redux and we’ll give you some guidance on some Observable-based Redux-wrappers at the end. The Core of Redux The above store is the essential core of Redux. Our reducer takes the current state and action and returns a new state, which is held by the store. Here’s our minimal TypeScript Redux stores in one image (click for larger version): There are obviously many more things that we need to add to build a large, production web app. However, all of the new ideas that we’ll cover are patterns that flow from building on this simple idea of an immutable, central store of state. If you understand the ideas presented above, you would be likely to invent many of the patterns (and libraries) you find in more advanced Redux apps. There’s still a lot for us to cover about day-to-day use of redux though. For instance, we need to know: - How to carefully handle more complex data structures in our state - How to be notified when our state changes without having to poll the state (with subscriptions) - How to intercept our dispatch for debugging (a.k.a. middleware) - How to compute derived values (with selectors) - How to split up large reducers into more manageable, smaller ones (and recombine them) - How to deal with asynchronous data While we’ll explain several of these in this post, if you want to go more in-depth with a Redux example with Angular two, checkout the Intermediate Redux chapter in ng-book 4 Let’s first deal with handling more complex data structures in our state. To do that, we’re going to need an example that’s more interesting than a counter. Let’s start building a chat app where users can send each other messages. A Messaging App In our messaging app, as in all Redux apps, there are three main parts to the data model: - The state - The actions - The reducer Messaging App state The state in our counter app was a single number. However in our messaging app, the state is going to be an object. This state object will have a single property, messages. messages will be an array of strings, with each string representing an individual message in the application. For example: // an example `state` value { messages: [ 'here is message one', 'here is message two' ] } We can define the type for the app’s state like this: interface AppState { messages: string[]; } Messaging App actions Our app will process two actions: ADD_MESSAGE and DELETE_MESSAGE. The ADD_MESSAGE action object will always have the property message, the message to be added to the state. The ADD_MESSAGE action object has this shape: { type: 'ADD_MESSAGE', message: 'Whatever message we want here' } The DELETE_MESSAGE action object will delete a specified message from the state. A challenge here is that we have to be able to specify which message we want to delete. If our messages were objects, we could assign each message an id property when it is created. However, to simplify this example, our messages are just simple strings, so we’ll have to get a handle to the message another way. The easiest way for now is to just use the index of the message in the array (as a proxy for the ID). With that in mind, the DELETE_MESSAGE action object has this shape: { type: 'DELETE_MESSAGE', index: 2 // <- or whatever index is appropriate } We can define the types for these actions by using the interface ... extends syntax in TypeScript: interface AddMessageAction extends Action { message: string; } interface DeleteMessageAction extends Action { index: number; } In this way our AddMessageAction is able to specify a message and the DeleteMessageAction will specify an index. Messaging App reducer Remember that our reducer needs to handle two actions: ADD_MESSAGE and DELETE_MESSAGE. Let’s talk about these individually. Reducing ADD_MESSAGE let reducer: Reducer<AppState> = (state: AppState, action: Action): AppState => { switch (action.type) { case 'ADD_MESSAGE': return { messages: state.messages.concat( (<AddMessageAction>action).message ), }; We start by switching on the action.type and handling the ADD_MESSAGE case. TypeScript objects already have a type, so why are we adding a typefield? There are many different ways we might choose to handle this sort of “polymorphic dispatch”. Keeping a string in a typefield (where typemeans “action-type”) is a straightforward, portable way we can use to distinguish different types of actions and handle them in one reducer. In part, it means that you don’t have to create a new interfacefor every action. That said, it would be more satisfying to be able to use reflection to switch on the concrete type. While this might become possible with more advanced type guards, this isn’t currently possible in today’s TypeScript. Broadly speaking, types are a compile-time construct and this code is compiled down to JavaScript and we can lose some of the typing metadata. That said, if switching on a typefield bothers you and you’d like to use language features directly, you could use the decoration reflection metadata. For now, a simple typefield will suffice. Adding an Item Without Mutation When we handle an ADD_MESSAGE action, we need to add the given message to the state. As will all reducer handlers, we need to return a new state. Remember that our reducers must be pure and not mutate the old state. What would be the problem with the following code? case 'ADD_MESSAGE': state.messages.push( action.message ); return { messages: messages }; // ... The problem is that this code mutates the state.messages array, which changes our old state! Instead what we want to do is create a copy of the state.messages array and add our new message to the copy. case 'ADD_MESSAGE': return { messages: state.messages.concat( (<AddMessageAction>action).message ), }; The syntax <AddMessageAction>actionwill cast our actionto the more specific type. That is, notice that our reducer takes the more general type Action, which does not have the messagefield. If we leave off the cast, then the compiler will complain that Actiondoes not have a field Instead, we know that we have an ADD_MESSAGEaction so we cast it to an AddMessageAction. We use parenthesis to make sure the compiler knows that we want to cast actionand not action.message. Remember that the reducer must return a new AppState. When we return an object from our reducer it must match the format of the AppState that was input. In this case we only have to keep the key messages, but in more complicated states we have more fields to worry about. Deleting an Item Without Mutation Remember that when we handle the DELETE_MESSAGE action we are passing the index of the item in the array as the faux ID. (Another common way of handling the same idea would be to pass a real item ID.) Again, because we do not want to mutate the old messages array, we need to handle this case with care: case 'DELETE_MESSAGE': let idx = (<DeleteMessageAction>action).index; return { messages: [ ...state.messages.slice(0, idx), ...state.messages.slice(idx + 1, state.messages.length) ] Here we use the slice operator twice. First we take all of the items up until the item we are removing. And we concatenate the items that come after. There are four common non-mutating operations: - Adding an item to an array - Removing an item from an array - Adding / changing a key in an object - Removing a key from an object The first two (array) operations we just covered. We’ll talk more about the object operations further down, but for now know that a common way to do this is to use Object.assign. As in: Object.assign({}, oldObject, newObject) // <-------<------------- You can think of Object.assignas merging objects in from the right into the object on the left. newObjectis merged into oldObjectwhich is merged into {}. This way all of the fields in oldObjectwill be kept, except for where the field exists in newObject. Neither oldObjectnor newObjectwill be mutated. Of course, handling all of this on your own takes great care and it is easy to make a mistake. This is one of the reasons many people use Immutable.js, which is a set of data structures that help enforce immutability. Trying Out Our Actions Now let’s try running our actions: let store = new Store<AppState>(reducer, { messages: [] }); console.log(store.getState()); // -> { messages: [] } store.dispatch({ type: 'ADD_MESSAGE', message: 'Would you say the fringe was made of silk?' } as AddMessageAction); store.dispatch({ type: 'ADD_MESSAGE', message: 'Wouldnt have no other kind but silk' } as AddMessageAction); store.dispatch({ type: 'ADD_MESSAGE', message: 'Has it really got a team of snow white horses?' } as AddMessageAction); console.log(store.getState()); // -> // { messages: // [ 'Would you say the fringe was made of silk?', // 'Wouldnt have no other kind but silk', // 'Has it really got a team of snow white horses?' ] } Here we start with a new store and we call store.getState() and see that we have an empty messages array. Next we add three messages to our store. For each message we specify the type as ADD_MESSAGE and we cast each object to an AddMessageAction. Finally we log the new state and we can see that messages contains all three messages. Our three dispatch statements are a bit ugly for two reasons: - we manually have to specify the typestring each time. We could use a constant, but it would be nice if we didn’t have to do this and - we’re manually casting to an AddMessageAction Instead of creating these objects as an object directly we should create a function that will create these objects. This idea of writing a function to create actions is so common in Redux that the pattern has a name: Action Creators. Action Creators Instead of creating the ADD_MESSAGE actions directly as objects, let’s create a function to do this for us: class MessageActions { static addMessage(message: string): AddMessageAction { return { type: 'ADD_MESSAGE', message: message }; } static deleteMessage(index: number): DeleteMessageAction { return { type: 'DELETE_MESSAGE', index: index }; } } Here we’ve created a class with two static methods addMessage and deleteMessage. They return an AddMessageAction and a DeleteMessageAction respectively. You definitely don’t have to use static methods for your action creators. You could use plain functions, functions in a namespace, even instance methods on an object, etc. The key idea is to keep them organized in a way that makes them easy to use. Now let’s use our new action creators: let store = new Store<AppState>(reducer, { messages: [] });?' ] } This feels much nicer! An added benefit is that if we eventually decided to change the format of our messages, we could do it without having to update all of our dispatch statements. For instance, say we wanted to add the time each message was created. We could add a created_at field to addMessage and now all AddMessageActions will be given a created_at field: class MessageActions { static addMessage(message: string): AddMessageAction { return { type: 'ADD_MESSAGE', message: message, // something like this created_at: new Date() }; } // .... Using Real Redux Now that we’ve built our own mini-redux you might be asking, “What do I need to do to use the real Redux?” Thankfully, not very much. Let’s update our code to use the real Redux now! If you haven’t already, you’ll want to run npm installin the code/redux/redux-chat/tutorialdirectory. The first thing we need to do is import Action, Reducer, and Store from the redux package. We’re also going to import a helper method createStore while we’re at it: import { Action, Reducer, Store, createStore } from 'redux'; Next, instead of specifying our initial state when we create the store instead we’re going to let the reducer create the initial state. Here we’ll do this as the default argument to the reducer. This way if there is no state passed in (e.g. the first time it is called at initialization) we will use the initial state: let initialState: AppState = { messages: [] }; let reducer: Reducer<AppState> = (state: AppState = initialState, action: Action) => { What’s neat about this is that the rest of our reducer stays the same! The last thing we need to do is create the store using the createStore helper method from Redux: let store: Store<AppState> = createStore<AppState>(reducer); After that, everything else just works! let store: Store<AppState> = createStore<AppState>(reducer);?' ] } Now that we have a handle on using Redux in isolation, the next step is to hook it up to our web app. Let’s do that now. Using Redux in Angular In the last section we walked through the core of Redux and showed how to create reducers and use stores to manage our data in isolation. Now it’s time to level-up and integrate Redux with our Angular components. In this section we’re going to create a minimal Angular app that contains just a counter which we can increment and decrement with a button. By using such a small app we can focus on the integration points between Redux and Angular and then we can move on to a larger app in the next section. But first, let’s see how to build this counter app! Here we are going to be integrating Redux directly with Angular without any helper libraries in-between. There are several open-source libraries with the goal of making this process easier, and you can find them in the references section below. That said, it can be much easier to use those libraries once you understand what is going on underneath the hood, which is what we work through here. Planning Our App If you recall, the three steps to planning our Redux apps are to: - Define the structure of our central app state - Define actions that will change that state and - Define a reducer that takes the old state and an action and returns a new state. For this app, we’re just going to increment and decrement a counter. We did this in the last section, and so our actions, store, and reducer will all be very familiar. The other thing we need to do when writing Angular apps is decide where we will create components. In this app, we’ll have a top-level AppComponent which will have one component, the AppComponent which contains the view we see in the screenshot. At a high level we’re going to do the following: - Create our Storeand make it accessible to our whole app via dependency injection Storeand display them in our components - When something changes (a button is pressed) we will dispatch an action to the Store. Enough planning, let’s look at how this works in practice! Setting Up Redux Defining the Application State Let’s take a look at our AppState: export interface AppState { counter: number; }; Here we are defining our core state structure as AppState – it is an object with one key, counter which is a number. In the next example (the chat app) we’ll talk about how to have more sophisticated states, but for now this will be fine. Defining the Reducers Next lets define the reducer which will handle incrementing and decrementing the counter in the application state: import { INCREMENT, DECREMENT } from './counter.actions'; const initialState: AppState = { counter: 0 }; // Create our reducer that will handle changes to the state export const counterReducer: Reducer<AppState> = (state: AppState = initialState, action: Action): AppState => { switch (action.type) { case INCREMENT: return Object.assign({}, state, { counter: state.counter + 1 }); case DECREMENT: return Object.assign({}, state, { counter: state.counter - 1 }); default: return state; } }; We start by importing the constants INCREMENT and DECREMENT, which are exported by our action creators. They’re just defined as the strings 'INCREMENT' and 'DECREMENT', but it’s nice to get the extra help from the compiler in case we make a typo. We’ll look at those action creators in a minute. The initialState is an AppState which sets the counter to 0. The counterReducer handles two actions: INCREMENT, which adds 1 to the current counter and DECREMENT, which subtracts 1. Both actions use Object.assign to ensure that we don’t mutate the old state, but instead create a new object that gets returned as the new state. Since we’re here, let’s look at the action creators Defining Action Creators Our action creators are functions which return objects that define the action to be taken. increment and decrement below return an object that defines the appropriate type. import { Action, ActionCreator } from 'redux'; export const INCREMENT: string = 'INCREMENT'; export const increment: ActionCreator<Action> = () => ({ type: INCREMENT }); export const DECREMENT: string = 'DECREMENT'; export const decrement: ActionCreator<Action> = () => ({ type: DECREMENT }); Notice that our action creator functions return the type ActionCreator<Action>. ActionCreator is a generic class defined by Redux that we use to define functions that create actions. In this case we’re using the concrete class Action, but we could use a more specific Action class, such as AddMessageAction that we defined in the last section. Creating the Store Now that we have our reducer and state, we could create our store like so: let store: Store<AppState> = createStore<AppState>(counterReducer); However, one of the awesome things about Redux is that it has a robust set of developer tools. Specifically, there is a Chrome extension that will let us monitor the state of our application and dispatch actions. What’s really neat about the Redux Devtools is that it gives us clear insight to every action that flows through the system and it’s affect on the state. Go ahead and install the Redux Devtools Chrome extension now! In order to use the Devtools we have to do one thing: add it to our store. const devtools: StoreEnhancer<AppState> = window['devToolsExtension'] ? window['devToolsExtension']() : f => f; Not everyone who uses our app will necessarily have the Redux Devtools installed. The code above will check for window.devToolsExtension, which is defined by Redux Devtools, and if it exists, we will use it. If it doesn’t exist, we’re just returning an identity function ( f => f) that will return whatever is passed to it. Middleware is a term for a function that enhances the functionality of another library. The Redux Devtools is one of many possible middleware libraries for Redux. Redux supports lots of interesting middleware and it’s easy to write our own. You can read more about Redux middleware here In order to use this devtools we pass it as middleware to our Redux store: export function createAppStore(): Store<AppState> { return createStore<AppState>( reducer, compose(devtools) ); } Now whenever we dispatch an action and change our state, we can inspect it in our browser! Providing the Store Now that we have the Redux core setup, let’s turn our attention to our Angular components. Let’s create our top-level app component, AppComponent. This will be the component we use to bootstrap Angular: We’re going to use the AppComponent as the root component. Remember that since this is a Redux app, we need to make our store instance accessible everywhere in our app. How should we do this? We’ll use dependency injection (DI). When we want to make something available via DI, then we use the providers configuration to add it to the list of providers in our NgModule. When we provide something to the DI system, we specify two things: - the token to use to refer this injectable dependency - the way to inject the dependency Oftentimes if we want to provide a singleton service we might use the useClass option as in: In the case above, we’re using the class SpotifyService as the token in the DI system. The useClass option tells Angular to create an instance of SpotifyService and reuse that instance whenever the SpotifyService injection is requested (e.g. maintain a Singleton). One problem with us using this method is that we don’t want Angular to create our store – we did it ourselves above with createStore. We just want to use the store we’ve already created. To do this we’ll use the useValue option of provide. We’ve done this before with configurable values like API_URL: The one thing we have left to figure out is what token we want to use to inject. Our store is of type Store<AppState>: export function createAppStore(): Store<AppState> { return createStore<AppState>( reducer, compose(devtools) ); } export const appStoreProviders = [ { provide: AppStore, useFactory: createAppStore } ]; Store is an interface, not a class and, unfortunately, we can’t use interfaces as a dependency injection key. If you’re interested in why we can’t use an interface as a DI key, it’s because TypeScript interfaces are removed after compilation and not available at runtime. If you’d like to read more, see here, here, and here. This means we need to create our own token that we’ll use for injecting the store. Thankfully, Angular makes this easy to do. Let’s create this token in it’s own file so that way we can import it from anywhere in our application; export const AppStore = new InjectionToken('App.store'); Here we have created a const AppStore which uses the OpaqueToken class from Angular. OpaqueToken is a better choice than injecting a string directly because it helps us avoid collisions. Now we can use this token AppStore with provide. Let’s do that now. Bootstrapping the App Back in app.module.ts, let’s create the NgModule we’ll use to bootstrap our app: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { appStoreProviders } from './app.store'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule, HttpModule ], providers: [ appStoreProviders ], bootstrap: [AppComponent] }) export class AppModule { } Now we are able to get a reference to our Redux store anywhere in our app by injecting AppStore. The place we need it most now is our AppComponent. Notice that we exported the function appStoreProvidersfrom app.store.tsand then used that function in providers. Why not use the { provide: ..., useFactory: ... }syntax directly? The answer is related to AOT – if we want to ahead-of-time compile a provider that uses a function, we must first export is as a function from another module. The AppComponent With our setup out of the way, we can start creating our component that actually displays the counter to the user and provides buttons for the user to change the state. imports Let’s start by looking at the imports: import { Component, Inject } from '@angular/core'; import { Store } from 'redux'; import { AppStore } from './app.store'; import { AppState } from './app.state'; import * as CounterActions from './counter.actions'; We import Store from Redux as well as our injector token AppStore, which will get us a reference to the singleton instance of our store. We also import the AppState type, which helps us know the structure of the central state. Lastly, we import our action creators with * as CounterActions. This syntax will let us call CounterActions.increment() to create an INCREMENT action. The template Let’s look at the template of our AppComponent. In this chapter we are adding some style using the CSS framework Bootstrap <div class="row"> <div class="col-sm-6 col-md-4"> <div class="thumbnail"> <div class="caption"> <h3>Counter</h3> <p>Custom Store</p> <p> The counter value is: <b>{{ counter }}</b> </p> <p> <button (click)="increment()" class="btn btn-primary"> Increment </button> <button (click)="decrement()" class="btn btn-default"> Decrement </button> </p> </div> </div> </div> </div> The three things to note here are that we’re: - displaying the value of the counter in {{ counter }} - calling the increment()function in a button and - calling the decrement()function in a button. The constructor Remember that we need this component depends on the Store, so we need to inject it in the constructor. This is how we use our custom AppStore token to inject a dependency: import { Component, Inject } from '@angular/core'; import { Store } from 'redux'; import { AppStore } from './app.store'; import { AppState } from './app.state'; import * as CounterActions from './counter.actions'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { counter: number; constructor(@Inject(AppStore) private store: Store<AppState>) { store.subscribe(() => this.readState()); this.readState(); } readState() { const state: AppState = this.store.getState() as AppState; this.counter = state.counter; } increment() { this.store.dispatch(CounterActions.increment()); } decrement() { this.store.dispatch(CounterActions.decrement()); } } We use the @Inject decorator to inject AppStore – notice that we define the type of the variable store to Store<AppState>. Having a different injection token than the type of the dependency injected is a little different than when we use the class as the injection token (and Angular infers what to inject). We set the store to an instance variable (with private store). Now that we have the store we can listen for changes. Here we call store.subscribe and call this.readState(), which we define below. The store will call subscribe only when a new action is dispatched, so in this case we need to make sure we manually call readState at least once to ensure that our component gets the initial data. The method readState reads from our store and updates this.counter to the current value. Because this.counter is a property on this class and bound in the view, Angular will detect when it changes and re-render this component. We define two helper methods: increment and decrement, each of which dispatch their respective actions to the store. Putting It All Together Try it out! cd code/redux/redux-chat/redux-counter npm install npm start open Congratulations! You’ve created your first Angular and Redux app! What’s Next Now that we’ve built a basic app using Redux and Angular, we should try building a more complicated app. When we build bigger apps we encounter new challenges like: - How do we combine reducers? - How do we extract data from different branches of the state? - How should we organize our Redux code? The next step is to build an intermediate Redux chat app. The code is open-source here and we go over how to build it step-by-step in the ng-book Intermediate Redux Chapter. If you found this book helpful, go grab a copy – you’ll become an Angular expert in no time. References If you want to learn more about Redux, here are some good resources: - Official Redux Website - This Video Tutorial by Redux’s Creator - Real World Redux (presentation slides) - The power of higher-order reducers To learn more about Redux and Angular checkout: Onward!
https://blog.ng-book.com/introduction-to-redux-with-typescript-and-angular-2/
CC-MAIN-2021-43
refinedweb
8,022
62.17
want to find module dependencies using py2exe without doing : >>> setup.py py2exe someone can help me ? thanks a partial solution for single file executables using NSIS is here: but it has a problem. you can't pass command line arguments and do not output anything to stdout. but i needed to make a command line tool... then there is pyco () it's an exe stub that unzips its attached payload to a temp dir and invokes python. Dave (pyco author) provides a python tool that zips up a folder and makes the exe. it has some nice properties: - zlib is staticaly linked to the executable, absolutely no other dll is required (appart from the standard windows ones that everyone has anyway) - it loads the python library dynamicaly. (means it's not linked against python23.dll. this makes it possible to extract the python dll before accessing it. it's also very flexible, it works with any python version in theory, but the dll name is a hardcoded string in the stub. the setup script could be made aware of that and patch the number) i fixed some issues (error reporting, runs a specific file/function, import site, dangerous cleanup method, only python21, the "if" with ReadTOC was realy broken, relative paths). then i use py2exe to prepare the distribution. a simple test app with ctypes and one dialog box compresses to 550kB in a single file, no libs changes to pyco i made: - chdir to tempdir before cleaning up (important when client app changes the current dir...) - execute the module and not a specific function - the module executed is "_pyco_loader.py" (which is autogenerated by the setup.py script) - Py_NoSiteFlag is set to prevent "import site" (and the warning and the console because it's not found.) - compiling with cygwin/mingw - console and windows stubs (pycostub.exe pycostub_w.exe) this allows to make command line tools with or without the dos box, or windows only apps (like py2exe). example setup.py: - runs py2exe to collect all the required files and then thows away the .exe file (pyco runs the python source directly) - generate the _pyco_loader.py which sets up the import paths and then executes the users module. it also sets the current directory to the exes location instead of the temp dir. the environ var PYTHONHOME is set to the temp dir location. remaining issues: - set the exes icon - copy pyo/pyc main file instead of py - patch the python dll name in the stub with the name of the current python version - integration in py2exes distutils build command would be nice. a zip file with source and binaries is located here: check out test.py (depends on ctypes) which is the appliaction and run setup.py to build the exe (py2exe required) Dave: thanks for your efforts with zlib and GetProcAddress Thomas: thanks for py2exe which is a pleasure to use chris I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details
https://sourceforge.net/p/py2exe/mailman/py2exe-users/?viewmonth=200412&viewday=9&style=flat
CC-MAIN-2017-34
refinedweb
527
63.29
. If you frequently work with objects and classes, you know that the intrinsic nature of object-oriented programming provides mechanisms that allow you to extend the functionality of an application, or sections of it, in a fairly straightforward fashion. Of course, the first approach that comes to my mind is Inheritance. It permits you to share, between multiple subclasses, a number of features exposed by a parent class; it even lets you implement new ones. While Inheritance can be of some help in a case like this, it's an admittedly overrated approach that only allows you to expand an application in a hierarchical way. This process is not always flexible; it can even lead to erroneous creation of hierarchies of classes that don't belong to the same type, due to the improper use of the so-called "is a" relationship. Luckily, the OOP paradigm offers an alternative which not only makes it easy to reuse common functionality and extend the existing one, but promotes the programming principle of favoring Composition over Inheritance. Of course, I'm talking specifically about Composition. This approach, when coupled to the power of interfaces, allows you to build "pluggable" systems in a snap. In fact, this association is usually known in OOP jargon as the "Plug-in" design pattern. Not surprisingly, it's covered in depth by Martin Fowler in his already classic book Patterns of Enterprise Application Architecture. Are you wondering what I mean by "pluggable" systems? Well, let me elaborate this concept with a simple example: say that you've created a handy PHP class that performs strict validation on email addresses. It checks for RFC compliant formats, MX records and even is capable of querying a mail server to see if it replies back. On the other hand, there's a client class that happily consumes your email validator and injects it into its internals to check email addresses entered by users in an HTML form. All of this works like a charm -- until the very moment that you realize you need to validate URLs, too. That's not really a big deal after all; you appeal to your programming skills (or someone else's), and then write a URL validator and inject it into the client class. Bam! It turns out that it accepts only an email validator, and therefore refuses to accept your shiny new URL checking class. The party is spoiled. In a situation like this, the Plug-in pattern can be used for to constructing all sorts of validators, which can be easily plugged into the aforementioned client class, thus implementing a truly "pluggable" system. Did you get the point of using this pattern? I hope so. Of course, the best way to understand the functionality of "Plug-in" is by example, so in this article series I'll be developing a few with PHP, which will help you grasp its underlying logic more quickly. Now, let's get started! Getting started: developing an "unpluggable" sample application As with many other patterns, there's no need to appeal to the "Plug-in" paradigm in every single case. It's possible, however, to recreate a scenario similar to the one described in the introduction that justifies its implementation. First, I will build a very basic program, which will make you see quickly why the pattern can be so useful when creating scalable systems. The functionality of this program will be limited to rendering some trivial divs on screen and nothing else. With that said, here's the first element of the program. It happens to be an abstract parent class that models the structure and behavior of generic HTML elements. Its definition is as follows: (Html/AbstractHtmlElement.php) <?php namespace Html; abstract class AbstractHtmlElement{ protected $_content; protected $_id; protected $_class; /** * Constructor */ public function __construct($content, $id = '', $class = '') { if (is_string($content)) { $this->_content = $content; } if (is_string($id) && !empty($id)) { $this->_id = $id; } if (is_string($class) && !empty($class)) { $this->_class = $class; } } /** * Implementation delegated to concrete HTML elements */ abstract public function render(); } As you can see above, the previous "AbstractHtmlElement" class accepts three arguments through its constructor. The first one is the text that will be wrapped by the HTML element, while the remaining two are optional, and come in handy for assigning to the element an "id" and a "class" attribute respectively. With that abstract parent comfortably seated on top of the hierarchy, building a refined implementation that renders Divs specifically is as easy as defining the following child class: (Html/Div.php) class Div extends AbstractHtmlElement{ /** * Render the Div element */ public function render() { $' . $this->_content . '</div>' . "n"; return $html; }} That was really simple to code and read, wasn't it? As its name suggests, all that the above "Div" class does is generate the HTML markup corresponding to a div element via its "render()" method. Since I'd like to keep the entire rendering process abstract, I'm also going to create a client class that consumes the previous "Div." This brand new client class is called "Renderer," and its source code looks like this: (Render/Renderer.php) namespace Render;use Html; class Renderer{ protected $_elements = array(); /** * Add a single div element */ public function addElement(HtmlDiv $element) { $this->_elements[] = $element; return $this; } /** * Remove a div element */ public function removeElement(HtmlDiv $element) { if (in_array($element, $this->_elements, true)) { $elements = array(); foreach ($this->_elements as $_element) { if ($element !== $_element) { $elements[] = $_element; } } $this->_elements = $elements; } } /** * Add multiple div elements */ public function addElements(array $elements) { if (!empty($elements)) { foreach ($elements as $element) { $this->addElement($element); } } } /** * Render all the inputted div elements */ public function render() { $output = ''; if (!empty($this->_elements)) { foreach ($this->_elements as $_element) { $output .= $_element->render(); } } return $output; } } At this point, things are becoming a bit more interesting. The earlier "Renderer" class is a sort of Composite that can inject into its internals one or multiple divs objects, which can be rendered in one go through its "render()" method. So far, so good. Since you probably want to see how all of these sample classes can be put to work together in a concrete example, I'm going to define a simple autoloader. It will save us from the hassle of using multiple PHP requires and will lazy-load the classes in question. The implementation of this autoloading class is as follows: (Autoloader.php) class Autoloader{ private static $_instance; /** * Get the Singleton instance of the autoloader */ public static function getInstance() { if (self::$_instance === null) { self::$_instance = new self; } return self::$_instance; } /** * Reset the instance of the autoloader */ public static function resetInstance() { self::$_instance = null; } /** * Class constructor */ private function __construct() { spl_autoload_register(array(__CLASS__, 'load')); } /** * Prevent to clone the instance of the autoloader */ private function __clone(){} /** * Load a given class or interface */ public static function load($class) { $file = str_replace('', '/', $class) . '.php'; if (!file_exists($file)) { throw new AutoloaderException('The file ' . $file . ' containing the requested class or interface ' . $class . ' was not found.'); } require $file; if (!class_exists($class, false) && !interface_exists($class, false)) { throw new AutoloaderException('The requested class or interface ' . $class . ' was not found.'); } } } (AutoloaderException.php) class AutoloaderException extends Exception{} Since this autoloader looks very similar to the ones used in other tutorials previously published here at the Developer Shed network, I'm not going to waste time discussing its underlying logic. In short, all that you need to know is that this class is a Singleton that includes on demand a namespace class. That is all that it does, in fact. With the autoloader up and running, it's time to set up a script that displays some divs on screen using all of the sample classes defined so far. The one included below performs this task in a fairly straightforward fashion. Check it out: use HtmlDiv as Div, RenderRenderer as Renderer; // include the autoloaderrequire_once 'Autoloader.php';Autoloader::getInstance(); // create some divs$div1 = new Div('This is the sample content for the first div element.', 'one_id', 'one_class');$div2 = new Div('This is the sample content for the second div element.', 'another_id', 'another_class'); // create the renderer and add the previous elements to it$renderer = new Renderer;echo $renderer->addElement($div1) ->addElement($div2) ->render(); Effectively, the previous script first creates two div objects, which are added to the renderer via its "addElement()" method. Finally, the HTML of these objects is displayed on the browser by calling the renderer's "render()" method. Certainly, I don't want to sound like I'm bragging here, but the script yields quite impressive results! Well, not so fast. What happens if I also want to display a few paragraphs or lists along with the previous divs? In a case like this, the renderer will simply refuse to do so, as it only accepts objects of type "Div." I could change its implementation and make it accept generic "AbstractHtmlElement" objects; then I would derive a couple of subclasses from the mentioned abstract parent, which would render the pertinent paragraphs and lists, thus solving this issue in a pretty effective way. Unfortunately, this approach offers only a temporary solution. If I decide to write a new class entirely independent from the parent "AbstractHtmlElement" that displays content in a PDF, and pass an instance of it to the renderer, it'll complain loudly again, and refuse to accept this object. So, is there a way to make the renderer accept any type of "renderable" element, other than closely-related HTML objects? This is exactly the scenario where the "Plug-in" pattern really shines, as its proper implementation permits you to solve this problem in an elegant and effective manner. Therefore, in the next segment I'm going to introduce some minor changes into the previous sample application. Thanks to the pattern's functionality, the changes will enable the application to accept all sorts of "renderable" objects. To see how this will be done, jump ahead and read the following lines. Plugin Pattern in PHP and JavaScript
http://www.devshed.com/c/a/PHP/The-PHP-Plugin-Pattern/
CC-MAIN-2014-10
refinedweb
1,642
51.78
I. 8 comments: Thank you for the information. I have mentioned your example (modified, with time elapsed output) here Excuse me for being pedantic, the first global declaration is unnecessary only the one in the cb is necessary. second, det could have been defined more easily as det = linalg.det third, and this depends entirely on the multiprocessing library, but I'd write a method in Pool that takes an iterable instead of repeatedly calling apply_async, as a bonus, it should return a decorator to be used on cb, it would look like this: pool = Pool() args = (random.normal(1,1,(100,100)) for x in xrange(1, 300)) @pool.async_map(det, args) def callback(r): ... @rgz: Pool already has a method called map_async, which does what you want. But to use that, the arguments to your function must be available as an iterable structure, which is possible for this simple example, but not in many of my use cases. The idea here was to put out something very general, and let users customize the example as they want, like you did. A good example, thanks for posting it. Bookmarked. I wonder if using a global counter in this example isn't going to give people wrong ideas? Usually when you get a result for a job you want to know which job it was, not just that job's number in the result queue. Making det return the argument as well as the computed value, and making cb print it instead of a counter might make a slightly better example. This was a useful start as it is a very common usage pattern for me too - thanks! But I have a question, how can one store the multiple return value of the det function? For example, say I have a very long calculation wrapped in a function call, long(a, b), where a and b are just floats, long() returns a single float. How can I store the return values of the call to long and correlate them to the input parameters? In code, how can I parallelise this: import numpy as np data = [] for a in np.linspace(0,1): for b in np.linspace(0,1): answer = long(a,b) data.append((a,b,answer)) Best regards, Dan Hi, I know the post is pretty dated (about an year old... however...), I was surfing the net trying to find some Python command that might be useful to me and I figure out your blog. I am sorry for bothering, I hope you'll have a chance to give me some help or at least an hint since I am pretty new to python. I am using a Fortran program, lately I figure out the necessity to run the same program several times (several means something like 10 times, and in a near future hopefully 1000 times). I have a python script that generates folder and in each folder writes the namelist the program needs to run. Now my question: what I would like to do is to launch a python script that does the following, goes in each sudirectory, get the namelist and start running it. Let's say I tell him to run 4 process on 4 different CPUs at the time: when one process finish the program starts a new process and so on... untill the very end... Yeah I am really sorry for bothering you but I got a bit lost and I had no idea how to implement something like that. Cheers! Alberto @usagi You said: "Pool already has a method called map_async, which does what you want. But to use that, the arguments to your function must be available as an iterable structure, which is possible for this simple example, but not in many of my use cases." But one can easily back multiple arguments into a single argument, say by using a dict. Don't you need locking for incrementing the global counter? Technically two threads could try to update it correct?
http://pyinsci.blogspot.in/2009/02/usage-pattern-for-multiprocessing.html
CC-MAIN-2018-09
refinedweb
671
69.21
I'm a begginer in java I have packet=090209153038020734.0090209153039020734.0 1) 090209153038020734.0 2) 090209153039020734.0 String packetArray[] = ... public class test { /** * @param args */ public static void main(String[] args) { try ... duplicate: hi, i'm have string like this 200209151422010231.10408360.00502240.105090.0200209151423010231.10408360.00502289.605090.0 200209151422010231.10408360.00502240.105090.0 200209151423010231.10408360.00502289.605090.0 I am looking for a method to combine an array of strings into a delimited String. An opposite to split(). I've seen this in other languages. Wanted to ask the forum before I ... I have a text area where a user can enter free flow text. I want to separate out lines/occurrences in my Java class based on the below conditions: When the user does ... I want to split a polynomial like: 2x^7+x^2+3x-9 I'm trying to split a java string in a Rhino javascript program var s = new java.lang.String("1 2 3"); s.split(); js: Can't find method java.lang.String.split(). I have to parse a line which is tab delimited. I parse it using the split function, and it works in most situations. The problem occurs when some field is missing, ... I am noticing strange behaviour when using the split() method in Java. I have a string as follows: 0|1|2|3|4|5|6|7|8|9|10 split() 0|1|2|3|4|5|6|7|8|9|10 String currentString[] = br.readLine().split("\\|"); System.out.println("Length:"+currentString.length); for(int i=0;i < currentString.length;i++){ System.out.println(currentString[i]); } Hi I want to split a string which has content like this: a$b$c String data=... data.split("$"); I have a multiline string which is delimited by a set of different delimiters: (Text1)(DelimiterA)(Text2)(DelimiterC)(Text3)(DelimiterB)(Text4) String.split I have some basic idea on how to do this task, but I'm not sure if I'm doing it right. So we have class WindyString with metod blow. After using it ... i need some help and guidance in displaying the splitted Strings in order. let say, i have username, password, nonceInString. i had successfully encrypted and decrypted those. then i split ... What I am trying to do is read a .java file, and pick out all of the identifiers and store them in a list. My problem is with the .split() ... I've got a Java problem. I'm trying split a string when ever a " " occurs, for example the sentence test abc. Then move the first letter in each word from first to ... I want to split string without using split . can anybody solve my problem I am tried but I cannot find the exact logic. Consider the following String : 5|12345|value1|value2|value3|value4+5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4+ myArray[0] = "5|12345|value1|value2|value3|value4"; myArray[1] = "5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4"; Case 1 String a = " "; String[] b = a.split(","); System.out.println(b.length); String a = ",,,,,,,,,,,,"; String[] b = a.split(","); System.out.println(b.length); I am wondering if i am going about splitting a string on a . the right way? My code is: String[] fn = filename.split("."); return fn[0]; i have a string 004-034556. now i want to split in into two string. string1=004 string2=034556 Is there a better way to read tokens in a file in java? I am currently using StringTokenizer for splitting the tokens. But it can be quite inefficient in most cases as ... I have a string in what is the best way to put the things in between $ inside a list in java? String temp = $abc$and$xyz$; i tried myself lot but can't get a solution so i'm asking help. i have an string String input="---4--5-67--8-9---"; now i need to convert in into an string array which ... String input="---4--5-67--8-9---"; final String json = "\"name\" : \"john\" , \"worth\" : \"123,456\""; String[] ss = json.split("\"\\s*,\\s*\""); System.out.println(json); for (String s : ss) { System.out.println("--> " + s); } I'm trying to use "value1:value2::value3".split(":"); [value1, value2, value3] [value1, value2, , value3] I have this string (Java 1.5): :alpha;beta:gamma;delta {":alpha", ";beta", ":gamma", ";delta"} I did not find anywhere an answer.. If i have: String s = "How are you"? How can i split this into two strings, so first string containing from 0..s.length()/2 and the ... String s = "How are you" 0..s.length()/2 Possible Duplicate: Split string to equal length substrings in Java /** * Splits string <tt>s</tt> into chunks of size <tt>chunkSize</tt> ... I'm looking to split a List of Strings up as i iterate throught the list imagine the following as the List. ["StringA.StringB.StringC"]["StringA.StringB.StringC"]["StringA.StringB.StringC"]["StringA.StringB.StringC"] My current project requires a search to be run on lyrics of a song, which is a String field in the Song object. To help make searches more efficient, I ... I've had a small problem with splitting a String in java as follows: System.out.println(dexListMod.get(selNum-1).getClass().getName()); String dexListTempString = dexListMod.get(selNum-1); So I have a string that is like this: Some text here?Some number here and I need to split those, I am using string.split("\\?") but if I have a string like this: This is a ... I have the following string: Mr John Smith Dickson <john@yahoo.com> I m facing problem in splitting string. Actually i want to split a string with some seperator but without loosing that seperator. when we use somestring.split(String seperator) method in java it splits the ... This is the input as string: "C:\jdk1.6.0\bin\program1.java" Path-->C:\jdk1.6.0\bin\ file--->program1.java extension--->.java I have a .txt text file, containing some lines.. I load the contain using the RequestBuilder object, and split the responseText with words = String.split("\n"); but i wonder, why the result is contains ... I got a String "1/3" where I want to get only the number 1 Is it possible to get it without using "1/3".split("\\/") ? When I try to split a String around occurrences of "." the method split returns an array of strings with length 0.When I split around occurrences of "a" it works fine.Does ... Hi I want to split a string as only two parts. i.e. I want to split this string only once. EX: String-----> hai,Bye,Go,Run Possible Duplicate: Is there a way to split strings with String.split() and include the delimiters? What is your name? My name ... I want to split the following string according to the td tags: <html> <body> <table> <tr><td>data1</td></tr> <tr><td>data2</td></tr> <tr><td>data3</td></tr> <tr><td>data4</td></tr> ... I would like to take the code below and take the 5 number string the I input into the box and output 5 spaces in between each number. So I ... String filterPath="aa.bb.cc{k1:v1,k2:{s1:s2}},bb.cc,ee.dd"; String[] result=filterPath.split(","); for(String r:result){ System.out.println(r); } filterPath aa.bb.cc{k1:v1,k2:{s1:s2}} bb.cc ee.dd I have a string Mr praneel PIDIKITI String[] nameParts = name.split("\\s+"); Mr Praneel ... What should i do if i want to split the characters of any string considering gaps and no gaps? For example, if I have the string My Names James I want each ... My Names James I have a URL string where I need to replace the last collection of characters after the final "/" In Ruby, this would be: str = "/some/url/structure" ar = str.split("/") ar[ar.length-1] = "path" string = ar.join("/") >> ... How would I split a string at a particular index? e.g split string at index 10, making the string now equal to everything up to index 10 and then dumping the ... In java I have a method that recieves a string that looks like: "Name ID CSVofInts" I'm trying to parse a txt file that represents a grammar to be used in a recursive descent parser. The txt file would look something like this: SPRIME ::= Expr eof Expr ::= ... I have this code down below that gives me this output 1,2,3,4,3,4,5,4,3,5,3,4,5,5,4,64, [Ljava.lang.String;@3e25a am using the Java exec command to issue a "hcitool scan" command in order to perform a Bluetooth Scan. The output is in the exact same format as it would ... Hi in my program a string is generated like "1&area_id=54&cid=3".First an integer and then a string "&area_id=",then antoher integer, and after that a string "&cid=" and then the final integer.These two ... "1&area_id=54&cid=3" "&area_id=" If I have a string like : 10.120.230.172 DOM1/HKJ - 2010-11-04 08:05:30 - - 10.120.12.16 ... I found that using String.substring is known for memory issues related to String.split. Is there a memory leak in using String.split? If yes what is the work-around for it? String.substring I am getting this string from a program [user1, user2] String1 = user1 String2 = user2 how to split the string in java in Windows? I used Eg. String directory="C:\home\public\folder"; String [] dir=direct.split("\"); Right now I am using StringUtils.split(String str, char separatorChar) , a,f,h String[] { "a", "f", "h" } a,,h String[] { "a", "h" } i have a string as below a > b and c < d or d > e and f > g a > b and c < d or d > e and f > g i get an string who's like: 1|"value"|; I wanna split that string and choosed that | as separator. My code looks like: String[] seperated = line.split("|"); I have a List and I would like to split the first two characters (alpha characters) into a different string and then all the numbers that follow (they vary in length). How ... I have a string something like |serialNo|checkDelta?|checkFuture?|checkThis?|. Now i am using the following code to split the string. String[] splitString = str.split("|"); but when i use this i get array of string that contains ... |serialNo|checkDelta?|checkFuture?|checkThis?| String[] splitString = str.split("|"); I created a program which will parse the firstName, middleName and lastName. Here is the program and output. This program can definitely be improved and need some input on reducing my ... Ok, you might say that this is a duplicate post but it is different. I am working on a program that is working on some kind of deleting delimiters specified by the ... Here is my problem, I have a dojo/dijit multiselect list, so after a multiple select i need to split the result Example var selecteted = dijit.byId('list1').attr('value'); Is it possible for split to return a null String[]? I am curious as I want to try to be as defensive as possible in my code without having unnecessary ... split String[] I have following data: 1||1||Abdul-Jabbar||Karim||1996||1974 "||" public void setDelimiter(String delimiter) { char[] c = delimiter.toCharArray(); this.delimiter ... This question is rather difficult to confer, for simplistic sake: I am loading some Strings via XML (XStream). for example, Your total count is +variable+ . The outcome would ... I am sucessfully splitting Sentences into words with a StringTokenizer. Is there a tool which is able to split compound words like Projektüberwachung into their parts Projekt and überwachung or even StringTokenizer Projektüberwachung Projekt überwachung And i have no idea why! I bascially have a STRING (yes, not an array), that has the following contents: [something, something else, somoething, trallala, something] I have String explanation = "The image-search feature will start rolling out in the next few days, said Johanna Wright, a Google search director. "Every picture has a story, and we want ... Can I extract string from the phrase using split() function with subphrases as delimeters? For example I have a phrase "Mandatory string - Any string1 - Any string2". How can I ... I'm using this method to split some text: String[] parts = sentence.split("[,\\s\\-:\\?\\!\\«\\»\\'\\´\\`\\\"\\.\\\\\\/]"); does anybody know if there is a solid library based method to achieve the following. say I have a string: "name1, name2, name3, name4" I have a group of radio buttons and a group of checkboxes. I want to print out the selected radio buttons/checked boxes. To print out the radio button selected I use ... I need to read alot of files and insert the data into Ms sql. Got a file, it looks the texts are separated by //t. Split does not do the job, I ... I have month in, which contains a value such as 12. I am trying to split it into two different strings e.g. a=1 and b=2. How do I do this? ... 12 I have a string with zero or more whitespace-separated words, that needs to be split into an array of words. This is what I did. But the post-processing step, where I ... Is there any library API or regex pattern to split a String on some delimiter and automatically trim leading and trailing spaces from every element without having to loop the elements? For ... Hi i am developing the android application now getting the String like under. I want to split my string with comma and with the Star is well. The String Is : kushal,naren,dhrumil,naren.zala@gmail.com,*Bcc:kushal.3106@gmail.com And ... kushal,naren,dhrumil,naren.zala@gmail.com,*Bcc:kushal.3106@gmail.com How to split a string in two parts : one part with first three characters & another part with leftover characters ? (I finally need to convert both splitted substrings to ... hai, hai i have constant maximum length... Based on that maximum length i have to split one string ..how to do in java... Example: String number= "000101051105210100010545"; spilt into 00010/1051105/210100/010545 like ... Suppose you have some simple CSV data in which some of the fields may be empty. Split() has to return a value for each field in order to keep in synch with the data, so it returns an empty string for each empty field. It would be an error for it to ignore the first field because it happened to be ... Hi all, In the Following code split(string) gives a wrong o/p. String individualFC = "CT$ALK1$192.10.2.54$100"; String fcashDet[] = individualFC.split( "$" ); for ( int i =0;i I have strings which use the following seperator | If I split using "|" I get a string array with one cell for every character. If I use a different character (regex) it works. Does anyone know why? Does the | character have a special meaning in the String. Below is sample code and output explaining the issue. Note: This uses ... Hi, I have a String containing the classes package structur, like this.is.a.package I'd like to split it, so I'd do something like: String[] tokens = packageStructur.split(???) Since "." is a special character when it comes to regular expressions, how can I split by "."? I can't find a soluation for this in the API. Hi with split method when i am trying to use "|"(pipe)as delimeter i am getting different result here i am pasting the code class split1 { public static void main(String[] args) { String ss="vijay |kumar"; String ss1[]=ss.split("|"); System.out.println("length is "+ss1.length); System.out.println("Hello World!"); } } Result: E:\vijay\excer>javac split1.java E:\vijay\excer>java split1 length is 13 Hello World! When i am trying to use "-" ... Hi, Name/username Host Dyn Nat ACL Port Status 5102/5102 (Unspecified) D 0 Unmonitored From the above i have to display the Name/username alone.I have tried the below code public class HelloLive extends JApplet implements ActionListener { String command="sip show peers"; public void run() throws ManagerCommunicationException { for (String string : asteriskServer.executeCliCommand(command)) { String b; char a; for(int i=0;i Dear All, We have a requirement that the user enters some decimal number like 123.345 or 12.0987 , now we want to break the real part and fractional part of the string , like for example when 123.345 is breaked it becomes "123" and "345" . I am using split method of the string class to break the real part and ... ... As Joanne said, | is a special character in regular expressions. It means choice. Therefore, || means "empty string or empty string or empty string", in other words: empty string. Now you may think: that would lead to 36 empty strings, because there are only 36 characters: one empty string before each character. The magic here is, there is also an ... I have a a string of the form bh;ah;|ai;al;|lk;| I have to break it up first by | and then by ; . then i have to add its contents to vector.. public Vector stringToVector(String saveString){ Vector day = new Vector(); String aliasArray[]= saveString.split("|");//splitting by shifts for(int j=0;j Hi, I need to use string.split() to tokenize a string. The problem is the delimiter can be any character or sequence of characters. What I've noticed is that some characters such as | or . perform incorrectly as the delimiting character. I understand that this is because they have a different meaning in regular expressions. It is easy to overcome this ... Hi ALL Does anyone know how to split a String into its constituent characters ?? e.g if you have a string say "saddle", how do I get hold of the character at position 1 or 2 ?? do I use the method charAt() ??? How do you use this method ??? Thanks in Advance. I was just posting a question regarding the java.lang.String.split() method when I figured out that I was using 1.3 and it's only available in 1.4. So that leaves me the question of whether there is some way to do this (split a comma separated list into an array) in 1.3 other than manually write my own function to do it. Anyone ... Never used it myself, but unless I miss my guess it's because your regular expression is incorrectly formatted. Are you trying to split on a string containing two periods? If so, (since the period is a special character in regular expressions) you'll need to specify the regex as something along the lines of "\\.\\." (the double-backslash turns into a single in ... Okay, I'll bite... as a Perl hacker my first inclination is to seek a regex based solution. The java.util.regex package isn't quite as easy to use as Perl's built in functionality, but this isn't too tough: import java.util.regex.Pattern; import java.util.regex.Matcher; public class JRTest { public static void main(String[] args) { String test = "IceCream"; StringBuffer buffer = new StringBuffer(); Pattern p ... I need to split a string of asterisks (that will vary in length) with a space after every five asterisks. I have tried playing around w/ a for loop, string tokenizer, and regex and I haven't come up w/ the solution yet. Yes, I am very new at studying Java! Any ideas? public class Histogram { public static void main(String[] args) ... I'm trying to parse/split a String into tokens using the String.split( regex ) method, but I'm losing the empty tokens at the tail of the String. Currently, I'm using: String str = "1,2,,4,,,"; str.split( "," ); which creates the following String array: str[0] = "1" str[1] = "2" str[3] = "" str[4] = "4" unfortunately, all the empty tokens are lost ...
http://www.java2s.com/Questions_And_Answers/Java-Data-Type/string/Split-1.htm
CC-MAIN-2013-48
refinedweb
3,336
68.06
If don’t want to try your hand at Java, then I would recommend you read my article: I want to develop Android Apps – What languages should I learn? Java Tutorial For Beginners – Introduction Not only is Java the official programming language for app development, Java itself is used by Google for large parts of the Android internals. There are two distinct parts to learn Java for writing an Android app. One is the Java programming language itself, the other is understanding how to create an app in terms of its user interface, the Android OS, and the Android Software Development Kit (SDK). In this tutorial we will deal with the first of these, the Java programming language. Java was first released in the mid-1990s by Sun Microsystems. It was designed to be easy to learn Java by programmers who already knew C and C++. During 2006 and 2007 Sun released Java as free and open-source software, under the terms of the GNU General Public License (GPL). Sun was bought by Oracle in 2009/2010, and Oracle remains committed to Java. To start writing Java programs you need a way to compile source code and turn it into an executable for the Java runtime. The normal way to do this is to install the Java Development Kit. At the time of writing the current version of Java is Java 8, however it is relatively new, so Android uses Java 7. If you are unsure about installing the JDK then read this How to Install the Java Software Development Kit tutorial. Oracle also provides a JDK 7 Installation Guide. However, if you aren’t quite ready to install the JDK, and you want a quick route to trying your first Java program, then I recommend compilejava.net. It is a simple online programming environment that lets you write simple Java programs and run them without needing to go through the hassle of setting up the JDK. There is also the added benefit that since the latest OpenJDK comes bundled with Android Studio then really you don’t actually need to install the JDK, even for writing Android apps! The compilejava.net web page is divided into three parts. At the top is the space to write your Java code and at the bottom is the output from compiling (left) and running (righ) that code. From here in I will assume you are using compilejava.net. However, for those who have installed the JDK the process is almost identical except that you will need to use a text editor on your PC rather than the editor inside the online IDE. Cut and paste the following code into the editor: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } } If you are using the JDK then you need to save the file as HelloWorld.java. In Java the filename of the source code and the class name must be the same. The first line of the code declares a class called HelloWorld, so this source code must be saved in HelloWorld.java. However compilejava.net is clever enough to work that out, so it saves the file as HelloWorld.java automatically! Now hit the “COMPILE & EXECUTE” button toward the bottom of the screen. Your reward is the text “Hello, World” being displayed in the bottom-right windows. Congratulations! Java Tutorial For Beginners – What did I just do? So let’s take a moment to look at what just happened. First the source code. The file does three things. 1) It declares a class called HelloWorld. 2) It defines a method (a function) in the HelloWorld class called main. 3) The main() method calls System.out.println to output some text. In Java, and in all object orientated programming languages, a class defines an object. An object is a self contained item that interacts with other objects. In Android such object would include elements in the UI, a network connection, some location data, and so on. Each Java program must define a method called main in at least one class. It is the entry point, where the program starts executing. In the simple example above the main() method has just one line of code, a call to System.out.println to output “Hello, World”. println() is a method that belongs to the PrintStream class and is included as part of the System class. Oracle has lots of information about the System class and the PrintStream class. Java is architecture-independent which means that a .java file isn’t compiled for a specific processor on a specific OS, like Windows on an Intel x86 chip, or Android on an ARM Cortex-A processor, but rather it is turned into Java bytecode. The job of the Java virtual machine is to run that bytecode on the specific platform. Java Tutorial For Beginners – Variables When writing computer programs you will need to store some data for temporary use. For example in an Android game you will want to store the score of the current player. These bits of data are stored in variables – a box in which you can put some data and then come back later a retrieve it. Since data comes in different forms a variable needs to be defined with a type, which tells Java what is being stored. Some of Java’s primitive data types include int (for integer), double (for double precision floating point number), and boolean (for a true/false value). Here is a simple program which sets the value of a variable, prints out the value to the console, changes the variable and then prints it out again: public class VariableTest { public static void main(String[] args) { int i = 1; System.out.println("The value of i is: " + i); i = i + 24; System.out.println("The value of i is now: " + i); } } Click “COMPILE & EXECUTE”. The output of the program will be: The value of i is: 1 The value of i is now: 25 As you can see the program defines a variable called “i” and gives it an initial value of 1. The value of “i” is printed to the console. Then i is set to the new value of i + 24, or 1 + 24, which is 25. The new value is then printed out. Try modifying the program to use a “double” rather than an “int”. Set “i” to something like 1.3 and increase its value by another decimal number like 24.9. If you take a look at the println() method you will see an integer being added to a string: “The value of i is: ” + i. What actually happens here is that Java knows that the first part of the expression is a string, so it generates the string value for i, in this case “1” and then concatenates it to the string giving: “The value of i is: 1”. Java Tutorial For Beginners – Strings Strings are an important part of any programming language including Java. Unlike int or boolean, a string isn’t a primitive type it is a class. When you create a string variable you are really creating a String object (notice the capital letter S). As an object it has certain properties like its value (the string itself) and its length. Strings can be manipulated in lots of different ways, including being dissected, concatenated, compared, and searched. Here is an example program that performs a few simple operations on a String: public class PlayingWithStrings { public static void main(String[] args) { String hello = "Hello, World"; System.out.println(hello); // Add an ! to the end hello = hello + "!"; System.out.println(hello); // Extract the word "Hello" from the String // i.e. starting at the beginning (0) for 5 characters String justHello = hello.substring(0,5); System.out.println(justHello); // Add some trailing spaces and then remove them with trim() hello = hello + " "; hello = hello.trim(); // Now output the string all in UPPERCASE and lowercase System.out.println(hello.toUpperCase()); System.out.println(hello.toLowerCase()); } } Compile and run it as shown previously. This is a special method called a constructor. The constructor is called only once, at the moment that the object is created. The first part of the program creates a String object called “hello” and gives it a value of “Hello, World”. Although this make look similar to how you declare and assign an integer or another primitive type, actually there is a lot more going on here. Java allows simple operators like = and + to be assigned simple tasks. So really String hello = “Hello, World”; is actually some like String hello = new String(“Hello, World”);, in other words, create a new object of type String and pass in the value “Hello, World” to the constructor. But we will talk more about that in the Objects section below. The next part shows how you can concatenate strings, in this case an exclamation point is added to the end of the string. Since String is an object it can have methods. String.substring() is a method which returns part of a string. In this case the first 5 characters. String.trim() is another method which removes leading and trailing spaces. The last part of the program demonstrates the String.toUpperCase() and String.toLowerCase() methods. The output from the program will be: Hello, World Hello, World! Hello HELLO, WORLD! hello, world! You can find out more about the String object in Oracle’s String tutorial and from the Java String documentation. Java Tutorial For Beginners – Loops If there is one thing a computer is good at, it is doing repetitive tasks. To perform a repetitive task in a programming language you use a construct called a loop – something that loops around again and again. Java has three types of simple loop: the for loop, the while loop, and the do while loop. Each loop type follows the same basic idea, you need to repeat something over and over again until a certain condition is met. Here is an example which shows how to print out the numbers 1 to 10, 11 to 20, and 21 to 30, using the three different types of loop: public class Loops { public static void main(String[] args) { // For loop for(int i=1; i<=10; i++) { System.out.println("i is: " + i); } // While Loop int j = 11; while(j<=20) { System.out.println("j is: " + j); j++; } // Do While Loop int x = 21; do { System.out.println("x is: " + x); x++; } while (x <=30); } } Create a file called Loops.java with the code from above, then compile it and run as shown previously. The for loop as three parts. First the initialization (int i=1), which is executed only once. In the example above the initialization is used to declare an integer i and set its value to 1. Then comes the test expression (i<=10). This expression will be tested every time the loop executes. If the result of the test is true then the loop will go around again. In this example the test is to check that i is still less than or equal to 10. After each iteration the third section, the iterator, will be executed. In this example it increases the value of i by one. Note that i = i + 1 is the same as i++. The while loop is similar to the for loop, except it doesn’t contain the initialization phase and the iterator phase. That means that the initialization needs to be done separately, hence the declaration int j = 11;. The iterator also needs to be coded separately. In our example it is the line j++ which is found inside the loop after the println(). A do… while loop is very similar to a while loop with one big difference, the test to see if the loop should continue is at the end of the loop and not at the start. This means that a do… while is guaranteed to execute at least once, but a while loop doesn’t even need to execute at all, if the conditions aren’t met on the entrance into the loop. Like the while loop, the initialization needs to happen outside the loop, in this case: int x = 21; and the iterator occurs inside the loop: x++. When x goes over 30 the loop will stop. Java Tutorial For Beginners – Objects As I mentioned before, Java is what is known as an object-orientated (OO) programming language and to really learn Java programming and Android programming it is important to understand OO concepts. At its simplest level an object is a set of methods (functions) that work on a data set. The data and the methods belong to the object, and work for the object. Here is the source code for a very simple program which creates a counter object: public class Counter { int count; public Counter() { count = 0; } public void Increment() { count++; } public int GetCount() { return count; } public static void main(String[] args) { Counter myCounter = new Counter(); System.out.println("mycounter is " + myCounter.GetCount()); myCounter.Increment(); System.out.println("mycounter is " + myCounter.GetCount()); } } The Counter object has one piece of data, the integer variable count and three methods (other than main): Counter(), Increment(), and GetCount(). Leaving the first method for the moment, you can see that Increment() and GetCount() are very simple. The first adds one to the internal variable count and the second returns the value of count. Until now all the methods we have declared started with public void but if you notice the GetCount() method starts with public int. We will talk more about public in a moment, but the difference between void and int is this: void declares that the method doesn’t return anything, there will be no result coming back out of the method. But int tells us that the method will return a number, specifically an integer. You can actually create methods that will return all kinds of data, including objects. Notice that the first method has the same name as the class itself, i.e. Counter(), and it doesn’t have a return type (not even void). This is a special method called a constructor. The constructor is called only once, at the moment that the object is created. It is used to initialize the object with default values and perform any other necessary initialization tasks. In this example it just sets count to zero. Java Tutorial For Beginners – Inheritance The great thing about classes is that you can create a general class for an abstract idea and then create specific classes which are derived from the original class. For example, you can create a class called Animal and then derive a new class from it for a specific animal, say an Elk. Here is an example, I will expand on what is happening here in a moment… You are going to need to create two files for this example, Animal.java and Elk.java. Here is Animal.java: public class Animal { int NumberOfLegs; public Animal(int n) { NumberOfLegs = n; } public int GetNumLegs() { return NumberOfLegs; } } Normally you would put the Animal class above in a file called Animal.java and the Elk class below in a file called Elk.java. However if you are using compilejava.net then you can put all the code into the editor window and it will automatically be saved into the correct files when you compile and execute. public class Elk extends Animal { int lengthOfAntlers; public Elk(int l) { super(4); lengthOfAntlers = l; } public int GetAntlerLength() { return lengthOfAntlers; } public static void main(String[] args) { Elk myElk = new Elk(30); System.out.println("Antler: " + myElk.GetAntlerLength()); System.out.println("Legs: " + myElk.GetNumLegs()); } } The Animal class is what is known as a super class, while the derived class Elk is known as a sub-class, because hierarchically it is below the Animal class. When a class is extended (i.e. you create a sub-class) the new class takes on the data and methods of the super class. That is why the program is able to call myElk.GetNumLegs() even though it is part of the Animal class. The new Elk class has two variables: NumberOfLegs and lengthOfAntlers. It also has two methods: GetAntlerLength and GetNumLegs. If we created another sub-class, say Sheep, it would inherit the NumberOfLegs variable and the GetNumLegs method. When designing objects you will discover that you want some methods to be exposed to the rest of the program, so that they can be called. But other methods you might want to keep private, so that only the object itself has access to it. This is where that word public comes into play. We have been declaring everything as public which means the method can be called from anywhere else in the code. However you can declare methods as private or protected, which will limit the access to those methods. The same access rules can also be applied to the object’s variables. A deeper discussion is beyond the scope of this tutorial, but if you would like some more information then you should read Controlling Access to Members of a Class and Declaring Member Variables from Oracle’s Java documentation. One other thing worth mentioning is how the constructors work. The Elk() constructor initializes the lengthOfAntlers variable, in this case to 30, the number passed in when the object was created. But before that, it calls the constructor of the super class (i.e. Animal() ) using the special Java notation super. There is a lot more that can be said about object-orientated programming (OOP), but this Java tutorial for beginners should be enough to give you a taste and get you started. Java Tutorial For Beginners – Wrap up Thanks for checking out this Java tutorial for beginners. If you want to learn more then check out part 2 of this series: Java tutorial for beginners, part 2. There are also lots of online tutorials to learn Java. Here are a few from Oracle: -. You might also want to look at the following tutorials: For those of you who would like an eBook or a printed book on Java programming then you might want to consider the following: Also, good books on Android programming include: - Android Programming: The Big Nerd Ranch Guide - The Beginner’s Guide to Android Game Development - Learning Java by Building Android Games
https://www.androidauthority.com/java-tutorial-beginners-2-582147/
CC-MAIN-2018-09
refinedweb
3,066
62.98
I am trying to return a pointer address to my main function but it isn't working. I am using Windows 98, Visual Studio 6.0 and making my program for a win 32 console application. I have put the function that I am working on below. The purpose of this program is to complete an assignment for school. What this function is to do is to take a complex array of predefined numbers and square them, storing the result in the original array. I am pretty sure that I have messed this up badly. I have a couple of questions about this as well. I am using pointers because I am under the impression that if you just pass the array the contents are protected, and would not be changed when the function returns. Is this true? The instruction and the book that in the course that I am taking has not been the best. Does anyone know where I can find a good explanation of using pointers, functions and structs? int square_function(int * original[][COLUMNS], int rows) { int i, j; for (i=0 ; i < rows ; i++) for (j=0 ; j < COLUMNS ; j++) *original[i][j] = (*original[i][j] * 2); return (*original); } Thank you for any help or direction.
http://cboard.cprogramming.com/c-programming/7176-returning-arrays-function-printable-thread.html
CC-MAIN-2014-23
refinedweb
210
72.76
This action might not be possible to undo. Are you sure you want to continue? Expanded Course Outline Professor E. A. Labitag Karichi Santos | UP Law B2012 ndSemester, A.Y. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Labitag [2 Page 2 of 110 Table of Contents Title I. OBLIGATIONS...................................................................................................................................................... 3 Chapter I. General Provision ......................................................................................................................................... 3 Concept of Obligation .............................................................................................................................................. 3 Sources of Obligations ............................................................................................................................................. 4 Classifications of Obligations..................................................................................................................................... 9 Chapter II. Nature and Effects of Obligations ................................................................................................................. 10 Kinds of Prestation ................................................................................................................................................. 10 Breach o f Obligation ............................................................................................................................................... 13 Remedies of Creditor In Case of Breach .................................................................................................................... 17 Subsidiary Remedies of Creditor ............................................................................................................................... 19 Extinguishment of Liability In Case of Breach Due To Fortuitous Event .......................................................................... 21 Usurious Transactions ............................................................................................................................................ 22 Fulfillment of Obligations ........................................................................................................................................ 26 Transmissibility of Rights ........................................................................................................................................ 26 Chapter III. Different Kinds of Civil Obligations .............................................................................................................. 26 Pure and Conditional .............................................................................................................................................. 26 Obligations with a Period ........................................................................................................................................ 33 Alternative Obligations............................................................................................................................................ 10 Joint and Solidary Obligations .................................................................................................................................. 38 Divisible and Indivisible Obligations .......................................................................................................................... 44 Obligations with a Penal Clause ............................................................................................................................... 46 Chapter IV. Extinguishment of Obligations..................................................................................................................... 49 Modes of Extinguishment ........................................................................................................................................ 49 Payment or Performance ........................................................................................................................................ 49 Loss or Impossibility ............................................................................................................................................... 54 Confusion o r Merger of Rights ................................................................................................................................. 63 Compensation ....................................................................................................................................................... 10 No vation .............................................................................................................................................................. 10 Title II. CONTRACTS ...................................................................................................................................................... 72 Chapter I. General Provisions ...................................................................................................................................... 72 Chapter II. Essential Requisites of Contracts .................................................................................................................. 76 Consent ............................................................................................................................................................... 76 Object of Contracts ................................................................................................................................................ 83 Cause of Contracts ................................................................................................................................................. 84 Chapter III. Form of Contracts..................................................................................................................................... 86 Chapter IV. Reformation of Instruments........................................................................................................................ 87 Chapter V. Interpretation of Contracts .......................................................................................................................... 88 Chapter VI. Rescissible Contracts ................................................................................................................................. 90 Chapter VII. Voidable or Annullable Contracts ................................................................................................................ 93 Chapter VIII. Unenforceable Contracts .......................................................................................................................... 95 Chapter IX. Void or Inexistent Contracts ....................................................................................................................... 97 Title III. NATURAL OBLIGATIONS .................................................................................................................................. 103 Title IV. ESTOPPEL ...................................................................................................................................................... 105 Title V. TRUSTS .......................................................................................................................................................... 108 Karichi E. Santos | UP Law B2012 ndSemester, A.Y. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Labitag [2 Page 3 of 110 University of the Philippines College of Law OBLIGATIONS AND CONTRACTS Professor Eduardo A. Labitag 2n d Semes ter, AY 2008-2009 Title I. OBLIGATIONS Chapter I. General Provision CONCEPT OF OBLIGATION Definition Art 1156 Obligation is a juridical necessity to give, to do or not to do. OBLIGATORY RELATION IN ITS TOTALITY: The juridical relation, created by virtue of certain facts, between two or more persons, whereby the creditor or obligee, may demand of the debtor or obligor, a definite prestation. on PASSIVE SIDE: Where there is a right or power to demand, there is a correlative obligation or an imposition upon a person of a definite conduct. Criticism of definition: Elements of Obligation 1. Active subject power to demand the prestation (obligee/creditor) Personal 2. Passive subject bound to perform the prestation (obligor/debtor) elements Temporary indefiniteness of a subject e.g. negotiable instrument payable to bearer or a promise of a prize or a reward for anyone performing a certain act 3. Prestation or Object not a thing but a particular conduct of the debtor, but always a prestation KINDS OF PRESTATION a. TO GIVE consists in the delivery of a movable or an immovable thing, in order to create a real right or for the use of the recipient or for its simple possession or in order to return to its owner b. TO DO all kinds of work or services, whether mental or physical c. NOT TO DO consists in abstaining from some act, includes not to give, both being negative obligations REQUISITES OF PRESTATION a. Physically and juridically possible b. Determinate or at least determinable according to pre-established elements or criteria c. Possible equivalent in money rd Pecuniary interest need not be for one of the parties, it maybe for the benefit of 3 person/s distinct from the parties to the contract Prestation need not be of economic character to have pecuniary value, if it does not have value the law attributes to it economic value e.g. moral and nominal damages 4. Efficient cause or juridical tie or vinculum juris relation between obligor and oblige which is established: - By law (e.g. relation of husband and wife giving rise to the obligation to support) - By bilateral acts (e.g. contracts giving rise to the obligations stipulated therein) - By unilateral acts (e.g. crimes and quasi-delicts) 5. Form in which the obligation is manifested cannot be considered essential Distinction between Natural and Civil Obligation NATURAL CIVIL Karichi E. Santos | UP Law B2012 It is one sided, reflects only the debtor s side of the agreement Sanchez Roman ndSemester, A.Y. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Labitag [2 Page 4 of 110 Court actio n or the coercive power of public authority As to enforceability Not by court actions, but by good conscience of debtor As to basis Equity and natural justice Positive law SOURCES OF OBLIGATIONS A. LAW [Ex-Lege]. - Governed by the law itself - Agreement of the parties is not necessary e.g. tax collection, Art 448 and Art 488 - Not presumed, only those expressly provided are enforceable B. CONTRACTS [Ex-Contractu, Culpa Contractual] Art 1159 Obligations arising from contracts have the force of law between the contracting parties and should be complied with in good faith. - Expresses principle of autonomy of will, presupposes that contract is valid and enforceable - PRE-CONTRACTUAL OBLIGATION: Damages can be recovered when contract is not perfected if: o Offers is clear and definite , leading offeree in good faith to incur expenses in expectation of entering into a contract o Withdrawal of the offer must be without any illegitimate cause. If offeror: _ Guilty of fault or negligence, liability would be based on Art 2176 _ No fault or negligence, withdrawal was in abuse of right, liability would be based on Art 19 e.g. breach of promise to marry Art 1305 A contract is a meeting of minds between two persons whereby one binds himself, with respect to the other, to give something or to render some service. C. QUASI-CONTRACTS or DELICTS [Quasi Ex-Contractu] Art 1160 Obligations derived from quasi-contracts shall be subject to the provisions of Chapter 1, Title XVII. Art 2142 Certain lawful, voluntary and unilateral acts give rise to the juridical relation of quasi-contract to the end that no one shall be unjustly enriched or benefited at the expense of another. - Juridical relation which arises from certain acts that are: _ LAWFUL (against crime), _ VOLUNTARY (against quasi-delict based on negligence or mere lack of foresight) _ UNILATERAL (against contract in which there are two parties) - E.g. Art 2144 Art 2150 Art 2154 Art 2164 Art 2167 Art 2168 Art 2174 Art 2175 Kinds of Quasi-contracts 1. Negotiorum gestio (officious management) Art Solutio indebiti (payment not due) Art 2154 If something is received when there is no right to demand it, and it was unduly delivered through mistake, the obligation to return it arises. Karichi E. Santos | UP Law B2012 2. ndSemester, A.Y. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Labitag [2 Page 5 of 110 3. Other quasi-contracts (support given by strangers and other Good Samaritans ) Art 2164 Art 2165 Art 2166 When, without the knowledge of the person obliged to give support, it is given by a stranger, the latter shall have a right to claim the same from the former, UNLESS it appears that he gave it out of piety and without intention of being repaid. When funeral expenses are borne by a third person, without the knowledge of those relatives who were obliged to give support to the deceased, said relatives shall reimburse the third person, should the latter claim reimbursement.. Art. Art 2168 Art 2169 Art 2170 Art 2171 Art 2172 Art 2173 Art 2174 When during a fire, flood, storm, or other calamity, property is saved from destruction by another person without the knowledge of the owner, the latter is bound to pay the former just compensation. When the government, upon the failure of any person to comply with health or safety regulations concerning property, undertakes to do the necessary work, even over his objection, he shall be liable to pay the expenses. When by accident or other fortuitous event, movables separ ately pertaining to two or more persons are commingled or confused, the rules on co-ownership shall be applicable. The rights and obligations of the finder of lost personal property shall be governed by Articles 719 and 720. The right of every possessor in good faith to reimbursement for necessary and useful ex penses is governed by Article 546. When a third person, without the knowledge of the debtor, pays the debt, the rights of the former are gov erned by Articl es 1236 (recover what has been beneficial to debtor) and 1237 (cannot compel creditor to subrogate payor in his rights). When in a small community a nationality. Art 2175 Any person who is constr ained to pay the taxes of another shall be entitled to reimbursement from the latter. D. ACTS or OMISSIONS PUNISHED BY LAW [Ex-Delictu, Ex-Maleficio, Culpa Criminal] Art 1161 Civil obligations arising from criminal offense shall be governed by the penal laws, subject to the provisions of Art 2177, and of the pertinent provisions of Chapter 2, Preliminary Title on Human Relations and of Title XVIII of this Book, regulating damages. Art 100, RPC Every person criminally liable for a felony is also civilly liable. GENERAL RULE: Civil liability is a necessary consequence of civil liability o Reason: Commission of crime causes not only moral evil but also material damage. o Art 12, RPC Exempting circumstances; do not incur liability but are NOT EXEMPT from civil liability 1. Imbecile or insane person, unless acting in a lucid interval 2. Person under 9 years of age 3. Person over 9 years of age and under 15, unless acting with discernment 4. Acting under compulsion of an irresistible force 5. Acting under impulse of an uncontrollable fear of an equal or greater injury EXCEPTION (crimes without civil liability) o Criminal contempt o Gambling o Traffic violations Subsidiary Liability for Crime 1. Innkeepers, tavern keepers and any other persons or corporations shall be civilly liable for crimes committed in their establishment, in all cases where a violation of municipal ordinances or some general or special police regulation shall have been committed by them or their employees. 2. Also applicable to employers, teachers, persons and corporations engaged in any kind of industry for felonies committed by their servants, pupils, apprentices or employees in discharge of their duties. - To hold employers subsidiarily liable for CRIME of an employee: committed in the performance of the functions or duties of the employee. Karichi E. Santos | UP Law B2012 ndSemester, A.Y. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Labitag [2 Page 6 of 110 - But if action is based on CONTRACT , and not upon previous conviction of employee for a crime: employer s liability is PRIMARY and INDEPENDENT, not merely subsidiary. Civil liability arising from Crime Art 1161 Civil obligations arising from criminal offenses shall be governed by the penal laws , subject to the provisions of Article 2177, and of the pertinent provisions of Chapter 2, Preliminary Title, on Human Relations, and of Title XVIII of this Book, regulating damages. Rules on Criminal Procedure Rule 111. Extent of Civil Liability Art 104, RPC What is included in civil liability 1. Restitution thing itself is restored (Art 105, RPC) 2. Reparation of damage caused court determines amount of damage (Art 106, RPC) rd 3. Indemnification for consequential damages not only caused the 3 party but also those suffered rd by his family or by a 3 person by reason of the crime (Art 107, RPC) y Civil liability for crimes is extinguished the same causes provided in the CC for the extinguishment of other obligations. GENERAL RULE: Criminal action bars civil action for the same offense y Civil action for recovery of civil liability arising from the offense is impliedly instituted with the criminal action EXCEPTIONS: y Offended party reserves the right to institute it separately y The law provides for an independent civil action (i.e. civil action may proceed to final judgment irrespective of result of the criminal action and filing of the criminal action does not suspend the civil action) o obligations arising from the act or omission claimed to be criminal (Art 31) o violations of constitutional rights and liberties of individuals (Art 32) o defamation, fraud or physical injuries (Art 33) o refusal or failure of members of police force to render protection to life or property (Art 34) E. QUASI-DELICTS [Quasi Ex-Delicto, Quasi Ex-Maleficio, Culpa Aquilana, Tort (common law)] Art 1162 Obligations derived from quasi-delicts shall be governed by the provisions of Chapter 2, Title XVII of this Book and by special laws. Art 2176 Whoever by act or omission causes damage to another, there being fault or negligence, is obliged to pay for the damage done. Such fault or negligence when there is no pre-existing contractual relation between the parties, is called quasi-delict and is governed by the provisions of this Chapter. BASIS: Undisputable principle of equity; fault or negligence cannot prejudice anyone else besides its author and in no case should its consequences be borne by him who suffers the harm produced by such fault or negligence. - Man is responsible not only for his voluntary willful acts, executed consciously and intentionally but also for those acts performed with lack of foresight, care and diligence, which cause material harm to society or to other individuals. NEW SOURCES OF OBLIGATION generally recognized by law although not included in the code 1. Unjust enrichment (CC categorized under quasi-contract) 2. Unilateral declaration of will 3. Abuse of rights (CC categorized under quasi-delict) Test of Negligence: Would a prudent man, in the position of the person to whom negligence is attributed, foresee harm to the person injured as a reasonable consequence of the course about to be pursued? ELEMENTS OF NEGLIGENCE a) duty on the part of the defendant to protect the plaintiff from injury of which the latter complains b) failure to perform such duty c) an injury to the plaintiff through such failure Karichi E. Santos | UP Law B2012 Culpa aquilana or culpa extra-contractual.Y.ndSemester. contempt. he cannot recover damages. negligence as a source of obligation. There exists a damage or injury 3. the plaintiff may recover damages. Possible that Criminal intent is necessary for the existence there is not criminal charge but only civil of liability. and under the particular circumstance surrounding the cause.g. Culpa criminal criminal negligence Distinction between Culpa Aquilana and Culpa Contractual CULPA AQUILANA CULPA CONTRACTUAL (culpa extra Distinction between Quasi-delicts and Crimes AS TO QUASI-DELICT CRIMES Nature of right violated. without it. each of them is a proximate cause o When the plaintiff s own negligence was the immediate and proximate cause of his injury. violations of ordinances and traffic regulations when nobody is injured Forms of redress Reparation of the injury suffered by the Fine (accruing to the public treasury). Labitag [2 Page 7 of 110 KINDS OF NEGLIGENCE 1. o BUT if negligence is only contributory . a quasi-delict 2. Santos | UP Law B2012 . or sets in motion other causes so producing it and forming a continuous chain in natural sequence down to the injury o CONCURRENT CAUSE: if two causes operate at the same time to produce a result which might be produced by either independently of the other. in the natural order of events. wrong against the state . injured party compensation. Private rights. indemnification imprisonment or both punishment Amount of evidence Preponderance of evidence Beyond reasonable doubt Compromise Can be compromised as any other civil liability Can never be compromised Requisites of Liability under Quasi-Delicts 1. would necessarily produce the event o NATURAL AND PROBABLE CAUSE: either when it acts directly producing the injury. wrong against the individual Public right. can be punished or negligence intervenes only when there is a penal law clearly penalizing it Liability for damages Liability for damages to the injured party Certain crimes do not have civil liability e. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. the courts shall mitigate the damages to be awarded (Art 2179) Karichi E. There exists a wrongful act or omission imputable to the defendant by reason of his fault or negligence 2.An obligation can arise from both crime and quasi-delict at the same time (e. there can be no crime liability for damages arising from quasi-delict Legal basis of liability Actionable in any act or omission wherein fault Not as broad as quasi-delict. Direct causal connection or relation of cause and effect between the fault or negligence and the damage or injury OR that the fault or negligence be the cause of damage or injury o DOCTRINE OF PROXIMATE CAUSE: such adequate and efficient cause as. physical injuries) BUT can only recover damage once and not twice Condition of mind Criminal intent is not necessary.g. gambling. Culpa contractual negligence in the performance of a contract 3. the immediate and proximate cause of the injury is defendant s lack of due care. A. but not when the damage has been caused by the official to whom the task done properly pertains. Diligence of Employers An employer may be held civilly liable for the quasi-delict or crime of his employee. RPC) Subsidiary. employee must have first been convicted and sentenced to pay civil indemnity and it must be shown that he is insolvent in order that employee may be liable Liability is absolute and cannot avail of the defense by proof of such diligence Employer is liable only when he is engaged in some kind of business or industry (during performance of duty) LIABILITY OF EMPLOYERS FOR EMPLOYEES QUASI-DELICT (Art 2180. entity or institution engaged in child are shall have special parental authority and responsibility over the mi nor child while under their supervision. The State is responsible in like manner when it acts through a special agent. are liable for the acts of their employees including house helpers Karichi E. are responsible for the damages caused by the minor children who live in their company. Art 219. CC) Primary.Y. Santos | UP Law B2012 . whether they are engaged in some enterprise or not.ndSemester. judicial guardians or the persons exercising substitute parental authority over said minor shall be subsidiarily liable. in case of his death or incapacity. ev en though the former are not engaged in any business or industry. LIABILITY OF EMPLOYERS FOR EMPLOYEES CRIME (Art 103. The respective liabilities of those referr ed to in the preceding paragraph shall not apply if it is proved that they exercised the proper diligence required under the particular circumstances. The responsibility treated of i n this article shall cease when the persons herein mentioned prove that they observed all the diligence of a good father of a family to prevent damage. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. entity or institution. its administrators and teachers. Art 2180 The obligation imposed by Article 2176 is demandable not only for one's own acts or omissions. teachers or heads of establishments of arts and trades shall be liable for damages caused by their pupils and students or apprentices. A. the mother. but also for those of persons for whom one is responsible. so long as they remain in their custody. instruction or custody. The father and. Employers shall be liable for the damages caused by their employees and household helpers acting within the scope of their assigned tasks. FC The school. Labitag [2 Page 8 of 110 Liability for fault of others Obligation arising from quasi-delict is demandable not only for one s own acts or omissions. but also for those of persons for whom one is r esponsible. The owners and managers of an establishment or enterprise are likewise responsible for damages caused by their employees in the service of the br anches in which the latter are employed or on the occasion of their functions. he can recover from his employee amount paid by him Employer can avoid liability by proving that he exercised the diligence of a good father of a family to prevent damage All employers. Guardians are liable for damages caused by the minors or incapacitated persons who are under their authority and live in their company. Authority and responsibility shall apply to all authorized activities whether inside or outside the premises of the school. Art 218. FC Those given the authority and responsibility under the preceding Article shall be principally and solidarily liable for damages caused by the acts or omissions of the unemancipated minor. Lastly. All other cases not covered by this and the preceding articles shall be gover ned by the provisions of the Civil Code on quasi-delicts. or the individual. The parents. i n which case what is provided in Ar ticle 2176 shall be applicable. can be sued directly by the injured party and after he has paid the damages to such injured party. depending on whose choice it is y FACULTATIVE: multiple prestations with a principal obligation and substitute prestations. Simple only one prestation b. several are due but only one must be fulfilled at the election of the debtor b. Distributive one or some must be performed a. to give support) Bilateral OR synallagmatic contracts. purchase and sale. HOW: Divisible and Indivisible (Art 1223-1225) performance of the prestation. Individual only one subject Collective several subject 7. choice is generally given to the DEBTOR 4. Secondary Classification 1. Primary Classification under the Civil Code 1. WHO: Joint and Solidary (Art 1207-1222) multiple subjects . Positive (to give. whether it can be fulfilled in parts or not 6. mortgage Principal main obligation 8.ndSemester.g. Multiple two or more prestation i. WHAT: Alternative and Facultative (Art 1199-1206) multiple objects y ALTERNATIVE: multiple prestations but debtor will perform one or some but not all. Conjunctive all must be performed ii. Facultative main prestation and a substitute prestation and it is the debtor who chooses. emptio vendito. (As to subject matter) Real (to give) and Personal (to do or not to do) 3. two parties are reciprocally bound thus debtor and creditor of each other (e.g. A. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Legal (Art 1158) from law Conventional (Art 1159) from contracts Penal (Art 1161) from commission of a crime 2. Accessory depends on the principal obligation e. (As to subject matter of obligation) Determinate and Generic 4. ease) 6. WHEN: With a period or term (Art 1193-1198) time of demandability y PERIOD: its fulfillment or extinguishment depends upon a future and certain event 3. As to object or prestation a. WHEN: Pure and Conditional (Art 1179-1192) time of enforceability y PURE: demandable at once y CONDITIONAL: fulfillment or extinguishment depends upon a future and uncertain event 2. Labitag [2 Page 9 of 110 CLASSIFICATIONS OF OBLIGATIONS A. simple and remuneratory donation. Alternative more than one prestation but one party may choose which one. With a penal clause (Art 1226-1230) B. one debtor and one creditor (e. Unilateral only one party bound to perform obligation. Santos | UP Law B2012 accessory undertaking to assume greater liability in case of breach . pledge. not to do) 5. only one thing is due but the debtor has reserved the right to substitute it with another Karichi E.g. to do) and Negative (not to give. focuses on the tie that bonds the parties y JOINT: each can be made to pay only his share in the obligation y SOLIDARY: one can be made to pay for the whole obligation subject to reimbursement 5.Y. not to the thing which is object thereof. either physically or legally Impossible physically or legally incapable of being done Chapter II.May be qualified by contrary intentions of the parties. Accesion industrial e.g. Labitag [2 Page 10 of 110 9. Accesion natural e. he accepts the thing without protest or disposes or consumes it waiver of defect b. .ndSemester. . have for their object the co mpletion o f the latter for which they are indispensable or convenient.Why: the obligation to delivery would be illusory. or more valuable than which is due. without being designated and from others of its kind distinguished from others of the same kind Object due becomes determinable from moment of delivery Specific thing (determinate) DUTIES OF THE OBLIGOR (Letters B-D are the accessory/incidental obligations) a. . e.Though upon agreement or consent of the creditor. use or preservation of another thing or more important.Non nudis pactis. Nature and Effects of Obligations KINDS OF PRESTATION A. although the latter may be of the same value as. even though they may not have been mentioned. . Obligation TO GIVE SPECIFIC THING (determinate) GENERIC THING (indeterminate) One that is individualized and can be identified or distinguished Indicated only by its kind. Santos | UP Law B2012 . sowing Those things which. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. building. elaborated in Art 1173 o Failure to preserve the thing Liability for damages o BUT if due to FORTUITOUS EVENTS or FORCE MAJEURE Exempted from responsibility c. A. UNLESS the law or the stipulation of the parties requires another standard of care. the debtor may deliver a different thing or perform a different prestation in lieu of that stipulated DATION in payment (Art 1245) or OBJECTIVE NOVATION (Art 1291) . Does not include fruits because Art 1164 mentioned it already Accesion continua which includes: 1.Defects of the thing may be waived by the creditor IF o Expressly declares o With knowledge thereof. However.g. either naturally or artificially.g. there is no real right until the same has been delivered to him. exclude delivery of accession or accessory of the thing. to preserve thing with due care Art 1163 Every person obliged to give something is also obliged to take care of it with the proper diligence of a good father of a family .Y. to deliver the fruits Art 1164 Par 1 The creditor has a right to the fruits of the thing from the time the obligation to deliver it arises. Possible capable of being performed. sed traditione domina rerum trasferentur the ownership of things is transferred not only by mere agreements but by delivery Karichi E. alluvion 2.What kind of diligence: DILIGENCE OF GOOD FATHER OF FAMILY. ACCESSIONS ACCESSORIES Includes everything which is produced by a thing. . to deliver thing itself Art 1244 Par 1 The debtor of a thing cannot compel the creditor to receive a different one. to deliver the accessions and accessories Art 1166 Obligation to give a determinate thing includes that of delivering all its accessions and accessories . or which is incorporated or attached thereto. d. destined for embellishment. planting. No real right until delivery personal action against debtor. Right to compel delivery a.Y. action for substituted performance y Creditor may ask for compliance by 3 (Art 1165) LIMITED GENERIC THING generic objects confined to a particular class. the fulfillment of a prestation to give. rd person at debtor s ex pense.Gives to a person a direct and immediate power over a thing. whose quality and circumstances have not been stated . rights of ownership and possession PERSONAL RIGHT power belonging to one person to demand of another. Right to ask for rescission or damages 2. without a passive subject individually determined. A. Right to damages Karichi E. Failure to deliver _ Legal excuse for breach of obligation or delay: FORTUITOUS EVENT unless there is o Law e. The purpose of the obligation and other circumstances shall be taken into consideration. as a definite passive subject. which is susceptible of being exercised. against whom such right may be personally exercised . Fraud c. Right to damages a.g. Fruits (both industrial and natural from the time obligation to deliver arises).g. Any manner in contravention of the tenor of obligation Generic thing (indeterminate) Art 1246 When the obligation consists in the delivery of an indeterminate or generic thing . to do or not to do CORRELATIVE RIGHTS OF THE OBLIGEE/CREDITOR (from Sir Labitag s diagrammatical outline) 1. Right to rescission or resolution 3.ndSemester. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. not only against a determinate person but against the whole world .E. Neither can the debtor deliver a thing of inferior quality.g. possession in bad faith (Art 552) o Stipulation to the contrary o Nature of obligation requires assumption of risk _ FE APPLICABLE TO: o Nonperformance o Delay o Loss/deterioration of specific thing Art 1189 Before happening of suspensive condition Art 1190 Before happening of resolutory condition _ Debtor still liable despite FE: o Expressly specified by law Art 1942 Bailee liable for loss (commodatum) Art 2001 Act of a thief Art 2147 Negotiorum gestio Art 1993 Loss of deposit o Stipulation e. accessions and accessories b. no long FE o Liability arises from criminal act except if debtor tenders thing and creditor unjustifiably refuses to receive (Art 1268) b. Santos | UP Law B2012 . Negligence in performance d. the creditor cannot demand a thing of superior quality. debtor becomes insurer of the obligation o Assumption of risk o Fraud or malice (bad faith) Art 1165 Par 3 Delivers to two or more persons having different interest o Debtor in delay already when FE happened (Art 1165 Par 3) o Debtor guilty of concurrent negligence in this case. the class is considered in itself a determinate object CORRELATIVE RIGHTS OF THE OBLIGEE/CREDITOR (from Sir Labitag s diagrammatical outline) 1. no right against the world 2. Labitag [2 Page 11 of 110 REAL RIGHT power belonging to a person over a specific thing. Delay or default e. Obligation NOT TO DO Art 1244 Par 2 In obligations to do or not to do. Labitag [2 Page 12 of 110 a. the same shall be executed at his cost.Y. To pay damages (Art 1170. an act or forbearance cannot be substituted by another act or forbearance against the obligee s will. Not to do what should not be done 2. To pay damages (Art 1170-1172. it shall also be undone at his expense. To shoulder the cost if someone else does it (Art 1167) 3. and the obligor does what has been forbidden him. DUTIES OF OBLIGOR (from BarOps Reviewer 2008) 1. c. it may be decreed that what has been poorly done be undone. 2201-2202) Karichi E. Failure to deliver Fraud (malice or bad faith) Negligence Delay Any matter contravene the tenor of obligation RIGHTS OF A CREDITOR (from BarOps Reviewer 2008) SPECIFIC GENERIC To compel specific performance To ask for the performance of the obligation To recover damages. in case of breach of the To ask that the obligation be complied with at the obligation.Performance cannot be by a delegate or an agent . To do it (Art 1167) 2. C. . The same rule may be observed if he does it in contravention of the tenor of the obligation. To should the cost to undo what should not have been done (Art 1168) 3. d. interests from the time To recover damages in case of breach of obligation to deliver arises o bligation B. .No legal accessory obligations arise (as compared to obligation to give) Art 1268 When the obligation consists in not doing. e.ndSemester. b. Furthermore. To undo what has been poorly done (Art 1167) 4. exclusive or in addition to specific expense of the debtor performance Entitlement to fruits.Exception: FACULTATIVE OBLIGATION wherein the debtor reserves the right to substitute another prestation Art 1167 If a person is obliged to do something fails to do it. an act or forbearance cannot be substituted by another act or forbearance against the obligee s will. DUTIES OF OBLIGOR (from BarOps Reviewer 2008) 1. 2201-2202) y No action for compliance because that would be involuntary servitude which is prohibited by the constitution. A. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Obligation TO DO Art 1244 Par 2 In obligations to do or not to do . Santos | UP Law B2012 . Y.Deliberate and intentional evasion of the normal fulfillment of obligations .Fraud in the performance of a pre-existing obligation . Santos | UP Law B2012 . Labitag [2 Page 13 of 110 BREACH OF OBLIGATION CONCEPT VOLUNTARY INVOLUNTARY arises from the modes provided in Art 1170 arises because of fortuitous events Distinction between SUBSTANTIAL and CASUAL/SLIGHT breach SUBSTANTIAL CASUAL Total Partial Amounts to non-performance A part is performed Basis for rescission and payment of damages Gives rise to liability for damages GENERAL RULE: Rescission will not be permitted for a slight or casual breach of the contract.The element of INTENT and NOT the harm done is the test KINDS OF FRAUD 1. Fraud in the execution/creation/birth a. Voidable contract GIVES RISE TO Right in favor of creditor to recover Right of the inno cent party to annul damages the contract Cases: y Woodhouse v Halili y Geraldez v CA Karichi E. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. knowing and intending the effects which naturally and necessarily arise from such act or omission. Dolo incidente (Art 1338) of the contract FRAUD (Art 1171) DOLO CAUSANTE (Art 1338) DOLO INCIDENTE (Art 1344) WHEN During the performance of a prePRESENT existing obligation PURPOSE Evade the normal fulfillment of obligatio n During the perfection of a co ntract During the perfection of a contract Secure the consent of another to enter into contract Secure the consent of another to enter into contract BUT fraud was not the principal inducement in making the contract Does not result in the vitiation of consent Gives rise to a right of the innocent party to claim for damages RESULTS IN Breach of the obligation Vitiation of co nsent. Dolo causante (Art 1344) b. or a willful omission. Cases: y Song Fo v Hawaiian Phils y Velarde v CA MODES OF BREACH Art 1170 Those who in the performance of their obligations are guilty of FRAUD. Fraud in the performance (Art 1171) 2. ergo synonymous to bad faith (dishonest purpose or some moral obliquity and conscious doing of wrong) . but only for such breaches as are so substantial and fundamental as to defeat the object of the parties in making the agreement.ndSemester. or DELAY and those who in any manner CONTRAVENE THE TENOR thereof. are liable for damages.Any voluntary and willful act or omission which prevents the normal realization of the prestation. A. knowing and intending the effects which naturally and necessarily arise from such act . 1 FRAUD (Dolo) Concept Fraud is the voluntary execution of a wrongful act . .Cannot cover mistake and errors of judgment made in good faith. NEGLIGENCE. according to the circumstances. Effects of Fraud Liability for damages. Santos | UP Law B2012 .ndSemester. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. a crime or a quasi-delict (Art 1170) 2 NEGLIGENCE (Culpa contractual) Art 1172 Responsibility arising from negligence in the performance of EVERY KIND OF OBLIGATION is also demandable. Labitag [2 Page 14 of 110 Non-waiver of Future Fraud Art 1171 Responsibility arising from fraud is demandable in ALL OBLIGATIONS. . not the voluntariness Willfulness or deliberate intent to cause damage or of act or omission injury to another Liability may be mitigated by courts Liability cannot be mitigated by courts Waiver for future negligence Waiver for future fraud is void valid if simple void if gross Distinction between Culpa Aquilana and Culpa Contractual y Different provisions that apply to the two concepts. When negligence shows BAD FAITH .To permit such advance renunciations would practically leave the obligation without effect. INSURANCE: A party to a contract is relieved from the effects of his fault or negligence by a 3 rd person Karichi E. malice or wanton attitude. bad faith. hence different legal effects CULPA AQUILANA (Culpa Extra-contractual) CULPA. Any waiver of action for future fraud is VOID. the provisions of Art 1171 (responsibility arising from fraud) and Art 2201 Par 2 (responsible for all damages reasonably attributed to non-performance) shall apply. Concept absence of due diligence Art 1173 Par 1 The fault or negligence of the obligor consists in the omission of that diligence which is required by the nature of obligation and corresponds with the circumstances of the persons. y Art 2201 Par 2 In case of fraud. Distinction between Culpa and Dolo CULPA (Negligence) DOLO (Fraud) Mere want of care or diligence. y Extra-ordinary diligence required in: o Art 1733 Common carriers o Art 1744 Lesser than extraordinary o Art 1998-2002 Inn keepers. of the time and the place. Cases: y Gutierrez v Gutierrez y Vasquez v Borja Standard of care required Art 1173 Par 2 If law or contract does not state diligence which is to be observed in the performance. .Y. that which is expected of a GOOD FATHER OF FAMILY is required.The law does not prohibit the renunciation of the action for damages on the ground of fraud already committed. the obligor shall be responsible for all damages which may be REASONABLY ATTRIBUTED to the non-performance of obligation. but such liability may be REGULATED BY COURTS. hotel keepers Exemption from Liability for Negligence 1. A. Y. Damages are demandable. Karichi E.Mere reminder is not a demand because it must appear that the benevolence and tolerance of the creditor has ended. From the moment ONE of the parties fulfills his obligation delay by the other begins. That the creditor requires or demands the performance extrajudicially or judicially . Mora solvendi default on the part of the debtor y EX RE referring to obligations to give y EX PERSONA referring to obligations to do REQUISITES OF MORA SOLVENDI 1.g. Kinds of Mora a. hence there is legally no delay if this is caused by factors not imputable to the debtor (e. as when the obligor has rendered it beyond his power to perform In reciprocal obligations . which the courts may regulate according to circumstances 2. Invalidates defense of fortuitous event 3 DELAY(mora) Concept non-fulfillment of obligation with respect to time Art 1169 Those obliged to DELIVER or to DO something incur in delay from the time the OBLIGEE JUDICIALLY OR EXTRAJUDICIALLYDEMANDS from them the fulfillment of their obligations. There is no mora in natural obligations because performance is optional and voluntary 2. VALID if simple negligence only Cases: y De Guia v Manila Electric Co y US v Barias y Sarmiento v Sps Cabrido y Crisostomo v CA Effects of Negligence 1. the DEMAND by the creditor shall NOT be necessary in order that delay may exist: 1. When from the nature and the circumstances of the obligation it appears that the DESIGNATION OF THE TIME when the thing to be delivered or the service is to be rendered was a controlling motive for the establishment of the contract 3.There can be no delay if the obligation is not yet due. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. neither party incurs in delay if the other DOES NOT COMPLY or is NOT READY to comply in a proper manner with what is incumbent upon him. When the OBLIGATION or LAWexpressly so declares 2. When demand would be USELESS.Effects of mora only arise when the delay is due to the causes imputable to the debtor. Labitag [2 Page 15 of 110 2. PRESTATION is demandable and already liquidated . A. GENERAL RULE: Creditor should make demand before debtor incurs delay y Default begins from the moment creditor demands the performance of obligation. Santos | UP Law B2012 .ndSemester. Party to a contract renounces in advance the right to enforce liability arising from the fault or negligence of the other a. o If extrajudicial: date of demand o If uncertain: date of filing of complaint (for purposes of computing payment of interests or damages) positive obligations (to give and to do) and not in negative obligations (not to . VOID if gross negligence Stipulations exempting from liability for that amount to a fraud b. However. y There can only be delay in give and not to do). fortuitous events) 3. That the debtor delays performance . especially acceptance on his part.Not enough to merely fix date for performance. the debtor shall not be exempted from the payment of its price. Mora solvendi 1.Y. Debtor becomes liable for damages of the delay Karichi E. the delay places the risk of the thing on the debtor 2. Francisco) 4. Otherwise. debtor can perform at any time after the obligation has been created. even before the date of maturity. A. Mora accipiendi default on the part of the creditor y Delay in the performance based on the omission by the creditor of the necessary cooperation. Cases: y Cetus Devt Corp v CA y Santos Ventura Hocorma Foundation v Santos y Vasquez v Ayala Corporation EXCEPTION: When demand is not required 1. when the period is established for the benefit of the creditor or both of the parties). the fulfillment must be SIMULTANEOUS and RECIPROCAL GENERAL RULE: Fulfillment of parties should be simultaneous EXCEPTION: Contrary stipulation (e.g. Labitag [2 Page 16 of 110 y Demand may be in any form. y Demand must refer to the prestation that is due and not another. but also that default will commence after the period lapses 3. Offer of performance by the debtor who has the required capacity 2. debtor incurs in delay if he acknowledges his delay.ndSemester. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. hiding or disposed of the thing to be delivered b. the latter refused without justification to accept it. Burden of proof of demand on the creditor. whatever may be the cause for the loss. Creditor refuses the performance without just cause See also Art 1268 When the debt of a thing certain and determinate proceeds from a criminal offense . REQUISITES OF MORA ACCIPIENDI 1. Offer must be to comply with the prestation as it should be performed 3. provided it can be proved. e. Law so provides . UNLESS the thing having been offered by him to the person who should receive it.g. Period is the controlling motive or the principal inducement for the creation of the obligation in cases where it appears that the obligation would not have been created for a date other than that fixed (Abella v.g. Santos | UP Law B2012 . Demand would be useless performance has become impossible a. Compensatio morae parties in a bilateral contract can regulate the order in which they shall comply with their reciprocal prestations. the acknowledgement must be express. Express stipulation Insertion of the clause without further notice 2. Caused by some act or fault of the debtor. y But even if without demand. y Generally. y It is necessary however that it be lawful for the debtor to perform. installment plans) Case: y Central Bank v CA Effects of Mora A. Impossibility caused by fortuitous event but debtor bound himself liable in cases of such events Case: y Abella v Francisco b. It is also generally necessary even if a period has been fixed in the obligation. Request for extension of time for payment is not sufficient though. Cases: y Vda de Villaruel v Manila Motor Co y Tengco v CA c. and that he can perform (e. When it has for its object a determinate thing. what is required is that it is his fault or the act done contravenes their agreement Cases: y Chavez v Gonzales y Telefast v Castro y Arrieta v NARIC y Magat v Medialdea 5 ABSOLUTE NON-PERFORMANCE REMEDIES OF CREDITOR IN CASE OF BREACH Primary Remedies: 1. Action for performance (specific performance or obtain compliance) 2. Other specific Remedies A. Compensation morae 1. Implied: when after delay has been incurred. y Implies that the basis is a contractual relation between plaintiff and defendants. Accion Pauliana 3. the creditor grants an extension of time to the debtor or agrees to a novation of the obligation 2. Santos | UP Law B2012 . Karichi E. may compel the debtor to make the delivery . A. 2008-2009] OBLIGATIONS & CONTRACTS | Prof.ndSemester. in addition to the right granted him by Art 1170 (indemnification for damages). Responsibility of the debtor for the thing is reduced and limited to fraud and gross negligence 2. Action for rescission Subsidiary 1. If the obligation bears interest. The debtor may relieve himself of the obligation by the consignation of the thing C. Express b. ACTION FOR PERFORMANCE 1. Action for damages (exclusively OR in addition to either of the first actions) 3. Sec 10 Execution. satisfaction and effect of judgment. Prescription 4 CONTRAVENTION OF TENOR any illicit act which impairs the strict and faithful fulfillment of the obligation or every kind of defective performance o Malicious or negligent violation of the terms and conditions stipulated in the obligation o Must not be due to fortuitous even or force majeure. The creditor becomes liable for damages 6. default of one compensates the default of the other Cessation of effects of mora 1. Accion Subrogatoria 2.Y. All expenses incurred by the debtor for the preservation of the thing after the mora shall be chargeable to the creditor 4. which automatically pass to the creditor 3. Action for specific performance (in obligation to give specific thing) Art 1165 Par 1 When what is to be delivered is a determinate thing. the creditor. Debtor is exempted from the risks of loss of thing. ROC 39. the debtor does not have to pay it from the moment of the mora 5. otherwise there would be no liability o Immaterial whether or not the actor is in bad faith or negligent. Mora accipiendi 1. Exceptio non adempleti contractus one is not compelled to perform his prestation when the other contracting party is not yet prepared to perform his prestation. Labitag [2 Page 17 of 110 B. Renunciation by the creditor a. Responsibility for damages is indivisible. The injured party may choose between FULFILLMENT and the RESCISSION of the obligation. If it cannot be determined which of the parties first violated the contract.ndSemester. in accordance with Articles 1385 and 1388 and the Mortgage Law. creditor debtor relations arise from the same cause or identity of cause y Reciprocal obligations have a TACIT RESOLUTORY CONDITION. it may be decreed that what has been done poorly be undone . the liability of the first infractor shall be equitably tempered by the courts. if the latter should become IMPOSSIBLE . complied with at the y Delivery of anything belonging to the species stipulated will be sufficient. y The court has no discretion to merely award damages to the creditor when the act can be done in spite of the refusal or failure of debtor to do so. y The remedy is alternative . This same rule shall be observed if he does it in contravention of the tenor of the obligation . Party seeking rescission can only elect one between fulfillment and rescission. the same shall be executed at his cost . This is understood to be without prejudice to the rights of third persons who have acquired the thing. Action for substituted pe rformance or undoing of poor work (in obligation to do) Art 1167 If a person obliged to do something fails to do it. where there is reciprocity between the parties i. y Power to rescind : o Pertains to the injured party. Santos | UP Law B2012 . Furthermore. He may also seek rescission. y Only applies to reciprocal obligations. y Debtor cannot avoid obligation by paying damages if the creditor insists on the performance. party who did not perform not entitled to insist upon the performance of the contract by the defendant or recover damages by reason of his own breach Karichi E. ACTION FOR DAMAGES Art 1170 Recoverable damages include any and all damages that a human being may suffer. with the payment of damages in either case.e. it shall also be undone at his expense . 2008-2009] OBLIGATIONS & CONTRACTS | Prof. The court shall decree the rescission claimed UNLESS there be a just cause authorizing the fixing of a period . in case one of the obligors should not comply with what is incumbent upon him. Action for substituted pe rformance (in obligation to give generic thing) Art 1165 Par 2 If the thing is indeterminate or generic. the same shall be extinguished and each shall bear his own damages. 3.Y. ACTION FOR RESCISSION Art 1191 The power to rescind obligation is implied in reciprocal ones. even after he has chosen fulfillment. C. Labitag [2 Page 18 of 110 2. y EXCEPTION: Imposition of personal force or coercion upon the debtor to comply with his obligation tantamount to involuntary servitude and imprisonment for debt Cases: y Chavez v Gonzales supra y Tanguilig v CA 4. and the obligor does what has been forbidden him. A. y EXCEPTION: When the only feasible remedy is indemnification for the damages caused: _ If has become impossible to undo the thing physically or legally _ If the act is definite and will not cease even if undone B. There can be no partial performance and partial rescission. he may ask that the obligation be expense of the debtor. Action for undoing (in obligation not to do) Art 1168 When the obligation consists in not doing. Art 1192 In case both parties have committed breach of obligation . To ask for rescission of the contracts made by the debtor in fraud of their rights REQUISITES OF ACCION SUBROGATORIA 1. ex cept such as are inherently personal to him 3. leaving things in their status before the celebration of the contract 2. or susceptible of being transformed to patrimonial value for the benefit of the creditor EXCEPTIONS TO ACCION SUBROGATORIA 1. save those which are inherent in his person. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Malicious or negligent inaction of the debtor in the exercise of his right or action of such seriousness as to endanger the claim of the creditor 3. may exercise all the rights andbring all the actions of the latter for the same purpose. Creditor has an interest in the right or action not only because of his credit but because of insolvency of the debtor 2. In the case the other party impugns rescission. y Previous approval of court is not necessary y EXTENT: Plaintiff entitled only to so much as is needed to satisfy his credit. The credit of the debtor against a third person is certain. may only be claimed in substantial breach (Song Fo v. they may also impugn the acts which the debtor may have done to defraud them. can refuse to perform if the other party is not yet ready to comply _ If the injured party has already performed: cannot extrajudicially rescind IF the other party opposes the rescission (otherwise. The debtor s right against 3 rd person must be patrimonial. Santos | UP Law B2012 . Concept Action which the creditor may ex ercise in place of the negligent debtor in order to preserve or recover for the patrimony of the debtor the product of such action. Right to existence. Hawaiian Philippines) o Rescission requires judicial approval to produce legal effect _ EXCEPTION: object is not yet delivered AND obligation has not yet been performed _ If the obligation has not yet been performed: extrajudicial declaration of party willing to perform would suffice.Y. he cannot maliciously reduce such guaranty. extinction has a retroactive effect. demandable and liquidated o It is not essential that the creditor s claim be prior to the acquisition of the right by the debtor 4. Hence. Extinguishes obligatory relation as if it had never been created. y Double function: o Conserving the patrimony of the debtor by bringing into it property abandoned or neglected by him o Making execution on such property thereafter Rights of Creditors 1. rescission produces legal effect). except such as exempt by law from execution 2. Exercise all the rights and actions of the debtor. any balance shall pertain to the debtor y Patrimony of the debtor (includes both present and future property) is liable for the obligations he may contract by being a legal guaranty in favor of his creditors. Equivalent to invalidate the juridical tie. and then obtain therefrom the satisfaction of his own credit. the court comes in either to: a. Give a period to the debtor in which to perform Effects of Rescission 1. Declare the rescission as properly made b. exempting from the reach of creditors whatever he may be receiving as support b. Rights or relations of a public character Karichi E. not permitted in casual/slight breach. Its nature is a facultative resolutory condition (Taylor v Uy Tieng) SUBSIDIARY REMEDIES OF CREDITOR 1 Accion Subrogatoria (subrogatory action) Art 1177 The creditors after having pursued the property in possession of the debtor to satisfy their claims. A. Mutual restitution y EXPRESS RESOLUTORY CONDITION: automatic resolution if one of the parties does not comply with his obligation. Labitag [2 Page 19 of 110 rd _ Rights of injured party subordinated to the rights of a 3 person to whom bad faith is not imputable o Not absolute.ndSemester. Often found in insurance contracts. Levy by attachment and execution upon all the property of the debtor. Inherent rights of debtor a. whether by gratuitous or onerous title. action to establish the creditor s status as a legitimate or natural child. Rights consisting of powers which have not been used i. REQUISITES OF ACCION PAULIANA 1. and other rights arising from family relations f. Art 772 Only those who at the time of the donor's death have a right to the legitime and their heirs and successors in interest may ask for the reduction or inofficious donations. although demandable later r d person 2. 3. action for legal separation or annulment of marriage. 3 person who received the property is an accomplice in the fraud o See Rescissible Contracts for more detailed discussion on the effects of good faith and bad faith of the third party transferee (Page 89) Cases: y Khe Hong Cheng v CA y Siguan v Lim Distinction between accion subrogatoria and accion pauliana ACCION SUBROGATORIA ACCION PAULIANA Not essential that credit is prior to the acquisition o f Credit must exist before fraudulent act debtor s right Intent to defraud creditors is not required If contracts rescinded is onerous. right to a government gratuity or pension g. devisees and legatees. Santos | UP Law B2012 . giving advantage to a 3 rd person (last resort) 3. whether natural or civil. Sec 13. sub-lessee Art 1729 Laborers vs. either by express declaration.g. Patrimonial rights inherent in the persons of the debtor e.Y.g. right to revoke a donation by reason fo ingratitude. cannot be impugned by an accion pauliana. or by consenting to the donation. A. who are not entitled to the legitime and the creditors of the deceased can neither ask for the reduction nor avail themselves thereof.g. Act being impugned is fraudulent o Presumption of fraud may be found in Art 1387 (gratuitous transfer without leaving sufficient funds for obligations OR gratuitous transfers by a judgment debtor) More details in page 92 rd 5. there must be fraudulent intent No period of prescription Action prescribes within 4 years of the discovery of the fraud 3 Other specific remedies (Accion Derecta) Art 1652 Lessor vs. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. right to demand the exclusion of an unworthy heir 2. Plaintiff asking for rescission (subsidiary action) has a credit prior to the alienation. owner Karichi E. Rights of an honorary character d. Power to carry out an agency or deposit because purely personal acts iii. y Payments of pre-existing obligations already due. Non-patrimonial rights e. debtor fails to have some property leased the creditor cannot give it in lease for him ii.g.ndSemester. can be revoked by this action. The donees. Debtor has made subsequent contract. Creditor has no other remedy but to rescind the debtor s contract to the 3 4. Power to accept an offer for a contract e. Power to administer e. Labitag [2 Page 20 of 110 c. Patrimonial rights not subject to execution e. All acts of the debtor which reduce his patrimony in fraud of his creditors. Rule 39. Rules of Court 2 Accion Pauliana Art 1177 they may also impugn the acts which the debtor may have done to defraud them Art 1381 Par 3 Those undertaken in fraud of creditors when the latter cannot in any other manner collect the claims due them. Those referred to in the preceding paragraph cannot renounce their right during the lifetime of the donor. (Found under Rescissible Contracts) Concept Creditors have the right to set aside or revoke acts which the debtor may have done to defraud them. g armed invasion. Fuerza Mayor. If he creates a dangerous condition or negligence although the act of God was the immediate cause. epidemics. Cause of the unforeseen and unexpected occurrence or the failure of the debtor to comply with his obligation must be independent of human will 2. robbery. creditor chooses from remainder Karichi E. delay or violation/contravention in any manner of the tenor of the obligation. etc. Act of Man by acts of man.ndSemester. Obligor must be free from any participation in the aggravation of the injury resulting to the creditor (no concurrent negligence) Effect of CONCURRENT FAULT of the Debtor When the negligence of a person concurs with an act of God in producing a loss. vendee a retro s transferee Art 1893 Principal vs. substitution appropriated by princip EXTINGUISHMENT OF LIABILITY IN CASE OF BREACH DUE TO FORTUITOUS EVENT Art 1174 Except in cases expressly specified by law. Concept of Fortuitous Event [Force Majeure.g. or when the nature of obligation requires the assumption of risk. There must be NOfraud. e. he cannot escape liability for the natural and probable consequence thereof. etc. in case of loss of one alternative. whether due to his active intervention or neglect or failure to act. storms. provided that the fault or negligence cannot be imputed to the debtor Requisites of Fortuitous Event 1. the whole occurrence is then humanized and removed from the rules applicable to the acts of God (NPC v CA the case of Welming and the exploding dam) Cases: y Juan Nakpil & Sons v CA y Republic v Luzon Stevedoring y Dioquino v Laureano y Austria v CA y NPC v CA y Yobido v CA y Bacolod-Murcia Milling v CA y Philcomsat v Globe Telecom Extinguishment of Liability GENERAL RULE: No liability if there fortuitous events intervene SPECIFIC APPLICATION: Non performance Delay Loss and deterioration of a specific thing Art 1189 Loss without the fault of debtor in suspensive condition Art 1190 Loss without the fault of debtor in resolutory condition Art 1194 Loss without the fault of the debtor in suspensive period Art 1204 Loss of all alternative prestations Art 1205 In alternative obligations. Impossible to foresee the event which constitute the caso fortuito (ordinary) OR if it can be foreseen. though foreseen.Y. attack by bandits. all human agencies excluded B. Caso Fortuito] A. When the effect is found to be partly resulting from the participation of man. Santos | UP Law B2012 . fires. must be impossible to avoid (extraordinary) 3. no person shall be responsible for those events which could not be foreseen or which. such person is not exempt from liability by showing that the immediate cause of the damage was the act of God. for as long as that they have a force of an imposition which the debtor could not have resisted y Includes unavoidable accidents. even if there has been intervention of human element. Labitag [2 Page 21 of 110 Art 1608 Vendee a retro vs. Act of God by nature e. or when it is otherwise declared by stipulation. A. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. floods. Occurrence must be such as to render it impossible for the debtor to fulfill his obligation in a normal manner 4. negligence. were inevitable. governmental prohibitions. earthquakes. either as price for the use of the money OR as stipulated advanced determination of the damages due to the delay in the fulfillment of the obligation. Interest for the use or loan or forbearance of money.g. premiums. Interest as damages for breach or default in payment of loan or forbearance of money. A. 10 Dec 1982) (Sec. credit In case of DEFAULT . 24% per annum * Interest due shall earn legal interest from the time it is judicially demanded. with interest thereon from the date of the payment. It is also taking more interest for the use of money. Monetary Board Such interest shall not be subject to ceiling prescribed under the Usury Law (Sec. INTEREST the income produced by money in relation to its amount and to the time that it cannot be utilized by its owner. goods or No interest for use or forbearance If no stipulation re: payment of interest: * No interest shall be due unless it has been expressly stipulated in writing (Art 1956) If there is express stipulation (which must be in writing to be valid) for payment of interests. so far as they are not inconsistent with this Code. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. but no rate mentioned If there is stipulation in writing and rate of interest is agreed upo n (including commissions. It can either be moratory or compensatory. although the obligation may be silent upon this point (Art 2212) Karichi E. at rate of 12% per annum from date of judicial or extrajudicial demand .Applies to all kinds of public services but limited to risks and events that are typical of the business concerned USURIOUS TRANSACTIONS Art 1175 Usurious transactions shall be governed by special laws. e. Art 1413 Interest paid in excess of the interest allowed by the usury laws may be recovered by the debtor. good or chattels.Y. *mora = delay o COMPENSATORY interests on obligations which have an extra-contractual or delictual origin USURY contracting for or receiving something in excess of the amount allowed by the law for the loan or forbearance of money. o MORATORY paid in contractual obligations to pay a sum of money. Monetary Board Circular 905. Express stipulation by the parties c. Cases specified by law Art 552 Par 2 Possessor in bad faith Art 2001 Act of a thief Art 1165 Debtor s delay Art 2147 Officious management Art 1942 Obligation of bailee in commodatum Art 2148 Negotiorum gestio Art 1268 Proceeds in a criminal offense Art 2159 Accepts undue payment in bad faith Art 1979 & Art 1993 Depositary Art 1198 Loss of benefit to make use period b. goods. TWO CONCEPTS ON PAYMENT OF INTEREST (from Sir Labitag s handout) credit A. subject to Art 1169 (delay/mora) Loan + stipulated interest. 2. shall date of judicial demand earn 12% per annum from No stipulation as to interest for use of money If rate of interest stipulated. goods or chattels or credits than the law allows. an ethico-economic sensibility of modern society which has noted the injustices which industrial civilization has created . fees and other charges) Interest shall be 12% per annum Circular 905.ndSemester. loan or forbearance shall earn legal interest. 10 Dec 1982)) B. Art 1961 Usurious contracts shall be governed by the Usury Law and other special laws. 1. Assumption of risk . Santos | UP Law B2012 . Labitag [2 Page 22 of 110 EXCEPTIONS: a.The principle is based on social justice. and the debtor incurs in DELAY. 6% per annum interest shall begin to run only from date of judgment on amount finally adjudged by court. the legal interest. goods or credit is breached. 6% per annum shall begin to run from the o But if obligation cannot be established with reasonable certainty at time of demand. A. at the discretion of court at the rate of 6% per annum . obligation to give. e. Art 2209 MB 905 Interest can now be charged as lender and borrower may agree upon. It shall prescribed under or pursuant to the Usury Law as amended. not be subject to any ceiling Art 2209 If the obligation consists in the payment of a sum of money . and in the absence of stipulation. which is six per cent per annum . the indemnity for damages . 1994) Monetary Board Circular # 905 lifting the interest rate ceiling vs. money judgment is A. there being no stipulation to the contrary.ndSemester. Santos | UP Law B2012 . D.g. When judgment of court awarding money becomes final and executory . until demand can be established with o After thus established with reasonable certainty. interest of date of judicial or extrajudicial demand . B and C (above) shall earn 12% per annum from finality of judgment until full payment money judgment shall be considered as forbearance of credit (Eastern Shipping Lines vs. shall be the payment of the interest agreed upon. to do. CA. not to do o Interest may be imposed o No interest adjudged on reasonable certainty. Labitag [2 Page 23 of 110 C.Y. Cases: y Eastern Shipping Lines v CA (see diagram on next page) y Crismina Garments v CA y Keng Hua Products v CA y Security Bank v RTC Makati y Almeda v CA y First Metro Investment v Este del Sol Karichi E. unliquidated claims or damages . If obligation NOT consisting of a loan or forbearance of money. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Santos | UP Law B2012 .e. A. Other than payment of sum of money AND court imposed damages Yes Unliquidated i.Y. Labitag [2 Page 24 of 110 What kind of obligation? Rate of interest Accrual Payment of sum of money (i. 2008-2009] OBLIGATIONS & CONTRACTS | Prof.n dSemester.e. loan or forbearance of money) Stipulated interest (1956) PLUS 12% of (principal debt + stipulated interest) (2212) If no stipulation: 12% (as legal interest) Computed from judicial demand Computed from judicial or extrajudicial demand Obligation is breached Liquidated? Did court impose interest? (since "court discretion") 2210 Presupposes an "award of damages" for breach of obligation 6% (as legal interest in 2209) Computed from judicial or extrajudicial demand Computed from date of court 's judgment (at which time the quantification of damages may be deemed to have been reasonably ascertained Basis for computation is the amount finally adjudged. cannot be reasonably established at time of demand? Must establish claim with "reasonable certainty first" (2213 ) No 6% (as legal interest in 2209) Karichi E. Santos | UP Law B2012 .Y.n dSemester. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Computed from time of finality until its satisfaction Karichi E. Labitag [2 Page 25 of 110 12% (as legal interest) Judgment of the court awarding sum of money becomes final and executory Because allegedly "forbearance of money" in the interim period. A.Though the great Labitag don't agree much with this. more properly called as basis . clearly inferable 3. transmissible . Contains no term or condition whatever upon which depends the fulfillment of the obligation contracted by the debtor.Y. death of a person CONDITION PERIOD/TERM Determines existence of an obligation Determines demandability of an obligation Kinds of Conditions 1. y PRESUMPTIONS are rebuttable by evidence TRANSMISSIBILITY OF RIGHTS Art 1178 Subject to the laws. The receipt of a later installment of a debt without reservation as to prior installments. if there has been no EXCEPTIONS: 1. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. shall depend upon the happening of the event which constitutes the condition. Labitag [2 Page 26 of 110 FULFILLMENT OF OBLIGATIONS See Chapter 4: Payment Presumptions in payment of interests and installments Art 1176 The receipt of the principal by the creditor. Not transmissible by their very nature e. all rights acquired in virtue of an obligation are stipulation to the contrary. B. Immediately demandable and nothing would exempt that debtor from compliance therewith. the acquisition of rights. promise to give donation propter nuptias if a person gets married is not conditional (DPN presupposes marriage) _ past event cannot be a condition because it is not a future and uncertain event. without reservation with respect to the interest. PURE OBLIGATIONS Art 1179 Par 1 Every obligation whose performance DOES NOT depend upon a future or uncertain event OR upon a past event unknown to the parties is demandable at once . A. as well as extinguishment or loss of those already acquired. shall give rise to the presumption that interest has been paid . Not transmissible by law Chapter III. shall likewise raise the presumption that such installments have been paid . Different Kinds of Civil Obligations I. it should be possible _ must be imposed by the will of a party and NOT a necessary legal requisite of the act e.g. CONDITIONAL OBLIGATIONS Art 1181 In conditional obligations. purely personal rights 2. Pure and Conditional Obligations A. CONDITION _ every future and uncertain event upon which an obligation or provision is made to depend _ even though uncertain. There is a stipulation of the parties that they are not transmissible not be easily implied but clearly established or at the very least. although proof of a past event may be a condition _ TERM not uncertain but must necessarily happen e. y GENERAL RULE: If the debt produces interests.g. As to effect on obligation Art 1181 Acquisition of rights and extinguishment or loss of those already acquired Karichi E. Santos | UP Law B2012 . payment of the principal shall not be deemed to have been made unless the interests have been covered.ndSemester.g. the retroactive effect of condition OBLIGATION TO GIVE OBLIGATION TO DO or NOT TO DO Bilateral (reciprocal obligation) Courts shall determine the retroactive effect of the . debtor suffers the loss because he is still the owner o acts of administration before fulfillment not affected by retroactivity. y Contracts entered into PENDENTE CONDITIONE (before happening of suspensive condition) o CREDITOR transfers his rights prior to happening of condition e. when the obligation imposes reciprocal prestations upon the parties. But because delivery transfers real right over the thing: y 3 r d person in good faith retains ownership. the courts shall determine . UNLESS there was a different intention y Until the fulfillment of suspensive condition.ndSemester. but over it hovers possibility of termination like Sword of Damocles Effect Acquisition of rights Extinguishment or lo ss of those already acquired Also known as Condition precedent/antecedent Condition subsequent Case: y Gonzales v Heirs of Tomas SUSPENSIVE (condition precedent/antecedent) y the obligation arises. . In obligations to do or not to do that has been complied with. o DEBTOR: cannot alienate or dispose the thing. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. However. creditor cannot enforce the obligation as his right then was merely an expectancy. if he does so. however abuse of rights in guise of administration are not allowed to defeat rights of creditor o usufructuary rights not within the principle of retroactivity of conditional obligations Rights of creditor and debtor before fulfillment of condition Karichi E. Labitag [2 Page 27 of 110 SUSPENSIVE RESOLUTORY When condition fulfilled Obligation arises Obligation is extinguished When condition not fulfilled The juridical or legal tie does not appear Tie of law is consolidated. Nevertheless. The obligation is constituted when the essential elements which give rise there to concur. UNLESS from the nature and circumstances of the obligation it should be inferred that the intention of the person constituting the same was different. y REASON FOR RETROACTIVITY: Condition is only accidental and not an essential element of the obligation. upon happening. the fruits and interests during the pendency of the condition shall be deemed to have been mutually compensated. Can also be seen as Rights of creditor and debtor after fulfillment of the condition Case: y Coronel v CA Art 1187 The effects of a conditional obligation to give . in each case.g. A. y 3 r d person is in bad faith he may be compelled to deliver the thing to the creditor. the debtor can be compelled to perform.deemed to have been mutually compensated condition Unilateral . If the obligation is unilateral . not happening of condition. y LIMITATIONS ON RETROACTIVITY (as dictated by justice and required by practicability or convenience): o loss of the thing by fortuitous event.debtor shall appropriate fruits and interests received. obligation does not come into existence Retroactive effect when suspensive condition is fulfilled The binding tie of conditional obligation is produced from the time of perfection. all such contracts are abrogated and cease to have any effect upon happening of the suspensive condition.Y. but if the condition does not happen. Santos | UP Law B2012 . mortgage over the property to be delivered to him Effect: consolidate or makes effective the act performed. becomes absolute Until it takes place Obligation is a mere hope The effect flow. debtor becomes liable to creditor for damages. once the condition has been fulfilled shall retroact to the day of the constitution of the obligation. the debtor shall appropriate the fruits and interests received. ndSemester. y PAYMENT BEFORE HAPPENING OF CONDITION: Debtor may only recover what he paid by mistake before happening of suspensive condition. Case: y Lim v CA Karichi E.Applicable only to SUSPENSIVE and NOT to RESOLUTORY . the obligation shall be deemed to be one with a period subject to the conditions of Art 1197 (period was intended).Y. y No preference of credit is granted to the creditor but only allows him to bring proper action for the preservation of his rights. As to cause or origin Art 1182 When the fulfillment of the condition depends upon the sole will of the debtor the conditional r d person. . It follows the same rules. bring the appropriate action for the preservation of his right. hence if condition has been fulfilled.If the payment was for a determinate thing: accion reivindicatoria (for inexistent contracts) . RESOLUTORY (condition subsequent) y extinguishes rights and obligations already existing Cases: y Parks v Province of Tarlac y Central Philippine University v CA y Quijada v CA 2. the obligation shall TAKE obligation shall be VOID.On the part of the debtor: Does not prevent formation of valid obligation because in part depends on contingencies over which he has no control 2.If the payment was with knowledge but the condition did not happen: debtor can recover lest the creditor will be unjustly enriched. especially if creditor is in bad faith (knew that the debtor is paying before the suspensive condition has happened).Otherwise (not a determinate thing): solutio indebiti . in the power of one of the parties to realize or prevent KINDS OF POTESTATIVE CONDITION 1. . Labitag [2 Page 28 of 110 Art 1188 The creditor. .If depends exclusively on the will of creditor VALID . If it depends upon chance or upon the will of a 3 EFFECT in conformity with the provisions of this Code. he can no longer claim because of retroactivity of the condition. POTESTATIVE One which depends upon the will of one of the contracting parties. Simple potestative presupposes not only a manifestation of will but also the realization of an external act . Santos | UP Law B2012 . 2008-2009] OBLIGATIONS & CONTRACTS | Prof. The debtor may recover what during the same time he has paid by mistake in case of a suspensive condition. Sir Labitag says yes.If the payment was with knowledge of condition: implied waiver of condition and cannot recover . Purely potestative depends solely and exclusively upon the will . since the obligation is already in force Debtor s promise to pay when he can is not a conditional obligation Art 1180 When the debtor binds himself to pay WHEN his means permit him to do so. but Tolentino says we can apply principle of solutio indebiti.The law is silent as to whether fruits may be recovered like in Art 1195. though. even if made to depend upon the obligor/debtor.Hence. A.Destroys the efficacy of the legal tie Effect if fulfillment of condition depends solely on the will of the debtor VOID because it is a direct contravention of Art 1308 on mutuality of contracts and to do so is to sanction illusory conditions .Creditor will have to ask the court to fix a period because an immediate action to enforce the obligation would be premature. may before the fulfillment of the obligation. resolutory potestative (facultative) conditions are perfectly valid. If the obligation is DIVISIBLE. good customs. A. IMPOSSIBLE may either be physical (contrary to the law of nature) or juridical (contrary to law. Santos | UP Law B2012 . 2008-2009] OBLIGATIONS & CONTRACTS | Prof. and public policy AND restricts certain rights which are necessary for the free development of human activity i. including the will of third persons Cases: y Osmena v Rama y Hermosa v Longora y Taylor v Uy Tieng Piao y Smith Bell v Sotelo Matti y Rustan Pulp and Paper Mills v IAC y Romero v CA 3. As to mode POSITIVE (suspensive) Art 1184 The condition that some event happen at a determinate time shall EXTINGUISH the obligation as soon as the time expires OR if it has become indubitable that the event will not take place.e.ndSemester. Thus. and not upon the will of the contracting parties Case: y Naga Telephone Co. In the case of a negative impossible condition. condition not to change domicile. that part thereof which is not affected by the impossible or unlawful condition shall be valid . . it s considered as not written and the obligation is converted to a pure and simple one. those contrary to good customs or public policy and those prohibited by law shall annul the obligation which depends upon them. Not the act but the intention and its effect that determine the illicit character of the condition. will of a third person or other factors.g. Labitag [2 Page 29 of 110 CASUAL depends exclusively upon chance. The condition not to do an impossible thing shall be considered as not having been agreed upon. Karichi E. political rights. the criterion is subjective.Y. religion or contract marriage) ILLICIT CHARACTER determined not by the facts but by the effect upon one of the parties. family rights and constitutional rights and liberties e. thus the nullity of the promise Effect of Impossible Conditions y Annuls only obligations which are POSITIVE and SUSPENSIVE. y Applies only to contracts and not to simple and testamentary donations and to testamentary dispositions y Impossibility of condition must exist at the time of the creation of the obligation (not existence of a valid obligation subsequently rendered impossible under Art 1266 on subsequent impossibility ) y DIVISIBLE OBLIGATION: part not affected by the impossible condition shall remain valid GENERAL RULE: Impossible condition annuls the obligation dependent upon them EXCEPTIONS: o Pre-existing obligation o Testamentary disposition o Divisible obligation o Negative impossible things o Simple or remuneratory obligation Case: y Roman Catholic Archbishop of Manila v CA 4. morals. As to possibility Art 1183 IMPOSSIBLE CONDITIONS. Inc v CA MIXED depends upon the will of one of the contracting parties and other circumstances.Why? Impossibility of fulfillment implies he does not intend to be bound. LOSS 1. and the time shall be that which the parties may have probably contemplated. Disappears in such a way that its existence is unknown or it cannot be recovered Any reduction or impairment in the substance or value of a thing which does not amount to a loss. Improved at the expense of the debtor: no other right than that granted to the usufructuary y Applicable only to obligations to deliver a determinate or specific thing. DETERIORATION or IMPROVEMENT pending happening of the condition Art 1189 When the conditions have been imposed with the intention of SUSPENDING the efficacy of an obligation to give . As for obligations to do or not to do . Disappears in such a way that its existence is unknown or it cannot be recovered 3.Y. or attached to the thing that is due. Goes out of the commerce of man 3. or improvement of the thing.ndSemester. creditor may recover damages Effect of improvement MODE Karichi E. Intention of the parties is controlling. the rule in Par 2 of Art 1185 is applicable. The thing still exists at the time the condition is fulfilled. Anything added to. the parties. the provisions of 2 n d par of Art 1187 (courts shall determine) shall be observed as regards the effect of the ex tinguishment of obligation. Loss through the fault of debtor: obliged to pay damages. OR is less than what it was when the obligation was co nstituted. Art 1190 When the conditions have for their purpose the EXTINGUISHMENT of an obligation to give . unless there is a stipulation to the Not liable for damage. the provisions which with respect to the debtor. A. NEGATIVE (suspensive) Art 1185 The conditions that some event will not happen at a determinate time shall render the obligation EFFECTIVE from the moment the time indicated has elapsed OR if it has become evident that the event cannot occur. Improved by its nature. Perishes b. In case of the loss. A thing is loss when it: a. LOSS. the condition shall be deemed fulfilled at such time as may have probably been contemplated. DETERIORATION IMPROVEMENT Effect of loss or deterioration LOSS DETERIORATION Without debtor s fault Extinguished. incorporated in. are laid down in the preceding article shall be applied to the party who is bound to return . loss or deterioration of the thing during the pendency of the condition: If the thing is 1. shall return to each other what they have received. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. NO application to generic objects (genus never perishes). y Apply only in case suspensive condition is fulfilled. Loss without fault of debtor: obligation extinguished 2. Deteriorates without fault of the debtor: impairment to be borne by the creditor 4. time: inure to the creditor 6. If no time has been fixed. Deteriorates through the fault of debtor: creditor may choose between the rescission of the obligation and its fulfillment with indemnity for damages in either case 5. creditor must accept the contrary. deterioration. Mode of extinguishment Art 1262 Par 1 thing in impaired condition With debtor s fault Liable to damages upon fulfillment of condition May demand the thing OR ask for rescission. Goes out the commerce of man c. in either case. Santos | UP Law B2012 . bearing in mind the nature of obligation. but it is no longer intact. taking into account the nature of the obligation. Perishes 2. Labitag [2 Page 30 of 110 y If there is no period fixed. the following rules shall be observed in case of the improvement. upon the fulfillment of the said conditions. Art 1192 In case both parties have committed breach of obligation. the liability of the first infractor shall be equitably tempered by the courts. y Recognized implied or tacit resolutory condition imposed exclusively by law. y Also applicable to provocation of resolutory conditions Cases: y Taylor v Uy Tieng Piao supra y Herrera v Leviste C. Concept RECIPROCITY arises from identity of cause and necessarily.Y. cannot ask for a. Labitag [2 Page 31 of 110 By nature or time Inures to the benefit of the creditor by virtue of principle of retroactivity of conditional obligatio ns At debtor s expense Only usufructuary rights. RECIPROCAL OBLIGATIONS Art 1191 The power to rescind obligation is comply with what is incumbent upon him. Obligor who performed chose rescission over fulfillment or performance is impossible c. The breach is substantial so as to defeat the object of the parties in making the agreement it will not be granted in slight or casual breach y How made Rescission requires judicial approval to produce legal effect Karichi E. may in some way be prevented by the debtor from happening. rescission takes place b. two obligations are created at the same time. if the latter should become IMPOSSIBLE. the same shall be extinguished and each shall bear his own damages . Actual prevention of the compliance y Why? Party to a contract may not be excused from performing his promise by the non-occurrence of the event which he himself prevented. Action for Fulfillment When fulfillment no longer possible. He may also seek rescission.ndSemester. This is understood to be without prejudice to the rights of third persons who have acquired the thing. Intent of the obligor to prevent the fulfillment of the condition ESSENTIAL! b. Each party is a creditor and debtor of the other and they are to perform simultaneously. CONSTRUCTIVE FULFILLMENT a condition which although not ex clusively within the will of the debtor. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. even after he has chosen fulfillment. remove if possible to remove without damage to pro perty) and Art 580 (set off the improvements he may have made against any damage) Effect of prevention of the fulfillment of the condition by the obligor Art 1186 The condition shall be deemed fulfilled when the obligor voluntarily prevents fulfillment. in accordance with Articles 1385 and 1388 and the Mortgage Law. with the payment of damages in either case. One of the creditors failed to comply with what is incumbent upon him b. Governed by Art 579 (useful improvements or for mere pleasure. implied in reciprocal ones . REQUISITES: a. A. even if there is no corresponding agreement between parties it s also called RESOLUTION y Power to rescind is given to the injured party Alternative remedies of injured party in case of breach partial rescission and partial fulfillment injured party should choose only one. in case one of the obligors should not The injured party may choose between FULFILLMENT and the RESCISSION of the obligation. Action for Rescission y Requisites for rescission a. Santos | UP Law B2012 . If it cannot be determined which of the parties first violated the contract. The court shall decree the rescission claimed UNLESS there be a just cause authorizing the fixing of a period. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Extinguishes obligatory relation as if it had never been created Equivalent to invalidate the juridical tie. The same rule applies to any amount he may have taken from the partnership coffers. rescission produces legal effect). without the need of any demand. Mutual restitution Rescission Art 1380 Distinguished from Resolution Art 1191 Art 1191 Resolution Art 1380 Rescission Similarities 1. Declare the rescission as properly made b. can refuse to perform if the other party is not yet ready to comply _ If the injured party has already performed: cannot extrajudicially rescind IF the other party opposes the rescission (otherwise. Give a period to the debtor in which to perform Effects of Rescission 1. in the same cases and in the same manner as the vendor is bound with respect to the vendee. Presuppose contracts validly entered into and existing Rescission v. the court comes in either to: a. obligatio n) mainly economic injury or lesions Scope of judicial Court determines sufficiency of reaso n to justify Sufficiency of reason does not affect right to ask for control extension o f time to perform obligation (whether slight rescission (cannot be refused if all the requisites are or casual breach) satisfied) Kind of obli Only to reciprocal Unilateral. Naguiat See also: Art 1786 (Partnership) Every partner is a debtor of the partnership for whatever he may have promised to contribute thereto. He shall also be liable for the fruits thereof from the time they should have been delivered. Mutual restitution when declared proper Who may Only by a party to the contract Party to the contract suffering lesion demand Third parties prejudiced by the co ntract Grounds Non-performance (implied tacit co ndition in reciprocal Various reasons of equity provided by the grounds. Santos | UP Law B2012 . and his liability shall begin from the time he converted the amount to his own use. leaving things in their status before the celebration of the contract 2.Y. In the case the other party impugns rescission. A. Annulment: the latter there is a defect which vitiates/invalidates the contract 2. Labitag [2 Page 32 of 110 y _ EXCEPTION: object is not yet delivered AND obligation has not yet been performed _ If the obligation has not yet been performed: extrajudicial declaration of party willing to perform would suffice. reciprocal applicable to Even when contract is fully fulfilled Character Principal Remedy Secondary/Subsidiary Cases: y Song Fo v Hawaiian Philippines y Boysaw v Interphil Promotions y UP v Delos Angeles y De Erquiaga v CA y Angeles v Calasanz y Ong v CA y Visayan Saw Mill v CA y Deiparine v CA y Iringan v CA y Vda de Mistica v Sps. Art 1788 (Partnership) A partner who has undertaken to contribute a sum of money and fails to do so becomes a debtor for the interest and damages from the time he should have complied with his obligation. He shall also be bound for warranty in case of eviction with regard to specific and determinate things which he may have contributed to the partnership. (1682) Karichi E.ndSemester. he shall have no further action against the purchaser to recover any unpaid balance of the price. does not carry with it any retroactive effect Time Always to the future May refer to past event not know to the parties Will of the debtor If dependent on will of debtor. (2) Cancel the sale. the obligation is CONDITIONAL. As to effect SUSPENSIVE (Ex die) Art 1193 Par 1 Obligations whose fulfillment a day certain has been fixed. o Requisites of Period 1. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Certain 3. when the lessor has deprived the lessee of the possession or enjoyment of the thing. (n) RA 6552 Realty Installment Buyer Protection Act aka Maceda Law II. should the vendee's failure to pay cover two or more installments. Possible Period/Term vs. him to do so. although it may not be known when . Future 2. A day certain is understood to be that which must necessarily come . the vendor may exercise any of the following remedies: (1) Ex act fulfillment of the obligation. In this case. Obligations with a resolutory period take effect at once but terminate upon arrival of the day certain. a stipulation that the installments or rents paid shall not be returned to the vendee or lessee shall be valid insofar as the same may not be unconscionable under the circumstances. (3) Foreclose the chattel mortgage on the thing sold. should the vendee fail to pay. exerting an influence on obligations a s a consequence of a juridical act. Labitag [2 Page 33 of 110 Art 1484 (Sales) In a contract of sale of personal property the price of which is payable in installments. Obligation with a Period Art 1193 Obligations whose fulfillment a day certain has been fixed. and it shall be regulated by the rules of the preceding Section. whether known before hand OR at a time which cannot be predetermined Influence on the No effect on the existence. (1454-A-a) Art 1486 (Sales) In the case referred to in two preceding articles. shall be demandable only when that day comes. Any agreement to the contrary shall be void. Santos | UP Law B2012 . ANNUL Kinds of Period/Term 1. Art 1180 When the debtor binds himself to pay WHEN his means permit deemed to be one with a period . but only on their obligatio n demandability or performance. the obligation shall be Concept A space of time which. suspends their demandability or determines their extinguishment. A. o Must lapse before the performance of the obligation can be demanded o Think: incubating period o The obligor has the burden of proving any extension of the period by satisfactory evidence Karichi E. (1454-A-a) Art 1485 (Sales) The preceding article shall be applied to contracts purporting to be leases of personal property with option to buy. subject to the provisions of Art 1197. Condition AS TO TERM/PERIOD CONDITION Fulfillment Event must necessarily co me. should the vendee's failure to pay cover two or more installments.Y.ndSemester. HENCE. merely empowers court to fix such period Event is uncertain Gives rise to an obligation or extinguishes one already existing If dependent on will of debtor. If the uncertainty consists in whether the day will come or not . shall be demandable only when that day comes. if one has been constituted. As to expression EXPRESS when specifically stated upon arrival of the day IMPLIED when parties intended a period E. o Period after which the performance must terminate o Think: expiry date 2. the obligor is merely relieved of the obligation to fulfill at that time. to meet constitutional requirements: The suspension should be definite and reasonable. E. As to source CONVENTIONAL/VOLUNTARY stipulated by the parties LEGAL period fixed by law. o MORATORIUM LAWS: postponement of the fulfillment of an obligation. o Same as Art 1189 Effect of loss or deterioration LOSS DETERIORATION Without debtor s fault Extinguished. RESOLUTORY (In diem) Art 1193 Par 2 Obligations with a resolutory period take effect at once but terminate certain. deterioration or improvement before arrival of period Art 1194 In case of loss. Franchise agreement in the Constitution (for 25 years) JUDICIAL set by the courts in case of implied and indefinite periods (See: When courts may fix period) Rules in case of loss. death of a person. unless there is a stipulation to the contrary. the rules in Art 1189 shall be observed.ndSemester. As to definiteness DEFINITE refers to a fixed known date or time INDEFINITENESS event which will necessarily happen but the date of its happening is unknown The uncertainty of the date of occurrence in indeterminate period DOES NOT convert it into a condition. so long as there is no uncertainty as whether it will happen or not. then ask the courts to fix the period No need to file to actions. creditor must accept the thing in impaired condition Karichi E. Santos | UP Law B2012 .g. or when a person undertakes to do some work which can be done only during a particular season 3. Art 1180 (promise to pay when able).Y. events in civil or political life (age of majority or becoming a qualified voter) Debtor promises to pay when able or little by little or as soon as possible Two steps in dealing with an indefinite period (from Sir Labitag s lecture) 1. movable religious holidays (Holy Week). decreed by the statute. an extension of the period for the performance of the obligation. spread in the CC e.g. Art 1197 Par 3 (period has been contemplated by the parties). Make judicial demand. Make the indefinite period definite by asking for payment or making an extrajudicial demand 2. deterioration or improvement of the thing before the arrival of the day certain. However. Mode of extinguishment Art 1262 Par 1 Not liable fo r damage. Art 1682 lease of rural land and Art 1687 lease of urban land. 4. and does not stop the running of the period because in effect that would be an extension of the term of the contract. Labitag [2 Page 34 of 110 o SUSPENSION OF PERIOD: If a fortuitous event supervenes. Force majeure cannot be deducted from the period stipulated. A. 2008-2009] OBLIGATIONS & CONTRACTS | Prof.g. just ask for two prayers to avoid multiplicity of suits: (1) fix period and (2) require the debtor to comply on the fixed period (action for specific performance) The 2-in-1 action discussed by Sir Labitag is actually contradictory with Tolentino s commentary. Benefit of Period 1. A. protects himself from sudden decline in purchasing power of the currency loaned May oppose a premature demand. (Sir Labitag) o Manresa: good faith/bad faith of the creditor in accepting the premature payment is immaterial o Tolentino: In accordance with solutio indebiti. For whose benefit and its effects Creditor May demand perfo rmance anytime. but may validly pay any time before period expires E. Labitag [2 Page 35 of 110 With debtor s fault Liable to damages upon fulfillment of condition May demand the thing OR ask for rescission.ndSemester.g. when the day certain comes cannot recover o If the creditor refuses. Cases: y Lachica v Araneta y Ponce de Leon v Syjuco y Buce v CA 3. Poor him. but when judgment comes. it cannot be recovered because it is considered as tacit waiver of the benefit of the term (not only fruits and interest.g. good faith of creditor makes him liable to restore the fruits and interests insofar as it benefited him. o The same principle as regards fruits and interest is true for payment before happening of suspensive condition in Art 1188 Par 2 o Fruits and interests not recoverable in these cases: _ Reciprocal obligation and there has been a premature performance on both sides _ When the obligation is a loan on which the debtor is bound to pay interest _ When the period is exclusively for the benefit of the creditor. in either case. because the debtor who pays in advance loses nothing _ If payment was with knowledge of the term. time to raise money Presumptio n in absence of stipulation or in case of doubt Creditor must give consent first before debtor may pay in advance especially when creditor receives o ther benefits by reason of the term Debtor Both 2. debtor will have to go to the court.Y. the court shall determine such period as may under the circumstances have been probably contemplated by the parties . remove if possible to remove without damage to property) and Art 580 (set off the improvements he may have made against any damage) Effect of payment in advance Art 1195 Anything paid or delivered before the arrival period. the obligor being unaware of the period OR believing that the obligation has become due and demandable. but also principal) Note Art 1197 Par 3 In every case. may be RECOVERED . with the fruits and interests. o Only applies to obligations to give o The action only lies before the arrival of the day certain. creditor may recover damages Effect of improvement MODE By nature or time Inures to the benefit of the creditor by virtue of principle o f retroactivity of conditional obligations At debtor s expense Only usufructuary rights. payment of interest. Presumption for the benefit of BOTH the creditor and debtor Art 1196 Whenever in an obligation a period is designated. Santos | UP Law B2012 . 2008-2009] OBLIGATIONS & CONTRACTS | Prof. UNLESS from the tenor of the same or other circumstances it should appear that the period has been established in favor of one or the other. the day certain has already arrived. wants to keep his money safely invested instead of having it in his hands. but not compelled to accept before period expires E. Governed by Art 57 9 (useful improvements or for mere pleasure. the period cannot be changed by them. it is presumed to have been established for the benefit of BOTH creditor and debtor. Once fixed by the courts. When debtor loses right to make use of period Art 1198 The debtor shall lose every right to make use of the period: Karichi E. the period cannot be changed by them. choice belongs to DEBTOR ONLY y Absent indication that it is facultative. but from its nature and circumstance it can be inferred that a period was intended . Santos | UP Law B2012 . converted to a pure obligation y Does not apply to extension of period fixed by moratorium statutes When court may fix period Art 1197 If the obligation does not fix a period. UNLESS it has been ex pressly granted to the creditor. choice belongs to debtor UNLESS expressly given to creditor b. he becomes insolvent UNLESS he gives a guaranty or security for the debt dovetail with accion pauliana (prior credit although demandable later) 2) When he does not furnish to the creditor the guaranties or securities which he has promised 3) When by his own acts he has impaired said guaranties or securities after their establishment. 1. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Par 2 The debtor shall have no right to choose those prestations which are impossible. A.Y. because creditor would be Art 1199 A person alternatively bound by different prestations shall completely perform one of them. Par 2 The courts shall also fix the duration of the period when it depends upon the will of the debtor . Conjunctive all prestations must be performed to extinguish obligation 2. Right of choice debtor unless ex pressly granted to creditor Art 1200 The right of choice belongs to the debtor . Facultative One principal prestation but one or more substitutes. Period depends solely on will of debtor o If it were condition : void Cases: y Araneta v Phil Sugar Estate Development y Central Philippine University v CA supra III. the presumption is that it is ALTERNATIVE at a disadvantage if facultative. Par 3 The courts shall determine which period as may under the circumstances have been probably contemplated by the parties. Alternative Debtor must perform one of several alternatives. Labitag [2 Page 36 of 110 1) When after the obligation has been contracted. also INDEFINITE PERIOD 2. Period is implied a period was intended. enough that he is in a state of financial difficulty that he is unable to pay his debts y Par 3: impaired need not be total. and when through a fortuitous event they disappear.ndSemester. Par 2 The creditor cannot be compelled to receive part of one and part of the other undertaking. UNLESS he immediately gives new ones equally satisfactory 4) When the debtor violates any undertaking in consideration of which the creditor agreed to the period 5) When the debtor attempts to abscond shows bad faith y Par 1: insolvency need not be declared in an insolvency proceeding. the courts may fix the duration thereof. unlawful or which could not have been the object of the obligation o Grant to creditor cannot be implied o Choice may also be entrusted by the parties to a third person o LIMITATIONS ON RIGHT OF CHOICE _ Right to choose is indivisible (cannot choose part of one and part of the other) Karichi E. Facultative is never presumed. Alternative Obligations plurality of objects Concept 1. Disjunctive one or some prestations must be performed to extinguish obligation a. disappear through fortuitous event total. Once fixed by the courts. used in the sense of loss y Obligation becomes immediately due and demandable even if period has not yet expired. Labitag [2 Page 37 of 110 _ Cannot choose prestations which are impossible. a. with all the When notice produces effect Art 1201 The choice shall produce no effect except from the time it has been communicated . Santos | UP Law B2012 according to the terms of the obligation. Creditor cannot claim damages. creditor rd person to can ask the court for a 3 r d party e. ALL THE THINGS which are alternatively the object of the obligation have been LOSTor b. COMPLIANCE of the obligation has become IMPOSSIBLE . when among the prestations whereby he is alternatively bound. it becomes irrevocable . as none of them can extinguish the obligation alone o Solidary: choice by one will be binding personally upon him. sheriff. . through the fault of the debtor . not liable for damages because he can still comply by performing the remaining prestations even if there is only one (Art 1202) LOSS THROUGH FORTUITOUS EVENTS: obligation is extinguished. only one is practicable. o Sir Labitag: Substituted performance when the debtor does not want to make a choice. . because it s the debtor s call Art 1203 If through the creditor s act . communicated to the other party is sufficient unilateral declaration of will Only possible EXCEPTION: Debtor has chosen a prestation which could not have been the object of the obligation. Notice of selection/choice may be in any form provided it is sufficient to make the other party know that election has been made. y Once the selection has been communicated. clerk of court. A. Par 2 The indemnity shall be fixed taking as a basis the VALUE of the last thing which disappeared OR that of the service which last became impossible. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. The impossibility of the act must not be due to creditor s act where Art 1403 shall apply. but not as to other (bakeeet?!) Right to choose is not lost by the mere fact that the party entitled to choose delays in making his selection. unlawful or could not have been the object of the obligation (Art 1200. Applies to cases where the debtor has the right to choose If only some of the prestations are lost/impossible. o Orally o In writing o Tacitly tacit declaration of the selection may be done: _ performance by the debtor who has the right to choose or in the acceptance of a prestation by the creditor when he has the right of selection _ when the creditor sues for the performance of one of the prestation o Any other unequivocal terms Law does not require the other party to consent to the choice made by the party entitled to choose.Y. Par 3 Damages other than the value of the last thing or service may also be awarded. debtor not liable for damages Karichi E.g. the debtor cannot make a choice the latter may rescind the contract with damages .ndSemester. Impossibility due to creditor Art 1204 The creditor shall have a right to indemnity for damages when. y The obligation is converted to a simple obligation to perform the prestation chosen. creditor s consent thereto would bring about a novation of the obligation PLURALITY OF SUBJECT o Joint: choice must be consented by all. or any other knowledgeable 3 choose Effect of loss or impossibility of one or all prestations Art 1202 The debtor shall lose the right of choice. Converted to a simple and pure obligation. A mere declaration of the choice. Par 2) Effect of notice of choice y The effect of notice of choice is to limit the obligation to the object or prestation selected consequences which the law provides. BUT once the substitution has been made. A. FACULTATIVE OBLIGATION Art 1206 When only one prestation has been agreed upon. 2. the responsibility of the debtor shall be governed by the following rules: 1. Joint and Solidary Obligation plurality of subjects. with a right to damages. Par 2 Until then. loss of one alternative gives rise to liability Effects of Substitution o Before the substitution is effected. but the obligor may render another in substitution. when the object is unlawful o r outside the commerce o f man) invalidates the obligation. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. the juridical tie that binds them JOINT OBLIGATIONS Karichi E. and he cannot be held for damages. or that which remains if only one subsists. Loss of substitute does not make debtor liable. o IF the substitute prestation becomes impossible due to the fault or negligence of the debtor obligation is not affected.Y. Concept Only one prestation is due. o From the time the debtor communicates to the creditor that he elects to perform the substitute prestation. or the price of that which. If ONE of the thing is LOSTthrough fortuitous event . If ALL the things are LOSTthrough the fault of the debtor . the obligation shall cease to be alternative from the day when the selection has been communicated to the debtor. Par 3 the same rules shall be applied to obligations to do or not to do .ndSemester. Santos | UP Law B2012 . does not render him liable. the substitute is not the prestation that is due. the obligation is called facultative . the obligor is liable for the loss of the substitute on account of his delay . OR SOME OR ALL of the prestations should become IMPOSSIBLE . Par 2 The LOSTor DETERIORATION of the thing intended as a substitute through the negligence of the obligor. If the LOSSof ONE of the things occurs through the fault of the debtor . also with indemnity for damages. the accessory being only a means to facilitate payment Nullity of the principal prestation (e. even if he acts with bad faith in rendering the substitute impossible. but the obligor reserved the right to render another in Distinguished from Alternative Obligation AS TO ALTERNATIVE FACULTATIVE Contents of Various prestations all of which co nstitute parts of the the obligation obligatio n Nullity of Nullity of one prestation does not invalidate the prestation obligatio n which is still in force with respect to those which have no vice Creditor can choose from the remainder substitution Only the principal constitutes the obligation . the choice by the creditor shall fall upon the price of any of them. Creditor cannot demand the substitute even when this is valid. the creditor may claim any of those subsisting. negligence or fraud . he shall perform the obligation by delivering that which the creditor should choose from the remainder. 3. substitution is effective. IV. unless substitution has been made Debtor is liable Loss of the substitute before substatio n does not render debtor liable Effect of Loss (through fault) Debtor no t liable if other prestation still available If choice belongs to creditor.g. Choice Right to choose may be given to the creditor Only the debtor can choose the substitute prestation Effect of Loss Only the IMPOSSIBILITY OF ALL the prestations due Impossibility of the principal prestation is sufficient to (fortuitous witho ut fault of the debtor extinguishes the obligation extinguish the obligation. in case ONE. through the fault of the debtor has disappear. Labitag [2 Page 38 of 110 Art 1205 When the choice has been expressly given to the creditor . even if the substitute is event) possible. Solidary obligations exist only by: o Stipulation of the parties Karichi E. Sir Labitag describes it as a solid steel cable that binds the parties. Each creditor may enforce the entire obligation and each debtor may be obliged to pay it in full. and each creditor is entitled only to a proportionate part of the credit. Extent of right of creditor 1. and each creditor is entitled to demand the whole obligation. JOINT DIVISIBLE OBLIGATION: defense of res judicata is not extended from one debtor to another b.Y. Each creditor can recover only his share of the obligation and each debtor can be made to pay only his part. There is a SOLIDARY LIABILITY only when the obligation expressly so states OR when the law OR the nature of the obligation requires solidarity. the credits or debts being considered distinct from one another. Interruption of prescription by the judicial demand of one creditor upon a debtor does not benefit the other creditors nor interrupt the prescription as to other debtors c. or the nature or the wording of the obligations to which the preceding article refers the contrary does not appear. Sir Labitag describes it as a thin plastic rope or string that binds the parties. A. Determination of the shares in the demandability of the fulfillment of the obligation Words used to indicate joint obligations o Mancomunada o Mancomunada Simple o Pro rata o We promise to pay used by two or more signers Presumptions in Joint Obligations Art 1207 The concurrence of two or more creditors or of two or more debtors in one and the same obligation does not imply that each one of the former has a right to demand. Requisites of Joint Obligations 1. Only with respect to his particular share in the debt 2. Demand by one creditor upon one debtor produces the effects of default only with respect to the creditor who demanded and the debtor on whom the demand was made. Labitag [2 Page 39 of 110 Concept Each of the debtors is liable only for a proportionate part of the debt. Extent of liability of debtor 1.ndSemester. y Remission: Benefits only the joint co-debtor in whom the remission is granted. In case of: y Novation: Affects only the share of the joint co-debtor in whom the novation is created y Compensation: Affects only the share of the joint co-debtor in whom the compensation takes place y Confusion: Art 1277 Confusion does not extinguish a joint obligation except as regards the share corresponding to the creditor or debtor in whom the two characters concur. Art 1208 If from the law. OR that each one of the latter is bound to render entire compliance with the prestations. subject to the Rules of Court governing the multiplicity of suits. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. The insolvency of a debtor does not increase the responsibility of his co-debtors nor does it authorize a creditor demand anything from his co-creditors 4. Santos | UP Law B2012 . obligation extinguished SOLIDARY OBLIGATIONS Concept Each of the debtors is liable for the entire obligation. but not with respect to others 2. Vices of each obligation arising from the personal defect of a particular debtor or creditor does not affect the obligation or rights of the others 3. Plurality of subjects 2. Joint character is presumed Equal shares Effects of Joint Obligation a. the credit or debit shall be presumed to be divided as many equal shares as there are creditors or debtors. As to uniformity UNIFORM same terms and condition for all VARIED/NON-UNIFORM Art 1211 Solidarity may exist although the creditors and the debtors may not be bound in the same manner and by the same periods and conditions. Labitag [2 Page 40 of 110 o Law o Nature of obligation o Charge of condition is imposed upon legatees or heirs o Imputed by final judgment upon several defendants Requisites of Joint Obligations 1. two or more managers Art 2157 Joint payees in solutio indebiti (payment is not due) Art 119. RPC CONVENTIONAL by stipulation of parties REAL nature of the obligation requires b. 2008-2009] OBLIGATIONS & CONTRACTS | Prof.ndSemester. A. each is liable to pay the whole to the common creditor _ Mutual guaranty simultaneously active and passive PASSIVE MIXED c. each has right to collect the whole of the prestation from the common debtor _ Mutual representation Each creditors represents the other in the act of receiving the payment and in all other acts which tend to secure the credit or make it more advantageous _ Death of solidary creditor does not transmit the solidrity to each of his heirs but all of them taken together _ The credit and its benefit are divided equally among the creditors UNLESS there is an agreement among them to divide differently solidarity of debtors . or the nature or the wording of the obligation ) LEGAL Art 1915 Two or more principals appointed an agent for common transaction. solidarily liable to agent Art 1945 Two or more bailees to whom a thing is loaned in the same contracts (commodatum) Art 2194 Joint tortfeasors Art 2146 Joint officious management. Effects of non-uniform solidary liability only the portion due at the time of the demand is collectible from any of the debtors or by anyone of the creditors Karichi E. Plurality of subjects 2. As to parties bound ACTIVE solidarity of creditors . As to source Art 1208 From law. Santos | UP Law B2012 .Y. Determination of the shares in the demandability of the fulfillment of the obligation Words used to indicate joint obligations o Mancomunada solidaria o Joint and several o In solidum o I promise to pay followed by the signature of two or more persons o Individuall and collectively Sir Labitag s magic shortcut formula (applicable only to joint liability on both sides o # of debtors x # of creditors = divisor of the total amount of obligation KINDS OF SOLIDARY OBLIGATIONS a. made by any of the solidary creditors OR with any of the solidary debtors. (Art 1217. (Quiombing v CA) The demand made against one of them shall not be an obstacle to those which may be subsequently be directed against others. and the latter need not thereafter pay the obligation to the former. confusion or remission of the debt. compensation. Labitag [2 Page 41 of 110 Cases: y Inchausti v Yuli y Lafarge Cement Philippines v Continental Cement EFFECTS OF SOLIDARY OBLIGATIONS a. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. novation. (Art 1212) o E. rd person. shall extinguish the obligation. wherefore Tolentino concludes that the provision is unhappily inaccurate . but if a judicial demand is made against him. (Art 1216) y Payment made by one of the solidary debtors extinguishes the obligation. shall be liable to others for the share in the obligation corresponding to them (Art 1215 Par 2) o Remission done by several but not all of the creditors: those who made it do not have action against each other. If simultaneous. but all of them liable for the share of one who does not remit Prejudicial acts prohibited y Each one of the solidary creditors may do whatever is useful to the others. compensation. Santos | UP Law B2012 . In case of novation. o To harmonize with Art 1215: The prejudicial acts are valid as to the debtor. Par 1) y Each creditor may renounce his right even against the will of the debtor. as well as he who collects the debt. compensation. so long as the debt has not been fully collected .e. A. confusion. _ Does not apply to MIXED SOLIDARITY: solidary co-debtor may pay in behalf of the one to whom demand has been made AND to any of the solidary creditors y The creditor may proceed against ANY ONE of the solidary debtors or SOME or ALLof them simultaneously .ndSemester. he must pay only to the plaintiff. remission by a creditor y Novation. without prejudice to the provisions of Art 1219 i. responsibility of a solidary co-debtor with respect to reimbursement prior to his remission (Art 1215 Par 1) ii.g. _ DEMAND BY SEVERAL CREDITORS: Pay the one who notified him first. _ Payment to creditor who did not sue is a payment to 3 _ Same effect granted to extrajudicial demand. i.Y. confusion. remission y The creditor who may have executed any of these acts. but not anything which may be prejudicial to the latter. Solidary co-creditor/s In case of novation. the creditor may choose which to accept . If two or more solidary debtors offer to pay. (Art 1214) _ Judicial demand revokes the tacit mutual representation of co-creditors. though not perpetually: only until such time the action exists. but not with respect to the co-creditors whose rights subsists and can be enforced against the creditor who performed prejudicial acts Assignment of rights not allowed y Solidary creditor cannot assign his rights without the consent of others (Art 1213) Karichi E. debtor reserves the right to choose. SOLIDARY CREDITOR in relation to: Common debtor Right to demand y Debtor may pay to any solidary creditor. remission. compensation and merger/confusion o Take note that the same act is permitted by Art 1215. but co-debtors have right against guilty debtor Karichi E. with the interest for the payment already made. no interest for the intervening period may be demanded. obtained by one of the solidary debtors. i. Implies mutual confidence may take into account the personal qualification of each creditor. (Art 1217. the provisions of the preceding paragraph shall apply. for the price and payment of damages and interests. Par 1) y Solidary co-debtor who paid may reimburse from his co-debtors only the share which corresponds to each. A. (Art 1218) Also applies to prior total remission in favor of one debtor y The remission made by the creditor of the share which affects one of the solidary debtors does not release the latter from his responsibility towards the co-debtors. remission by a creditor y Extinguishes the obligation without prejudice to the responsibility of a solidary co-debtor with respect to reimbursement prior to his remission (Art 1215 Par 1) ii. in case debt had been totally paid by anyone of them before remission was effected. (Art 1217.Y.ndSemester. but if the payment is made before debt is due. Par 3) Converted into a Joint Obligation as to co-debtors. without prejudice to their action against the guilty or negligent debtor. Solidary co-debtor In case of payment by a co-debtor y Payment by one of the solidary co-debtors extinguishes the obligation. the obligation as to the creditor is already extinguished and nothing more to remit even partially) Relationship of the creditor with the solidary debtor does not ex tend to the relationship among solidary co-debtors y The remission of the whole obligation. Par 3) LOST or IMPOSSIBLE without fault / fortuitous event Obligation is extinguished LOST or IMPOSSIBLE with fault of any one All liable for damages and interest. his share will be borne by all his codebtors in proportion to the debt of each. o Assignment of rights allowed as to co-creditor b. (Art 1217. (Art 1221. Par 3) y Payment by co-debtor does not entitle him to reimburse from co-debtors if such payment is made after the obligation has prescribed or become illegal. confusion. but no real case of subrogation because the old one is extinguished and the new one is created Partial payment: may recover only insofar as the payment exceeded his share of the obligation y When one of the solidary debtors is insolvent and cannot reimburse. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. (Art 1219) Applies when one of the debtors has already paid the obligation in full (in such a case. Par 2) Guilty creditor who pays indemnity cannot recover from his co-debtors. does not entitle him to reimbursement from his co-debtors. SOLIDARY DEBTOR in relation to: Common creditor Obligation to perform y Each one of the solidary co-debtor is bound to render entire compliance with the prestations (Art 1207) In case of novation. (Art 1220) In case of fortuitous event y If the thing has been LOST OR if the prestation has become IMPOSSIBLE without the fault of the solidary debtors. Other co-debtors who pay the indemnity can recover the full amount from the guilty co-debtor. the obligation shall be extinguished (Art 1221. (Art 1221. Labitag [2 Page 42 of 110 o Why? As a solidary creditor. cannot assign that agency without the consent of his principals. y If through a fortuitous event . compensation. Santos | UP Law B2012 . ALL shall be responsible to the creditor. he is an agent of others. Par 1) y If there was fault on the part of any one of them. the thing is LOST or the performance of the prestation has become IMPOSSIBLE after one of the solidary debtors has incurred in delay through the judicial or extra-judicial demand upon him by creditor. that is liable only to a proportionate share. may share is not yet due. all other means of defense which may invalidate the original contract y Sir Labitag: Look for these things because it will give you a total defense: i.g. minority. A. Vices of consent ii. insanity. collective action is expressly required for prejudicial acts) Karichi E. intimidation (sufficient causes to annul consent) y Partial defense e. but co-debtors have right against guilty debtor LOST or IMPOSSIBLE without fault / fortuitous event but after any one incurred in delay Cases: y Jaucian v Querol y RFC v CA y Quiombing v CA y Inciong v CA DEFENSES AVAILABLE TO A SOLIDARY DEBTOR AGAINST THE CREDITOR Art 1222 A solidary debtor may. but the performance is indivisible. If personally to the co-debtor: partial defense Cases: y Inchausti v Yulo supra y Alipio v CA JOINT INDIVISIBLE OBLIGATIONS Concept Their tie is joint. non-existence of the obligation because of illicit cause. If personal one: only him benefited (exclusively) 3. object or absolute simulation. avail himself of all defense which are of four types : 1. extinguishment of the obligation such as by payment and remission.Y. nullity due to defect in capacity or consent of all the debtors (minority. (Art 1209) Several creditors or debtors but the prestation is indivisible. One in which the object of the object or prestation is indivisible. Personal defenses y Total defense e. fraud or violence). while the tie between the parties is joint. Labitag [2 Page 43 of 110 All liable for damages and interest. If derived from the nature: all the solidary co-debtors are benefited 2. not susceptible of division. Those personally belonging to the other co-debtors avail himself thereof only as regards that part of the debt for which the latter are responsible y Partial defense only for the debtor-defendant y E. 2008-2009] OBLIGATIONS & CONTRACTS | Prof.g.g. so you can only compel me to give my share EFFECTS OF THE DEFENSES 1. the co-debtor s share is not yet due.g. obligation is joint unless solidary has been stipulated Midway between joint (no creditor can do prejudicial acts to others. Santos | UP Law B2012 . fraud. Cause of action has prescribed iii.ndSemester. no debtor can be made to answer for the others) and solidarity (fulfillment requires the concurrence of all the debtors. Defenses pertaining to his share y Partial defense y E. special terms or conditions affecting his part of the obligation 3. violence. non-performance of suspensive condition or non-arrival of period affecting the entire obligation. BUT if just one. so you can only compel me to give the share of the co-debtors 4. Entire obligation is void iv.g. unenforceability because of lack of proper proof under the Statute of Fraud. Those derived from the nature of the obligation y Connected with the obligation and derived from its nature y Constitutes a total defense y E. in actions filed by the creditor. Voidable at the instance of all of them . you can use the defense as well 2. If he delivers to only one. Provisions of law affecting the prestation Karichi E. debtor can legally perform the obligation by parts and the creditor cannot demand a single performance of the entire obligation.Y. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Santos | UP Law B2012 . Effects of Joint Indivisible Obligation Art 1209 If the division is impossible. If one of the debtors cannot comply. Damages are divisible and each creditor can recover separately his proportionate share. non-compliance with undertaking 2. Indivisibility distinguished from solidarity Art 1210 The indivisibility of an obligation does not necessarily give rise to solidarity. One who is ready and willing to comply will pay his proportionate share plus damages when his financial condition improves. A. Labitag [2 Page 44 of 110 Sir Labitag s example: obligation to assemble a jeepney between three different specialist: mechanic. Objective or purpose of the stipulated prestation 3. DIVISIBILITY OF THINGS different from DIVISIBILITY OF OBLIGATIONS o Divisible Thing: When each one of the parts into which it is divided forms a homogenous and analogous object to the other parts as well as to the thing itself o Indivisible Thing: When if divided into parts. The debtors who may have been ready to fulfill their promises shall not contribute to the indemnity beyond the corresponding portion of the price of the thing or of the value of the service which the obligation consists. welder. Nor does solidarity of itself imply indivisibility. Creditor must proceed against all the joint debtors. Nature of the thing 4. its value is diminished disproportionately Test of Divisibility 1. Liability for damages in case of breach Art 1224 A joint indivisible obligation gives rise to indemnity for damages from the time anyone of the debtors does not comply with his undertaking .. liable for non-performance as to other creditors. Debtor must deliver to all the creditors. the right of the creditors may be prejudiced only by their collective acts 1. the obligation is converted into monetary consideration (liability for losses and damages). Gives rise to indemnity for damages. 1.ndSemester. Debtors ready to fulfill shall not be liable V. Co-debtors not liable for the share of the insolvent debtor 3. because the compliance of the obligation is possible only if all the joint debtors would act together. Creditors prejudiced only by their collective acts 2. 5. Will or intention of the parties 2. 4. upholsterer or car painter. DIVISIBLE AND INDIVISIBLE OBLIGATION thing which is the object thereof performance of the pres tation and not to the DIVISIBLE OBLIGATIONS Concept One which is susceptible of partial performance . an obligation is indivisible if so provided by law or intended by parties . A. Obligation to give definite things 2. even though the object or service may be physically divisible. the accomplishment of work by metrical units or analogous things which by their nature are susceptible of partial performance . Santos | UP Law B2012 . Labitag [2 Page 45 of 110 Effects of Divisible Obligations 1. shall be divisible . CONVENTIONAL Art 1225 Par 3 However. INDIVISIBLE OBLIGATIONS Concept Whatever may be the nature of the thing which is the object thereof. Distinguished from Solidary Obligations. Art 1233 A debt shall not be understood to have been paid unless the thing or service in which the obligation consists has been completely delivered or rendered as the case may be.ndSemester. even though the object or service may be physically divisible. Divisibility and indivisibility in obligations not to do Art 1225 Par 4 In obligations not to do. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. character of the Karichi E.). obligations to give definite things not susceptible of partial performance shall be deemed to be indivisible . 2. when it cannot be validly performed in parts. an obligation is indivisible if provided by law or intended by parties. 1. Presumptions in Indivisible Obligations OF INDIVISIBILITY Art 1225 Par 1 For the purposes of the preceding articles. divisibility or indivisibility shall be determined by the prestation in each particular case. obligations to give definite things not susceptible of partial performance shall be deemed to be indivisible. Kinds of Indivisible Obligations NATURAL Art 1225 Par 1 For the purposes of the preceding articles.Y. Presumption of indivisibility also applies in obligations to do so and those which are OF DIVISIBILITY Art 1225 Par 2 When the obligation has for its object the execution of certain number of days of work. Not susceptible of partial performance and those which are LEGAL Art 1225 Par 3 However. g. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. unless that right is expressly granted to him OBLIGATIONS WITH A PENAL CLAUSE FACULTATIVE OBLIGATION Payment of the penalty in lieu of the principal can be made only Power of the debtor to make substitution is absolute Karichi E. but can be any other thing stipulated by the parties. without the fault of the penalty debtor. the obligation is deemed fully performed (Art 1235) 3. Art 1233 A debt shall not be understood to have been paid unless the thing or service in which the obligation consists has been completely delivered or rendered as the case may be. 2. When the creditor accepts performance.). Ad terrorem clause Generally a sum of money. EXCEPTIONS: a. Labitag [2 Page 46 of 110 Effects of Indivisible Obligations 1. and the price is apportioned to each of them VI. OBLIGATIONS WITH A PENAL CLAUSE Concept An accessory undertaking to assume greater responsibility in case of breach. still leaves the other subsisting He cannot choose to pay the penalty to relieve himself of the The debtor an choose which prestation to fulfill principal obligation. Santos | UP Law B2012 .ndSemester. e. PRINCIPAL OBLIGATION ACCESSORY OBLIGATION Can stand alone. A. it is the very beginning fulfillment of the condition that gives rise to the o bligation Accessory obligation (penalty) is dependent upon nonPrincipal obligation itself is dependent upon an uncertain event performance of the principal obligation OBLIGATIONS WITH A PENAL CLAUSE ALTERNATIVE OBLIGATION Only one prestation and it is only when this is not performed Two or more obligations are due. including an act or abstention Double function: (1) provide for liquidated damages and (2) strengthen the coercive force of the obligation by the treat of greater responsibility in the event of breach Mere non-performance of the principal obligation gives rise to damages PENAL CLAUSE constitutes an exception to the general rules on the recovery of losses and damages. Art 1224 A joint indivisible obligation gives rise to indemnity for damages from the time anyone of the debtors does not comply with his undertaking . death of creditor (division among heirs) Entire and Severable Contracts depends upon the consideration to be paid. Attached to an obligation to insure performance. e. and without protest. The debtors who may have been ready to fulfill their promises shall not contribute to the indemnity beyond the corresponding portion of the price of the thing or of the value of the service which the obligation consists. Sir Labitag: yearly subscription to Herald Tribune y SEVERABLE consideration is expressly or by implication apportioned.g. 4. but fulfillment of one of them that the penal clause is enforceable is sufficient Impossibility of the principal obligation also extinguishes the Impossibility of one of the obligations. not upon its object y Not in the syllabus but Sir mentioned in passing during lecture y ENTIRE consideration is entire and single.Y. Obligation has been substantially performed in good faith (Art 1234) b. a. part to be performed by one party consists in several distinct and separate items. See Joint Indivisible Obligations Cessation of Indivisibility a) Natural Indivisibility: conversion of the obligation to pay damages b) Conventional/Legal Indivisibility: novation. independent of other obligations Attached to the principal in order to complete it or take their place in case of breach OBLIGATIONS WITH A PENAL CLAUSE CONDITIONAL OBLIGATION There is already an existing o bligation (the principal) from the No obligation before the suspensive condition happens. knowing its completeness. the question of indemnity for damage is not resolved. Labitag [2 Page 47 of 110 by express stipulation Creditor may demand both prestation as long as such right is granted to him (i. besides the penalty subsists.Y. Santos | UP Law B2012 by ex press stipulation of the parties . Can be both assumed by a third person. As to effect SUBSIDIARY only the penalty may be enforced y Presumed in Art 1227: Cannot demand the fulfillment of the obligation and the satisfaction of the penalty at the same time COMPLEMENTARY both principal obligation and penalty may be enforced y Only occurs by express stipulation of the parties 2.ndSemester. As to purpose PUNITIVE the right to damages. SIMILARITIES 1. Principal obligation and the penalty can be assumed by the Principal debtor cannot be the guarantor of the same obligation same person. called the guarantor. 3. Kinds of Penal Clause 1. There is an express provision to that effect 2. A. Par 1: Shall substitute the indemnity for damages and the payment of interests in case of non-compliance y Sir Labitag: pre-agreed measure prior to the breach y Cases when damages and interest may be recovered in addition to the penalty 1. and it represents the estimate of the damages that a party might suffer from non-performance of the obligation. They are both intended to insure the performance o f the principal obligation. Debtor is guilty of fraud in the non-fulfillment of the obligation Karichi E. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. it s purpose is to bludgeon the debtor into performing the obligation y The Courts are authorized to reduce the damages if: o They find that the breach was not one that is wanton (noodles) or done in callous disregard for the rights of the creditor o Treble damages REPARATORY substitutes the damages suffered by creditor.e. To pay the penalty is different from the principal obligation The object of the obligations of the principal debtor and the guarantor is the same. Penalty is extinguished by the nullity o f the principal obligation. However. but remains subsisting y Only occurs by express stipulation of the parties y Sir Labitag: value of the penal clause is much more than the value of the principal. As to source CONVENTIONAL LEGALby law 3. They are both accessory and subsidiary obligations. the same principle will apply as in the case of a guaranty. the matter of damages is generally resolved. 2. binds himself to fulfill the obligatio n of the principal debtor in case the latter should fail to do so. Guaranty subsists even when the principal obligation is voidable except when the penal clause is assumed by a third person o r unenforceable or is a natural one. Debtor refuses to pay the penalty 3. if the penal clause is assumed by a third person. thereby avoiding the difficulties of proving such damages y Presumption in Art 1226. complementary penalty) OBLIGATIONS WITH A PENAL CLAUSE GUARANTY Creditor can never demand both prestations Contract by virtue of which a person. becomes a facultative obligation Cases: y Makati Development Corporation v Empire Insurance y Tan v CA y Country Bankers Insurance v CA 2. Debtor refuses to pay the penalty 3. Substitute for indemnity for damages and payment of interest (Art 1226) EXCEPTION: Unless there is a stipulation to the contrary e. (Art 1228) c.g.ndSemester. The nullity of the principal obligation carries with it that of the penal clause. When creditor elected fulfillment but the same has become impossible (Art 1227) y HOWEVER. Only when the non-performance is due to the fault or fraud of the debtor b. y Partial quantity or extent of fulfillment y Irregular form of fulfillment y Only applies to penalties prescribed in contracts and not to collection of the surcharge on taxes that are due. Labitag [2 Page 48 of 110 Demandability of penalty Art 1226 Par 2 The penalty may be enforced only when it is demandable in accordance with the provisions of Code. Not exempt debtor from performance penalty is not a defense for leaving obligation unfulfilled Art 1227 The debtor cannot exempt himself from the performance of the obligation by paying the penalty EXCEPTION: Where this right to substitute penalty has been expressly reserved for him 3. Creditor cannot collect other damages in addition to penalty Art 1226 Substitute the indemnity for damages and the payment of interest in case of non-fulfillment * EXCEPTIONS: 1. There is an express provision to that effect 2. Debtor is guilty of fraud in the non-fulfillment of the obligation When penalty shall by equitably reduced Art 1229 The judge shall equitably reduce the penalty when the principal obligation has been partly or irregularly complied with by the debtor. Santos | UP Law B2012 . Even if there is no performance . which is mandatory on the collector Effects of Nullity of Principal Obligation or Penal Clause Art 1230 The nullity of the penal clause does not carry with it that of the principal obligation. Nullity of principal obligation Also nullifies the penal clause EXCEPTIONS: Penal clause may subsist even if the principal obligation cannot be enforced r d person precisely for an obligation which is unenforceable. Burden of proof for the excuse on the debtor. Non-performance gives rise to the presumption of fault creditor does not need to prove the fault of the debtor. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. A. the penalty may also be reduced by the courts if it is iniquitous or unconscionable. y When the penalty is undertaken by a 3 natural or voidable assumes a form of guaranty which is valid under Art 2052 Karichi E. penalty not enforceable when the principal obligation becomes IMPOSSIBLE: y Due to fortuitous event y Because the creditor prevents the debtor from performing the principal obligation Effects of penal clause 1.Y. a. GENERAL RULES: 1. Creditor cannot demand both performance and penalty at the same time Art 1227 Neither can the creditor demand the fulfillment of the obligation and the satisfaction of the penalty at the same time EXCEPTION: Unless this right has been clearly granted him 4. vendor knew that the thing was inexistent at the time of the contract. Normal debtor voluntarily performs the prestation stipulated b. apart from its extinctive effect in some contracts such as partnership and agency . Payment or Performance CONCEPT Fulfillment of the prestation due. payment should be the very same obligation/prestation promised to be performed/not performed Karichi E. LICIT. Santos | UP Law B2012 .ndSemester.Annulment .Mutual dissent (opposite of mutual agreement) . Confusion or Merger of the rights of the creditor and debtor E. damages shall be determined by the same rules as if no penalty had been stipulated Penal clause may be void because it is contrary to law. Manner. Condonation or Remission of the debt D. Thing to be paid 4. A.g. time and place of payment Kinds of Payment a.Rescission . Nullity of penal clause Does not affect the principal obligation In the case of non-performance . Modes of Extinguishment Art 1231 Obligations are extinguished: A. Art 662 (abandonment of interest in a party wall) and abandonment of a vessel under the code of commerce . and MADE WITH THE INTENT TO EXTINGUISH THE OBLIGATION Requisites of a Valid Payment 1. Identity what is to be paid. a fulfillment that extinguishes the obligation by the realization of the purposes for which it was constituted. Person to whom payment is made 3.Y. Compensation F. either to comply with the prestation or pay indemnity Why do you pay? Bigger consequences if you don t pay.Proscription H.Arrival of resolutory period . Person who pays 2. Novation G. Juridical act which is VOLUNTARY. Loss of the thing due or Impossibility of performance C. the creditor will file action for collection then the sheriff will levy upon your other properties What are the elements/characteristics of a valid payment? 1. morals.Compromise . Payment or performance most natural way of extinguishing obligation B.g.Insolvency does not extinguish obligation unless judicially declared and a discharge was given him. public order or public policy Rationale: Penalty is merely an accessory to the principal obligation Chapter IV. vendor becomes liable for the damages although contract itself is void 2.Abandonment e. II. Abnormal when debtor is forced by means of judicial proceeding. 2008-2009] OBLIGATIONS & CONTRACTS | Prof.Renunciation by the creditor .Death extinguishes obligations which are of a purely personal character. good customs.Fulfillment of resolutory condition . Other causes of extinguishment of obligations . Additional miscellaneous causes from Sir Labitag and Tolentino . Labitag [2 Page 49 of 110 y Nullity of principal obligation itself gives rise to liability of debtor for damages e. Extinguishment of Obligations I. pays with the express or tacit approval of the creditor. Anyone acting on his behalf a. if alive. without prejudice to the effects of confusion as to the latter s share. he can recover only insofar as the payment has been beneficial to the debtor . Art 1236 Par 2 Whoever pays for another may demand from the debtor what he has paid. not interested in the obligations. Duly authorized agent or representatives b. Legal subrogation (novation) 3 r d person is subrogated/steps into the shoes of creditor _ Payor can exercise all the rights of the creditor arising from the very obligation itself. obligation extinguished 2. Third person who is NOT AN INTERESTED PARTY and WITHOUT THE KNOWLEDGE OR AGAINST THE WILL OF THE DEBTOR Art 1236 Par 1 The creditor is not bound to accept payment or performance by a third person who has no interest in the fulfillment of the obligation. Creditor may refuse to accept payment d. Heirs (means that debtor is dead. Santos | UP Law B2012 . Debtor 2. Effects of Payment by 3 r d Person Interested 1. unless there is a stipulation to the contrary. 3 rd person can only be reimbursed insofar as payment has been beneficial to debtor y Burden of proof of payment on the 3 r d person y Benefit to the creditor need not be proved in the following cases: Karichi E. Successors in interest and assignees Third person who is an INTERESTED PARTY (creditor cannot refuse valid tender of payment) Meaning of INTERESTED PARTY interested in the extinguishment of the obligations such as y Co-debtors y Guarantors y Sureties y Owners of mortgaged property or pledge of the b. unless there is a stipulation to the contrary. Art 1236 Par 1 The creditor is not bound to accept payment or performance by a third person who has no interest in the fulfillment of the obligation. Effects of Payment by 3 r d Person Not Interested With Debtor s Consent 1. a person interested in the fulfillment obligation pays. cannot compel the creditor to subrogate him in his rights . 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Valid payment. Effects of Payment by 3 r d Person Not Interested Without Knowledge or Against the Will 1.ndSemester. Who can pay a. A.Y. except that if he paid without the knowledge or against the will of the debtor. whether against the debtor or third person 3. 1. 3 rd person subrogated to the rights of the creditor c. 3 rd person is entitled to full reimbursement _ Demand from the debtor what he has paid 2. Art 1302 (3) When even without the knowledge of the debtor. such as those arising from a mortgage. it should be complete (not only specific thing but all of its accessions and accessories) Can anybody pay? YES. Labitag [2 Page 50 of 110 Integrity how payment should be made. as long as his payment has integrity and identity and the creditor accepts it as a valid tender of payment 2. In general (creditor cannot refuse valid tender of payment) 1. guaranty or penalty. Third person who is NOT AN INTERESTED PARTY but WITH CONSENT of debtor Art 1302 (2) When a third person. Art 1237 Whoever pays on behalf of the debtor without the knowledge or against the will of the latter. they would be third persons interested in obligation) c. Debtor to reimburse fully 3 rd person interested 3. there shall be no right to recover the same from the oblige who has spent or consumed it in good faith. the third person acquires the creditor s right b.When payment to an incapacitated person is valid : a) If creditor has kept the thing delivered b) Insofar as payment benefited creditor Benefit to the creditor need not be proved in the following cases: Karichi E. Assignment of credit without notice to debtor (Art 1626) 2. 2. Extinguished if the mistake is imputable to the fault or negligence of the creditor (PAL v CA) 2. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Effects of Payment by 3 r d person Interested or not Does not intend to be reimbursed 1. In general Art 1240 Payment shall be made to the person in whose favor the obligation has been constituted. If after the payment. 3 rd person cannot compel creditor to subrogate him in the latter s rights e. obligation is not extinguished. Payment is deemed as a donation/offer of donation 2. Santos | UP Law B2012 . His successor in interest 3. Minor who entered contract without consent of parent/guardian No right to recover fungible thing delivered to the creditor who spent or consumed it in good faith In case of active solidarity Art 1214 The debtor may pay any one of the solidary creditors. In obligation to give Art 1239 In obligation to give. If by the creditor s conduct . or any person authorized to receive it. But the payment is in any case valid as to the creditor who has accepted it. Art 1427 When a minor 18-21 entered into a contract without the consent of the parent or guardian.n dSemester. g. To whom payment can be made a. without prejudice to the provisions of Art 1427 under Title on Natural Obligations. but if any demand. voluntarily pays a sum of money or delivers a fungible thing in fulfillment of an obligation. or his successor in interest . even if in good faith of the debtor EXCEPTION: 1. which requires the debtor s consent. payment made by one who does not have free disposal of the thing due and capacity to alienate it shall not be valid . Payment in good faith to person in possession of credit (Art 1242) Incapacitated person Art 1241 Par 1 Payment to a third person incapacitated to administer his property shall be valid if he has kept the thing delivered or insofar as the payment has been beneficial to him. GENERAL RULE: Payment not valid EXCEPTION . payment should be made to him. but without prejudice to natural obligations 2. Labitag [2 Page 51 of 110 a. 1. A.e. No free disposal and no capacity to alienate Payment is invalid. Any person authorized to receive it Payment to a wrong third party GENERAL RULE: Not valid. Third person who does NOT INTEND TO BE REIMBURSED DEBTOR MUST GIVE CONSENT Art 1238 Payment by third person who does not intend to be reimbursed by the debtor is deemed to be a donation . Donation must be in proper form (i.Y. Effect of Incapacity of the payor 1. judicial or extrajudicial has been made by one of them. If the creditor ratifies the payment to the third person c. Creditor/person in whose favor obligation was constituted 2. the debtor has been led to believe that the third person had authority to receive the payment d. if above P5K it must be in writing) f. whose quality and circumstances have not been stated. Third person Art 1241 Par 2 Payment to a third person shall also be valid insofar as it has redounded to the benefit of the creditor. the third person acquires the creditor s right 2. debtor may pay to any of the solidary creditors y If any judicial/extrajudicial demand is made by any of the creditors who made the demand 3. The delivery of promissory notes payable to order. or bills of exchange or other mercantile documents shall produce effect of payment only when they have been cashed . What is to be paid ( identity ) a. 1. Give specific things itself 2. Karichi E. Debtor cannot deliver a thing of inferior quality EXCEPTION: Unless quality and circumstances have been stated. If the creditor ratifies the payment to the third person g. the debtor has been led to believe that the third person had authority to receive the payment h. GENERAL RULE: VALID if third person proves that it redounded to creditor s benefit. otherwise VOID EXCEPTION. the action derived from the original obligation shall be held in abeyance. or more valuable than which is due. Neither can the debtor deliver a thing of inferior quality. but if any demand. In general y The very prestation (thing or service) due In obligations to b.Pay money Art 1249 The payment of debts in money shall be made in the currency stipulated.n dSemester. payment should be made to him. If after the payment. The purpose of obligation and other circumstances shall be taken into consideration. judicial or extrajudicial has been made by one of them. and if it is not possible to deliver such currency. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Assignment of credit without notice to debtor (Art 1626) b. If by the creditor s conduct .GIVE a specific thing Art 1244 Par 1 The debtor of a thing cannot compel the creditor to receive a different one. Payment in good faith to any person in possession of the credit shall release the debtor (Art 1242) EFFECT: Debtor is released Art 1243 Debtor pays creditor after being judicially ordered to retain debt EFFECT: Payment not valid if the property is attached or garnished c. If with loss. A. the debtor has been led to believe that the third person had authority to receive the payment 4. If by the creditor s conduct . Labitag [2 Page 52 of 110 e.GIVE a generic thing Art 1246 When the obligation consists in the delivery of an indeterminate or generic thing.Y. In the meantime. purpose and other circumstances of obligation considered. Accessions and accessories 3. the creditor cannot demand a thing of superior quality. deterioration Apply Art 1189 . Assignment of credit without notice to debtor (Art 1626) 5. In case of active solidarity Art 1214 The debtor may pay any one of the solidary creditors. When proof of benefit not required also applicable to INCAPACITATED PERSONS Art 1241 Par 3 Such benefit to the creditor need not be proved in the following cases: 1. the third person acquires the creditor s right f. then in the currency which is the legal tender in the Philippines. improvements. If the creditor ratifies the payment to the third person 3. GENERAL RULE: Creditor cannot demand a superior quality. . although the latter may be of the same value as. If after the payment. or when through the fault of the creditor they have been impaired . Santos | UP Law B2012 . y If no demand is made. . when the debt is in part liquidated and in part unliquidated . Attempt in good faith to perform. Contrary stipulation o Art 1248 Par 1 Unless there is an express stipulation to that effect . In general Art 1233 A debt shall not be understood to have been paid unless the thing or service in which the obligation consists has been completely delivered or rendered as the case may be. less damages suffered by the oblige. Payment of interest Art 1956 No interest shall be due unless it has been expressly stipulated in writing. unless there is an agreement to the contrary. GENERAL RULE: Partial payment is not allowed Creditor cannot be compelled to receive partial prestations. . Neither may the debtor be required to make partial payments. Debtor cannot be compelled to give partial payments EXCEPTIONS: 1. Omission or defect is unimportant and technical 4. Paul Fire and Marine Insurance v Macondray y Papa v AV Valencia et al y PAL v CA c. Labitag [2 Page 53 of 110 EXCEPTION. the obligation is deemed fully complied with .DO or NOT TO DO Art 1244 Par 2 In obligations to do or not to do. Deviation from the obligation must be slight 3. 2008-2009] OBLIGATIONS & CONTRACTS | Prof.Y. Must not be so material that intention of the parties is not attained Estoppel Art 1235 When oblige accepts the performance. and without expressing any protest or objection. RA 4100. How is payment to b e made ( integrity ) a. the obligor may recover as though there had been a strict and complete fulfillment . y Requisites of Substantial Performance 1. c. Debt is partly liquidated and partly unliquidated o Art 1248 Par 2 Howev er. the creditor may demand and the 3. Art 1253 Interest must be satisfied first before capital 4. RA 529 RA 4100 . y Substitution cannot be done against the will of creditor Cases: y Arrieta v NARIC supra y Kalalo v Luz y St. in which the obligation consists. 2. the value of the currency at the time of the establishment of the obligation shall be the basis of the payment.n dSemester.Constitutes a waiver of defect in performance there must however be an intentional relinquishment of a known right. an act or forbearance cannot be substituted by another act or forbearance against the obligee s will. the creditor cannot be compelled partially to receive the prestations. When there are several subjects/parties are bound under different terms and conditions 4. Waiver will not result from mere failure to assert a claim for defective performance when the thing or work is received Karichi E. Santos | UP Law B2012 debtor may effect the payment of the former without waiting for the liquidation of the latter. A. without any willful or intentional departure 2. Compensation b. Substantial performance in good faith Art 1234 If the obligation has been substantially performed in good faith. knowing its incompleteness or irregularity. RA 8183: Foreign currency if agreed to by parties Art 1250 In case of an extraordinary inflation or deflation of the currency stipulated should supervene. . may declare at the time of making the payment. or after he has incurred in delay. Santos | UP Law B2012 . the expenses shall be borne by him . y If principal amount is received without reservation as to interest interest is presumed to have been paid INSTALLMENTS Art 1176 Par 2 The receipt of a later installment of debt. Art 1253 If the debt produces interest. debtor may only prior to the due date if creditor consents thereto. In general Art 1169 Debtor incurs in delay from the time creditor obligation judicially or extrajudicially demands fulfillment of the b. to which of them the same must be applied. without reservation as to prior installments shall likewise raise the presumption that such installments have been paid. Expenses of making payment Art 1247 Unless it is otherwise stipulated. the Rules of Court shall govern. SPECIAL FORMS OF PAYMENT APPLICATION OF PAYMENTS Art 1252 He who has various debts of the same kind in favor of one and the same creditor . Where payment is to be made a. When is payment to be made When obligation is due and demandable but debtor may pay before due date if period is for the benefit of debtor. the place of payment shall be at the domicile of the debtor . y If a latter installment is received without reservation to prior installments prior installments are presumed to have been paid 5. If for the benefit of both the debtor and creditor. a. shall give rise to the presumption that said interest has been paid. the extra-judicial expenses required by the payment shall be for the account of the debtor with regard to the judicial costs.Y. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Art 1251 Par 4 If the debtor changes his domicile in bad faith. without reservation with respect to the interest. If no place is expressly designated Art 1251 Par 2 There being no express stipulation and if the undertaking is to deliver a determinate thing the payment shall be made wherever the thing might be at the moment the obligation was constituted Art 1251 Par 3 In any other case (not to deliver a determinate thing). See Chapter 2: Delay 6. or when the Karichi E. Presumptions in payment of interests and installments INTEREST Art 1176 The receipt of the principal by the creditor. Labitag [2 Page 54 of 110 . it will be borne by the creditor) additional .Applies only when he knows the incompleteness or irregularity of the payment. UNLESS the parties so stipulate. Estopped from complaining d. obligation is deemed extinguished. A. In the designated place in the obligation (Art 1251 Par 1) b. (Absent such circumstances.n dSemester. 7. payment of the principal shall not be deemed to have been made until the interests have been covered . Right to apply must be exercised at the time of the payment (Art 1252) 2. This cession. or if application can not be inferred from other circumstances. Labitag [2 Page 55 of 110 application of payment is made by the party for whose benefit the term has been constituted. the debt which is MOST ONEROUS TO THE DEBTOR among those due. which courts must determine on the basis of circumstances of each case eg. Same creditor 3. unsecured PAYMENT BY CESSION Art 1255 The debtor may cede or assign his property to his creditors in payment of his debts. (Art 1252) 3. Santos | UP Law B2012 . If the debts are of the same nature and burden. Creditor may undertake application. A.Y. subject to the debtor s approval.n dSemester. The agreements which on the effect of the cession. application shall made as to debts that are not yet due . shall only release the debtor from responsibility for the net proceeds of the thing assigned. younger vs. Various debts are of same kind. Debtor has preferential right to choose the debt which his payment is to be applied o Not absolute. If the debtor accepts from the creditor a receipt in which an application of the payment is made complain of the same . he cannot complain UNLESS there is a cause for invalidating the contract. the former cannot Concept Designation of the debt which is being paid by a debtor who has SEVERAL OBLIGATIONS OF THE SAME KIND. sole debtor o Same amount. If rules are inapplicable and application cannot be inferred Art 1254 When payment cannot be applied in accordance with preceding rules. older o Secured vs. o Co-debtor (especially if solidary) vs. All obligations must be due o EXCEPTIONS: _ Mutual agreement of parties _ upon consent of the party in whose favor the term was established 5. Apply to interest first. the payment shall be applied to all of them proportionately . and period has not yet arrived _ Right to apply debts must be exercised at the time when debt is paid Rules in Application of Payment 1. UNLESS there is stipulation to the contrary. BOTH (1) interest stipulated and (2) interest due because of debtor s delay Art 1253 If debt produces interest. payment of the principal shall not be deemed to have been made until the interest are covered. Karichi E. LIMITATIONS: _ Cannot make partial payments _ Cannot apply to unliquidated debts _ Cannot choose a debt whose period is for the benefit of the creditor. Once the latter accepts receipt of application. Meaning of MOST ONEROUS TO DEBTOR Fundamentally a question of act. generally monetary character o Cannot apply to prestation to give specific thing o Can apply to prestation to give generic thing 4. not be . are made between the debtor and his creditors shall be governed by law. Same debtor 2. UNLESS there is a cause for invalidating the consent. in favor of one creditor to whom payment is being made Cases: y Reparations Commissions v Universal Deep Sea Fishing y Paculdo v Regalado Requisites for Application of Payment 1. Payment is not enough to extinguish all debts 6. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. shall be deemed to have been satisfied. Karichi E. Acceptance or consent on the part of the creditors Effects of Payment by Cession 1. whereby property is alienated to the creditor in satisfaction of a debt in money. unless there is a stipulation to the contrary not total extinguishment 3. Not a pactum commissorium (a stipulation entitling the creditor to appropriate automatically the thing given as security in case debtor fails to pay) Effects of Dation in Payment 1. either as agreed upon by the parties. consider the thing as equivalent to the obligation in which case the obligation is totally extinguished. Abandonment of all debtor s property not subject to execution 5. An onerous contract of alienation because object is given in exchange of credit Special form of payment because one element of payment is missing: identity Case: y DBP v CA Distinguished from payment by cession DATION IN PAYMENT PAYMENT BY CESSION Transfers the ownership over the thing alienated to the Only the possession and administration (not the creditor ownership) are transferred to the creditors. or as may be proved. Debtor is not declared judicially insolvent 4. Labitag [2 Page 56 of 110 Concept Abandonment of the universality of the property of the debtor for the benefit of his creditors. in order ordinarily established by law. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. A. Plurality of debts 2. plurality of creditors Both are substituted performances o f obligations accepted Requisites for Dation in Payment 1. Concept Delivery and transmission of ownership of a thing by the debtor and to the creditor as an equivalent of the performance of the obligation .Y. Dacion will not prejudice of other creditors 3. DATION IN PAYMENT (Dacion en Pago) Art 1245 Dation in payment. Plurality of creditors 3. Creditor will collect credits in the order of preference agreed upon. Santos | UP Law B2012 . Consent of creditor sale presupposes the consent of both parties 2. Creditors do not become the owner. Extinguishes payment to the extent of the value at the thing to be delivered. Complete or partial insolvency of the debtor 4.n dSemester. unless the parties by agreement expressly or impliedly or by their silence. shall be governed by law of sales. Debtor is released up to the amount of the net proceeds of the sale. unless otherwise agreed upon Cession of only some specific thing Involves ALL the property of the debtor Transfer is only in favor of one creditor to satisfy a debt There are various. in order that such property may be applied to the payment of his credits. with an authorization to convert the property into cash with which the debts shall be paid May totally extinguish the obligation and release the Only extinguishes the credits to the extent of the amount debtor realized from the properties assigned. they are merely assignees with authority to sell 2. Debtor transfers all the properties not subject to execution in favor of creditors that the latter may sell them and thus apply the proceeds to their credits Initiative comes from the debtor but must be accepted by the creditors in order to become effective Usually done by debtors in state of insolvency Requisites for Payment by Cession 1. or in default of agreement. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. without which the consignation is ineffective 2. Unaccepted offer in writing to pay is equivalent to actual production and tender of money or property 2. A. Should include interest due 3.n dSemester. Generally requires prior tender of payment Made by depositing the things due at the disposal of judicial authority (includes sheriff) Purpose Avoid performance of an obligation becoming more onerous to the debtor by reasons not imputable to him Duty of attending indefinitely to its preservation. There is a debt due 2. or in case of money obligations. There was a previous tender of payment. Santos | UP Law B2012 . tender presupposes capacity of the payor 3. as it involves less transmission of rights unless it is clearly the intention of parties Case: y Filinvest Credit Corporation v Philippine Acetylene TENDER OF PAYMENT AND CONSIGNATION 1. does not cause extinguishment of obligation unless completed by consignation Required ONLY when the creditor refuses without just cause to accept payment What are the examples of unjust cause for refusal 1. Tender of payment was of the very thing due. CONSIGNATION Concept The act of depositing the thing due with the court or judicial authorities whenever the creditor cannot accept or refuses to accept payment. without remedy to be relieved from the debt Requisites of Consignation 1. he is in mora accipiendi and debtor is released from responsibility if he consigns the thing due Manifestation made by debtor to creditor of desire to comply with obligation Preparatory act to consignation. Payment by third persons not interested in the fulfillment of the obligation because to begin with. When tender and refusal not required Karichi E. Must be unconditional.Y. The consignation of the obligation was made because of some legal cause o Previous valid tender was unjustly refused o Other circumstances making previous tender exempt s t notice) 3. Tender of payment was unconditional 4. Accrual of interest will be suspended from the date of such tender if immediately deposited with the court Requisites of a Valid Tender of Payment 1. sureties) or active (solidary co-creditors. Debt is not yet due and the period is for the benefit of the creditor 2. Prior notice of consignation had been given to the person interested in the obligation (1 4. If property delivered to the creditor assumption that it is a PLEDGE. Made in lawful currency 2. Labitag [2 Page 57 of 110 2. Creditor refused to accept payment without just cause What are the examples of just cause for refusal 1. that the legal tender currency was offered 3. Actual deposit /consignation with proper judicial authority 5. but the creditor cannot vary the terms of a tender accepted by him 4. possible litigants) a. Subsequent notice of consignation (2 n d notice) o May be complied with by the service of summons upon the defendant creditor together with a copy of the complaint o Given to all interested in the performance of obligations: passive (co-debtors. guarantors. TENDER OF PAYMENT Concept The act of offering the creditor what is due him together with a demand that the creditor accept the same When creditor refuses without just cause to accept payment. it must FIRST be announced to the persons interested in the fulfillment of the obligation. The accrual of interest on the obligation is suspended from the moment of the consignation. Creditor is absent or unknown or does not appear at place of payment 2. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Any increment or increase in value of the thing after the consignation inures to the benefit of the creditor. The debtor is released in the same manner as if he had performed the obligation at the time of consignation. Title of the obligation has been lost b. Two notice requirement FIRST NOTICE: Art 1257 Par 1 In order that the consignation of the thing due may release the obligor. because this produces the effect of a valid payment. A. 4. he shall lose every preference which he may have over the thing . Incapacitated to receive payment at the time it is due need not be legally declared 3. or before a judicial declaration that the consignation has been properly made. (TLG v Flores) Art 1260 Par 2 Before the creditor has accepted the consignation. the debtor may withdraw the thing or sum deposited allowing the obligation to remain in force . he refuses to give a receipt 4. charge against the creditor with the Art 1260 Par 1 Once the consignation has been duly made.Before the consignation is effected.n dSemester. Labitag [2 Page 58 of 110 Art 1256 Par 2 Consignation alone shall produce the same effect in the following cases: 1. Expenses of consignation Karichi E. 3. Santos | UP Law B2012 . The co-debtors. because the risks of the thing are transferred to the creditor from the moment of deposit. Effects of withdrawal before consignation is final 1. guarantors.Y. Without just case. the debtor may ask the judge to order the cancellation of the obligation. the debtor is still the owner and he may withdraw it. y Why? . The deteriorations or loss of a thing or amount consigned occurring without fault of the debtor must be borne by the creditor. 2. Withdrawal by debtor AFTER proper consignation Art 1261 If the consignation having been made . Debtor bears all the expenses incurred because of the consignation e. and sureties shall be released. y Why? SECOND NOTICE: Art 1258 Par 2 The consignation having been made notified thereof. the creditor should authorize the debtor to withdraw the same. d. Obligation remains in force 2. 1. Effects of Consignation when properly made. the interested parties shall also be Effects of non-compliance Art 1257 Par 2 The consignation shall be ineffectual if it is not made strictly in consonance provisions which regulate payment. Two or more persons claim the same right to collect 5. (Soco v Militante) c. Withdrawal by debtor BEFORE acceptance by creditor OR approval by the Court . With creditor s approval EFFECTS:revival of the obligation and relationship between creditor and debtor is restored to the condition in which it was before the consignation Without creditor s approval EFFECTS: - f. Before the debtor incurs in delay 3. Generally applies to determinate things Must be subsequent to the ex ecution of the contract in order to extinguish the obligation If impossibility already existed when the contract was made. he shall be obliged to pay damages. it shall be presumed that the loss was DUE TO HIS FAULT . Art 1165 Action for specific performance or substituted performance When not applicable In case of earthquake. Labitag [2 Page 59 of 110 Art 1259 The expenses of consignation. Burden of explaining the loss of the thing in the possession of the debtor. shall be charged against the creditor . after hearing declares that the consignation has been validly made.Y. it is understood that the thing is loss when it: a. Disappears in such a way that its existence is unknown or it cannot be recovered Kinds of Loss a. Santos | UP Law B2012 . flood. Loss or Impossibility LOSS OF THE THING DUE Concept Not limited to obligations to give but extends to those which are personal. Effects of Loss of the Thing Due a. Loss or destroyed without the fault of the debtor 2.n dSemester. contract without any effect). Goes out of the commerce of man c. the result is not extinguishment but inefficacy of the obligation under Art 1348 (impossible things or services cannot be object of contracts) and Art 1493 (Sales. In obligation to give a specific thing Karichi E. o Consignation is properly made when: _ After the thing has been deposited in the court. As to extent TOTAL PARTIAL Requisites of Loss of the Thing Due Art 1262 In order to extinguish obligation: 1. loss object of contract. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. After the obligation is constituted Presumption in Loss of the Thing Due Art 1265 Whenever the thing is lost in the possession of the debtor . Perishes b. embracing therefore all causes which may render impossible performance of the prestation. storm or other natural calamity. Art 1189 (2) If the thing is lost through the fault of the debtor. Cases: y De Guzman v CA y TLG International Continental Enterprising v Flores y McLaughlin v CA y Soco v Militante y Sotto v Mijares y Meat Packing Corp v Sandiganbayan y Pabugais v Sahijwani III. UNLESS there is proof to the contrary. and without prejudice to the provisions of Art 1165. when properly made. the creditor accepts the consignation without objection and without reservation of his right to contest it because of failure to comply with any of the requisites for consignation _ When the creditor objects to the consignation but the court. A. rest upon him. Monetary obligation c. delay 2. under the circumstances. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. y Provided that partial loss is not imputable to the fault or negligence of the debtor but to fortuitous events or circumstances y Intention of the parties is the controlling factor in the solution of each case of partial loss y E. the contract also ceases to exist. insurance received by owner of company with respect to victims of sunk vessel IMPOSSIBILITY OF PERFORMANCE Concept Art 1266 The debtor in obligations to do shall also be released when the prestation becomes legally or physically impossible without the fault of the obligor. y E. in bad faith. contractual stipulation or nature of obligation requires assumption of risk on part of debtor b.Y. the latter refused without justification to accept it. UNLESS the thing having been offered by him to the person who should receive it. Debtor is made liable for fortuitous event by law. In case of partial loss Art 1264 The courts shall determine whether.e. Doctrine of unforeseen events. A.n dSemester. become determinate objects whose loss extinguishes the obligation 2. the obligation constituted is under VOID contracts Art 1267 When the service has become so difficult as to be manifestly beyond the contemplation of the parties. the debtor shall NOT BE EXEMPTED from the payment of its price. negligence. the partial loss of the object of the obligation is so important as to extinguish the obligation . If existing BEFORE.g.g. y Genus nunquam perit or The genus never perishes y Sir Labitag: Fallacy! The genus may be legally loss! EXCEPTIONS: 1. EXCEPTIONS: 1. the obligor may also be released therefrom. Event or change in circumstances could not have been fo reseen at the time of the execution of the contract Karichi E. In obligation to give a generic thing not extinguished does Art 1263 In an obligation to deliver a generic thing. Santos | UP Law B2012 . the loss or destruction of anything of the same kind not extinguish the obligation. and once these conditions cease to exist. money paid to the debtor upon expropriation of the property which is the object of obligation. the creditor shall have all rights of action which the debtor may have against third person by reason of the loss . by Sir: When Tyson bit off Holyfield s ear which did not undermine the latter s boxing prowess hehe d. Refers to SUBSEQUENT IMPOSSIBILITY arises AFTER the obligation has been constituted. Debtor is at fault i. Labitag [2 Page 60 of 110 Art 1262 Loss or destruction of determinate thing without fault of debtor AND before he incurs in delay EXTINGUISHES OBLIGATION Art 1268 When the debt of a thing certain and determinate proceeds from a criminal offense . Delimited generic things: limitation of the generic object to a particular existing mass or a particular group of things. Requisites for application of Art 1267 1. y Refers not only to the rights and actions which the debtor may have against third persons but also to any indemnity which the debtor may have already received. Generic thing has been segregated 3. whatever may be the cause for the loss . Action against third persons Art 1269 The obligation having been extinguished by the loss of the thing . rebus sic stantibus : the parties stipulate in the light of certain prevailing conditions. in whole or in part. As to source LEGAL a. Makes the performance of the co ntract extremely difficult but not impossible 3. Condonation or Remission Concept An act of liberality by virtue of which. the creditor renounces the enforcement of obligation . As to extent TOTAL PARTIAL significant in Art 1264 (extinguishment due to partial loss subject to the court s determination) 2. A. Karichi E. Cases: y Occena v CA y Naga Telephone Co v CA y PNCC v CA b. such that one party would be placed at a disadvantage by the unforeseen event. In obligations to do Art 1266 releases debtor from obligation if prestations has become legally or physically impossible Art 1267 releases debtor if performance has become so difficult to be so manifestly beyond the contemplation of the parties Art 1262 Par 2 (by analogy) Impossibility due to fortuitous events does not extinguish obligation if: o By law o By stipulation o Nature of the obligation requires assumption of risk In case of partial performance by the debtor : creditor must pay the part done so long as he benefits from such partial compliance. Difficulty Manifest disequilibrium in the prestations. under the circumstances. partial loss of the object of the IV. cannot be accomplished Requisites of Impossibility Art 1266 1.n dSemester. Direct prohibited by law b. Event must not be due to the act of any of the parties 4. Subsequent impossibility 3. If debtor received anything from creditor prior to loss or impossibility: return anything in excess of what corresponds to the part already performed when the impossibility supervened. the obligation is so important as to extinguish the obligation . Without the fault of the debtor Effects of Impossibility a.Y. Obligation used to be possible at the constitution of obligation 2. In case of partial impossibility Art 1264 The courts shall determine whether. Impossibility vs. Labitag [2 Page 61 of 110 2. without receiving any equivalent. which is extinguished in its entirety or in that part or aspect of the same to which the remission refers. Santos | UP Law B2012 . 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Indirect prevented by supervening legal duty such as military service PHYSICAL By reason of its nature. Contract is for a future prestation Kinds of Impossibility 1. It may be expressly or impliedly . Art 1272 Whenever the private document in which the debt appears is found in the POSSESSION of the debtor . IMPLIES the renunciation of the action which the former had against the latter. and requires the acceptance by the obligor. 3. ingratitude and condition not followed Presumptions in Condonation 1. As to form Art 1270 Par 1 Condonation or remission is essentially gratuitous. Art 1274 It is presumed that the accessory obligations of pledge has been after its delivery to the creditor.Y. shall furthermore. made voluntarily by a creditor to the debtor. Only prima facie and may be overcome by contrary evidence to show that notwithstanding the possession by the debtor of the private document of credit. Labitag [2 Page 62 of 110 It is an essential characteristic of remission that it be gratuitous . Bilateral acts which requires acceptance by the debtor Subject to the rules on donations with respect to acceptance. As to extent TOTAL PARTIAL refer to the amount of indebtedness. Surrender of weapon of enforcement of his rights 2. unless the contrary is proved. EXPRESS condonation. accordance with the forms of ordinary donations IMPLIED inferred from the acts of parties Requisites of Condonation 1. once such equivalent exists. amount and revocation Formalities of a donation are required in the case of an express remission Revocable subject to the rule on inofficious donation (excessive. implied in mortis causa (effective upon the death of the creditor) and express inter vivos (effective during the lifetime of the creditor) Case: y Yam v CA When formalities required Art 1270 Par 2 One and other kind shall be subject to the rules which govern inofficious donation . Debts must be existing and demandable at the time remission is made 2. that there is no equivalent received for the benefit given. A. or to an accessory obligation (such as pledge or interest) or to some other aspect of the obligation (such as solidarity) 2. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. requires acceptance by the obligor. The renunciation of the debt must be gratuitous or without any equivalent or consideration 3. is found in the possession of the debtor thing . comply with the forms of donation . it has not been paid. . Art 1271 The DELIVERY of a private document evidencing a credit . REMITTED when the thing pledged.n dSemester. Santos | UP Law B2012 . Debtor must accept the remission y Unilateral renunciation is possible under Art 6 and nothing prevents him from abandoning his rights y Parties must be capacitated and must consent. legitime is impaired). the nature of the act changes y Dation in payment receive a thing different from that stipulated y Novation object or principal conditions of the obligation should be changed y Compromise when the matter renounced is in litigation or dispute and in exchange of some concession which the creditor receives Kinds of Condonation 1. Not applicable to public documents because there is always a copy in the archives which can be used to prove the credit. or a third person who owns the Karichi E. it shall be presumed that the creditor delivered it voluntarily . EXPRESS when made formally. Very same obligation must be involved. In case of joint or solidary obligations affects the share corresponding to the debtor in whose benefit the remission was given Governing Rules in Condonation Art 1270 Rules in inofficious donations Effects of Renunciation of Principal or Accessory Obligation Art 1273 The renunciation of the principal debt shall extinguish the accessory obligations latter shall leave the former in force. for if the debtor acquires rights from the creditor. debtor inherits credit from the creditor. However. Must take place between the creditor and the principal debtor (Art 1276) 2. Abbreviated payment Karichi E. A. When mortgaged property belongs to a third person. mortgagee acquires a part of the property. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. the same is released from the encumbrance. VI.g. Why? Accessory merely follows principal . y Solidary obligations Art 1215 confusion made by any of the solidary creditors or with any of the solidary debtors shall extinguish the obligation . Labitag [2 Page 63 of 110 Effects of Condonation 1. (Solidary co-debtor who has been remitted is still liable to co-debtors if one of the had paid the obligation in full prior the remission) Confusion in Principal or Accessory Obligation Art 1276 Merger which takes place in the person of the principal debtor or creditor benefits the guarantors . Confusion or Merger of Rights Concept Merger or confusion is the meeting in one person of the qualities of the creditor and the debtor with respect to the same obligation. the obligations of those persons who in their own right are reciprocally debtors and creditors of each other. his obligation as guarantor is extinguished. Confusion must be total or as regards the entire obligation Effects of Confusion 1.n dSemester. In general extinguishes either totally or partially 2. Merger releases the guarantor because they are merely accessory obligations Guarantor acquires the credit. The obligation merely becomes a partly (if the acquisition is not total) unsecured obligation. cannot be the other way around because under the present law. without prejudice to the provisions of Art 1219. Santos | UP Law B2012 . as a result of which the obligation is recreated in the same condition that it had when merger took place CAUSE OF MERGER: Anything that brings about succession to the credit e. Erases the plurality of subjects of the obligation and extinguishes the obligation because it is absurd that a person should enforce an obligation against himself. In general extinguish the obligation 2. Confusion which takes place in the person of any of the latter does not extinguish the obligation . there will be no merger 3. Requisites for Confusion 1. Compensation Concept It is a mode of extinguishing the obligation to the concurrent amount. but not particular obligation in question. In case of y Joint obligations . heirs do not inherit the debts of their predecessors.Art 1277 Confusion does not extinguish a joint obligation EXCEPT as regards the share corresponding to the creditor or debtor in whom the two characters concur .Y. but the principal obligation subsists which he can enforce against the debtor and other co-guarantors. but the waiver of the V. May be revoked. Karichi E. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. As to extent TOTAL when two obligations are of the same amount PARTIAL when the amounts are not equal 2. in their own right are creditors and debtors of each other.n dSemester. Distinguished from Confusion CONFUSION COMPENSATION Involves only one obligation There must always be two obligations There is o nly one person in whom the characters of Two persons who are mutually debtors and creditors of creditor and debtor meet each other in two separate obligations. such as that provided in Art 1282 Art 1279 Requisites of legal compensation is inapplicable Art 1282 The parties may agree upon the compensation of debts which are not yet due. FACULTATIVE when it can be claimed by one of the parties who. defendant is the creditor of the plaintiff for an unliquidated amount. because there is less risk of loss by the creditor due to insolvency or fraud of the creditor Art 1278 Compensation shall take place when two persons. the former may set it off by proving his right to said damages and the amount thereof. because it takes place receive are required for debtor and creditor by operation of law and not by the acts of parties Performance must be complete There may be partial extinguishment of an obligation Advantage of Compensation over Payment 1.Y. it must be alleged and proved by the debtor who claims its benefits.g. each arising from a different cause Kinds of Compensation 1. its effect retroacts to the moment when the requisites provided by law concur. Although it takes place by operation of law. More guaranty in making the credit effective. Payment is simplified and assured between persons who are indebted to each other. Labitag [2 Page 64 of 110 Offsetting of two obligations which are reciprocally extinguished if they are of equal value or extinguished to the concurrent amount if of different values. y Requisites of Voluntary Compensation 1. sets up his credit as a counterclaim against the plaintiff and his credit is liquidated by judgment. Balancing between two obligations. however. A. Legal compensation is not possible because the claim is unliquidated Art 1283 If one of the parties to a suit over an obligation has a claim for damages against the other. taking effect without action by either party to extinguish their respective obligations 2. Distinguished from payments PAYMENT COMPENSATION Capacity to dispose of the thing paid and capacity to Such capacity is not necessary. has the right to object to it such as when one of the obligations has a period for the benefit of one party alone and who renounces that period so as to make the obligation due y When legal compensation cannot take place for want of some legal requisites . Each of the parties can dispose of the credit he seeks to compensate 2. Once proved. As to origin LEGALtakes place by operation of law because all the requisites are present VOLUNTARY/CONVENTIONAL when the parties agree to compensate their mutual obligations even if some requisite is lacking. They agree to the mutual extinguishment of their credits JUDICIAL when decreed by the court in a case where there is a counterclaim e. involves a figurative operation of weighing two obligations simultaneously in order to extinguish them to the extent in which the amount of one is covered by the other. Santos | UP Law B2012 . thereby compensating it with the credit of the plaintiff. Simple. Each one of the obligors be bound principally and that at the same time a principal creditor of the other y Principals not applicable if only a guarantor y Solidary debtor cannot set up the obligation of the creditor in favor of a co-debtor. Support due gratuitous title (Art 1287) 4. but applicable to those with penal clause Art 1280 Notwithstanding the provisions of the preceding article. Santos | UP Law B2012 rules on . except as regards 2. Karichi E. 2008-2009] OBLIGATIONS & CONTRACTS | Prof.g. without prejudice to the provisions of Art 301 (support in arrears can be compensated). or if the things due are consumable. they be of the the share of the latter same kind and also of the same quality if the latter has been stated 3. Civil liability arising from a penal offense (Art 1288) Art 1287 Compensation shall not be proper when one of the debts arises from a depositum or from the obligations of a depositary or of a bailee in a commodatum .enforceable in court y What are not subject to compensation o Period which has not yet arrived o Suspensive condition has not yet happened o Obligation cannot be sued upon e.n dSemester. commenced by third persons and communicated in due time to the debtor y Not applicable to facultative obligations. A. natural obligation 5. the guarantor may set up compensation as regards what the creditor may owe the principal debtor. Interests stop accruing on the extinguished obligations or the part ex tinguished 3. Period of prescription stops with respect to the obligation or part extinguished 4. That both debts consists in a sum of money . That over neither of them there be any retention or controversy . If a person should have against him several debts which are susceptible of compensation. That they be liquidated and demandable y Liquidated debts when its existence and amount are determined y Demandable . the application of payments shall apply to the order of the compensation. Depositum (Art 1287) 2. Both debts are extinguished to the concurrent amount (Art 1290) 2. it would mean the extinguishment of the guaranteed debt and benefits the guarantor Cases: y Gan Tion v CA y Silahis Marketing Corp v IAC y BPI v Reyes y PNB v Sapphire Shipping y BPI v CA y Mirasol v CA Effects of Legal Compensation 1. That the two debts are due 4. (Art 1289) When compensation is not allowed 1. while conventional depends upon agreement of both parties LEGAL COMPENSATION Requisites for Legal Compensation Art 1279 In order that compensation may be proper it is necessary that: 1. Liability of the guarantor is only subsidiary. Labitag [2 Page 65 of 110 y As compared with conventional: facultative is unilateral. it is accessory to the principal obligation of the debtor If debtor s obligation is compensated. Commodatum (Art 1287) 3. Neither can compensation be set up against a creditor who has a claim for support due by gratuitous title . All accessory obligations of the principal which has been extinguished are also extinguished 5.Y. nothing to assign at all . even though the debts may be payable at different places but there shall be an indemnity for expenses of exchange or transportation to the place of payment. A. the assignment does not take effect except from the time he is notified thereof. Santos | UP Law B2012 .n dSemester. just that the depositary or borrower should in fact perform his obligation. Effects of Assignment of Credit A. compensated against each other BEFORE 2.Assignee is left with an action for eviction or for damages for fraud against assignor B. Made AFTER compensation took place: no effect. When there is renunciation of the effects of compensation by a party rests upon a potestative right and unilateral declaration of renunciation is sufficient 2. Art 1287 one of the debts arises from a depositum or from the obligations of a depositary or a bailee in commodatum Claim for support due by gratuitous title. No compensation may occur even when all the requisites concur : 1.Y. Without the knowledge of debtor all debts maturing prior to his knowledge Art 1285 Par 3 If the assignment is made without the knowledge of the debtor. . but not of subsequent ones. Subrogating a third person in the rights of the creditor Karichi E. Art 3012 b. 3. Substituting the person of the debtor 3. It is therefore. Made BEFORE compensation took place 1. With consent of debtor cannot set up against assignee UNLESS debtor reserved his right to compensation when he gave his consent Art 1285 Par 1 The debtor who has consented to the assignment of rights made by a creditor in favor of a third person. he may set up the compensation of all credits prior to the same and also later ones until he had knowledge of the assignment. the latter may set up the compensation of debts previous to the cession . Rationale : As far as the debtor is concerned. they may be they are judicially rescinded or avoided. Novation Concept The extinguishment of an obligation by the substitution or change of the obligation by a subsequent one which extinguishes or modifies the first either by: 1. without prejudice to the provisions of 2 Par. cannot set up against the assignee the compensation which would pertain to him against the assignor. Art 1288 civil liability arising from a penal offense nd Compensation of debts payable in different places Art 1286 Compensation takes place by operation of law . UNLESS the assignor was notified by the debtor at the time he gave his consent. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. VII. With knowledge but without consent of debtor only debts prior to assignment. not subsequent Art 1285 Par 2 If the creditor communicated the cession to him but the debtor did not consent thereto. Labitag [2 Page 66 of 110 y Why? A deposit is made or a commodatum is given on the basis of confidence of the owner. that he reserved his right to the compensation. Applies to legal compensation but not to voluntary compensation Effects of Nullity of debts to be compensated Art 1284 When one or both debts are rescissible or voidable. compensation already perfected. Art 1288 Neither shall there be compensation if one of the debts consists in civil liability arising from a y Why? Satisfaction of such obligation is imperative penal offense . When the law prohibits compensation a. Changing the object or principal conditions 2. otherwise the trust of the depositor or lender would be violated. Animus novandi or intent to novate (especially for implied novation and substitution of debtors) Cases: y Millar v CA y Dormitorio v Fernandez y Magdalena Estate v Rodriguez y Reyes v Secretary of Justice y Congchingyan v RB Surety and Insurance y Broadway Centrum Condominium Corp v Tropical Hut Karichi E.Y. Subrogating a third person in the rights of the creditor Kinds of Novation 1. Art 1291 Obligations may be modified by: 1. Labitag [2 Page 67 of 110 Unlike other acts of extinguishing obligation. As to effect PARTIAL only a modification or change in some principal conditions of the obligation TOTAL obligation is completely extinguished Art 1292 In order that obligation may be extinguished by another which substitutes the same. it creates a new one in lieu of the old. novation is a juridical act of dual function extinguishes an obligation. Accidental changes do not produce novation.n dSemester. A. As to origin CONVENTIONAL by express stipulation of the parties LEGALby operation of law 3. object or principal SUBJECTIVE/PERSONAL modification of obligation by the change of the subject o passive . It be so declared in unequivocal terms (express) 2. Changing the object or principal conditions 2. Requisites of Novation 1.substitution of debtor o active . Old and the new obligations be on every point incompatible with each other (implied) Novation is not presumed Express novation: expressly disclose that their object in making the new contract is to extinguish the old contract Implied novation: no specific form is required. Previous valid obligation 2. all that is needed is incompatibility between original and subsequent contracts Test of incompatibility: If the two contracts can stand together and each one having independent existence The change must refer to the object. Santos | UP Law B2012 . As to form in that at the time it EXPRESSparties declare that the old obligation is extinguished and substituted by the new obligation IMPLIED incompatibility between the old and the new obligations that they cannot stand together 2. it is imperative that 1. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. The agreement of all parties to the new contract 3. Substituting the person of the debtor 3. As to object OBJECTIVE/REAL change in the cause. Extinguishment of the old contract 4. Does not operate as absolute but only as a relative extinction.subrogation of a third person in the rights of the creditor MIXED both objective and subjective novation 4. Validity of the new one 5. the cause or the principal conditions of the obligations. In general extinguishment of the original obligation and creation of a new one 2. original SUBSISTS Art 1297 If the new obligation is void. pledgor. y Pending the happening of the condition. novation itself must be held to be conditional also and its efficacy depends upon whether the condition which affects the former is complied with or not y Suspensive condition of the original not performed. cause for the new obligation is wanting y Resolutory condition. OBJECTIVE NOVATION change in the object of prestations Meaning of PRINCIPAL CONDITIONS . Labitag [2 Page 68 of 110 y California Bus Line v State Investment Effects of Novation 1. surety or guaranty Effect of the Status of the Original or the New Obligation 1. obligation does not come into existence. y Where the original obligation is conditional. A. 2008-2009] OBLIGATIONS & CONTRACTS | Prof.n dSemester. no novation If intention is extinguish the original obligation itself by the creation of a new obligation. making the debt absolute instead of conditional and vice-versa) Sir Labitag lecture notes . Santos | UP Law B2012 . the novation does not arise except from fulfillment of the condition from original obligation. unless the parties intended that the former one shall be extinguished in any event. Nullity of the original obligation new obligation is VOID y One of the requisites of novation is a previous valid obligation y Also applies to voidable that are already annulled/extinguished Voidability of the original obligation new obligation is VALID if ratified before novation new obligation is VALID even if not ratified. same category as void obligation or one which has been extinguished Original obligation is pure New obligation is conditional y If the intention is merely to attach the condition to the original obligation. unless it is otherwise stipulated. 3. the old obligation is enforceable Art 1299 If the original obligation was subject to a suspensive or resolutory condition. Suspensive or resolutory condition of original obligation New is pure If intention is merely to suppress the condition. guaranty was given to any for a particular obligation or for the insolvency of a particular debtor. but voidable at the instance of the debtor y Consent of debtor constitutes implied waiver of the action for nullity y Defect is not completely cured in expromision wherein debtor has not intervened or consented Art 1298 The novation is void if the original obligation was void. the new obligation shall be under the same condition.principal conditions or terms (e. When accessory obligation may subsist only insofar as they may benefit third person who did not give the consent to the novation y Why? Mortgage.Y.Dacion en pago is an objective novation Karichi E. the original one shall subsist. y If the new conditional obligation is intended to substitute the original and pure obligation. novation (and consequent extinguishment of the original) is subject to the condition. or when ratification validates acts which are voidable. except when annulment may be claimed only by the debtor. 2.g. any change in either of this destroys the basis of the consent of the mortgagor. Nullity of the new obligation original SUBSISTS . pledge. there is no novation . UNLESS intends extinguishment of former in any event Voidability of the new obligation new obligation is VALID y BUT if new obligation is annulled and set aside. such as those arising from a mortgage.g. except that if he paid without the knowledge or against the will of the debtor. E. Without the release. Why? Substitution of one debtor for another may delay or prevent the fulfillment of the obligation by reason of the inability or insolvency of the new debtor o Consent may be implied or express as long as it is given. then it will be an implied novation. Knowledge or consent of the debtor is not required Art 1293 Novation which consists in substituting a new debtor in the place of the original one. there is no novation.g. The debtor is released from obligation 2. that is a novation. If substitution is without his knowledge or consent a. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. rd o However. to subrogate him in his rights . the first and the new debtor are considered obligated jointly.Y. the person who assumed the obligation of the debtor merely becomes a co-debtor or a surety No agreement to solidarity. it s not a novation if you change the amount. A. Art 1293 ) Karichi E. EXPROMISION . b.Increase in amount and you can prove that the intention to novate. By change of debtor CONSENT OF THE THIRD PARTY ALWAYS REQUIRED. obligation for contract of deposit for one of loan. but usually. DELEGACION y Debtor offers and the creditor accepts a third person who consents to the substitution so that the consent of the three is necessary y Delegante (old debtor). Art 1237 Whoever pays on behalf of the debtor without the knowledge or against the will of the latter. If substitution is with knowledge and consent a. the consent of the creditor is required. guaranty. Consent of two parties (new debtor and creditor) 2. may be made even without the knowledge or against the will of the original debtor. no novation because no consent to the transfer of the debt itself rd It is not enough to extend the juridical relation to a 3 person. but not without the consent of the creditor . The new debtor can only compel old debtor to reimburse inasmuch as the payment has been beneficial to him No subrogation takes place (Art 1237) 4. Payment by the new debtor gives him the rights mentioned in Art 1236 and Art 1237.May be done at the instance of the creditor or the third party himself Requisites of Expromision 1. he can recover only insofar as the payment has been beneficial to the debtor. cannot compel the creditor Effects of Expromision 1.Extension of time does not imply novation. Old debtor is not liable for the insolvency or non-fulfillment of the new debtor (Art 1294) b. . Santos | UP Law B2012 . delegatario (creditor) and delegado (third person new debtor) Requisites of Delegacion (vs. Ynchausti v Yulo . SUBJECTIVE NOVATION In all kinds of subjective novation. Labitag [2 Page 69 of 110 . Why? Because he assumes the obligation CONSENT OF THE CREDITOR IS LIKEWISE INDISPENSABLE. or penalty. or a contract of deposit to one of commodatum. the new debtor s insolvency or non-fulfillment of the obligation shall NOT give rise to any liability on the part of the debtor.n dSemester. New debtor is entitled to full reimbursement of the amount paid and subrogation Art 1294 If the substitution is without the knowledge or against the will of the debtor.Convertion of an obligation to some other obligation e. it cannot be presumed from his acceptance of payments by a 3 party for the benefit of the debtor without further acts. Creditor generally cannot recourse from the old debtor if the new debtor is insolvent 3. 1. a. it is necessary that the old debtor be released rd from the obligation and the 3 person or new debtor takes his place. Art 1236 Par 2 Whoever pays for another may demand from the debtor what he has paid . But if the time situation is reversed (shortening of the period). Consent of the debtor old is extinguished and he becomes liable to a new obligation 3. the latter must be clearly established in order that it may take effect. Original debtor is released from the obligation 2. that condition must be fulfilled first in order the new creditor may exercise his rights. By change of creditor: subrogation of a third person in the rights of the creditor Art 1300 Subrogation of a third person in the rights of a creditor is either legal or conventional. He may demand from the old debtor the entire amount of what he has paid for the obligation.n dSemester. The transfer of all the rights of the creditor to a third person who substitutes him in all his rights. o If suspensive condition is attached. subject to stipulation in a conventional subrogation. to whom partial payment has been made. EXCEPT when said insolvency was already existing and of public knowledge OR known to the debtor when he delegated his debt . a. Acceptance by the creditor Effects of Delegacion 1. GENERAL RULE: Old debtor is not liable for the insolvency or non-fulfillment of the new debtor (Art 1295) EXCEPTION: i.Y. Labitag [2 Page 70 of 110 1. Consent of the new debtor 3. 2. Santos | UP Law B2012 . Case: y Licaros v Gatmaitan Karichi E. be they guarantors or possessors of mortgages. A. except in cases expressly mentioned in this Code. The new debtor is subrogated in the rights of the creditor. either against the creditor or against third persons. The former is not presumed. Art 1304 A creditor. the new debtor s insolvency is already existing and of public knowledge (Art 1295) Art 1295 The insolvency of the new debtor who has been proposed by the original debtor and accepted by the creditor shall NOT REVIVE the action of the latter against the original obligor. Cases: y Garcia v Llamas y Quinto v People 2. Consent of the third person new creditor becomes a party to the new relation Distinguished from Assignment of Credits CONVENTIONAL SUBROGATION ASSIGNMENT OF CREDITS Debtor s consent is necessary Debtor s consent no t required Extinguishes the old obligation and gives rise to a new one Refers to the same right which passes from one person to another The nullity of an old obligation may be cured by subrogation Nullity of an obligation is not remedied by the assignment of the such that the new obligation will be perfectly valid creditor s right to another Effects of Conventional Subrogation 1. Initiative for substitution must emanate from the old debtor 2. Art 1303 Subrogation transfers to the person subrogated the credit with all the rights thereto appertaining. (Art 1302 Par 2) 3. Consent of the old creditor because his right is extinguished 2. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. He is aware of the insolvency at the time he delegated his debt (Art 1295) ii. At the time of the delegation. CONVENTIONAL SUBROGATION .Takes place by agreement of the parties Requisites of Conventional Subrogation (Art 1301) 1. may exercise his right for the remainder and he shall be preferred to the person who has been subrogated in his place in virtue of the partial payment of the same credit. even without the knowledge of the debtor. to whom partial payment has been made.Takes place without agreement but by operation of law because of certain acts . A. that condition must be fulfilled first in order the new creditor may exercise his rights. even without the debtor s knowledge o Refers to hierarchy of credits which will be taught next sem hehe o Debtor can still use any defenses he may have against the original creditor such as compensation 2. o If suspensive condition is attached. without prejudice to the effects of confusion as to the latter s share o Solidary co-debtor may reimburse to the extent of the debtor s share o Guarantors. Art 1303 Subrogation transfers to the person subrogated the credit with all the rights thereto appertaining. either against the creditor or against third persons. pays with the express/tacit approval of the debtor 3. When a creditor pays another creditor who is preferred . mortgagors and sureties Effects of Legal Subrogation 1. EXCEPTION: Art 1302 . When a 3 r d person. When. Art 1304 A creditor. Labitag [2 Page 71 of 110 b. be they guarantors or possessors of mortgages. subject to stipulation in a conventional subrogation.The third person is called legal subrogee Requisites of Legal Subrogation When is Legal Subrogation presumed Art 1302 It is presumed that there is legal subrogation: 1. may exercise his right for the remainder and he shall be preferred to the person who has been subrogated in his place in virtue of the partial payment of the same credit. not interested in the obligation.n dSemester. Santos | UP Law B2012 . LEGAL SUBROGATION . 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Case: y Astro Electronics Corp v Philippine Export and Foreign Loan Guarantee Corporation Karichi E.Y.GENERAL RULE: Not presumed. 2. a person interested in the fulfillment of the obligation pays. bond Case: y GSIS v CA C. its of one of them. to which is repugnant to have one party bound by the contract leaving the other free therefrom B. Art 1308 The contracts must bind both contracting parties. the courts shall Art 1473 The fixing of the price can never be left to the discretion of one of the contracting parties However. Consent b. the sale is perfected. to do or not to do. whose decision shall not be binding until it has been made known to both contracting parties . because the law.n dSemester. Relativity binding only upon the parties and their successors a.g. to give something or to render some service. infra) without which there can be no contract a. Karichi E. DEFINITION Art 1305 A contract is a meeting of minds between two persons whereby one binds himself. warranty against hidden defects or eviction in the contract of purchase and sale 3. 3. In such case. or reciprocally. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. CONTRACT OF ADHESION: A contract in which one party has already prepared a form of a contract containing stipulations desired by him and he simply asks the other party to agree to them if he wants to enter into the contract. Essential elements (Chapter II. guaranty.Y. Labitag [2 Page 72 of 110 Title II. Natural elements exist as part of the contract even if the parties do not provide for them.g. by virtue of which one or more persons bind themselves in favor of another or others.Sanchez Roman: a juridical convention manifested in legal form. Accidental elements agreed upon by the parties and which cannot exist without being stipulated e. validity or compliance cannot be left to the will Art 1309 The determination of the performance may be left to a third person. Santos | UP Law B2012 . . Contracts take effect only between the parties. General Provisions A. . CONTRACTS Chapter I. with respect to the other. E.Binding effect of contract based on the following principles o Obligations arising from the contract have the force of law between the contracting parties o There must be mutuality between the parties based on their essential equality. to the fulfillment of a prestation to give. their assignments and heirs . if the price fixed by one of the parties is accepted by the other. Object c. Obligatory force constitutes the law as between the parties Art 1308 The contracts must bind both contracting parties of one of them. CHARACTERISTICS OF A CONTRACT 1. . its validity or compliance cannot be left to the will 2. creates them. Art 1310 The determination shall not be obligatory if it is decide what is equitable under the circumstances. mortgage. A. Cause 2. Mutuality validity and performance cannot be left to the will of only one of the parties y Purpose is to render void a contract containing a condition which makes fulfillment dependent exclusively upon the uncontrolled will of the one of the contracting parties. as suppletory to the contract. ELEMENTS OF A CONTRACT 1. evidently inequitable .Limited to that which produces patrimonial liabilities . partnership and agency b. Santos | UP Law B2012 . Consensuality Freedom entering into contracts is a guaranteed right of the citizens. terms and conditions as they may deem convenient. FC inter vivos donation between spouses o Art 1490 husband and wife generally cannot sell property to each other. D. public order and public policy. subject to exceptions o Art 1491 special prohibition as to who cannot acquire by purchase o Art 1782 persons prohibited from giving each other any donation or advantage. public order and public policy o A contract is to be judged by its character. o As long as there are two distinct patrimonies. good customs. Freedom to contract Art 1306 The contracting parties may establish such stipulations. Art 1302 Par 1) Case: y Gutierrez Hermanos v Orense Two more general principles of contracts that were not included in your book/syllabus 4. clauses. public order and public policy. Not by the number of individual wills but by the number of declarations of will. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. PARTIES IN A CONTRACT 1.Y. 2. y Unenforceable unless ratified expressly or impliedly (Unenforceable Contracts. morals. Labitag [2 Page 73 of 110 Art 1311 Par 1 Contracts take effect only between the parties. The heir is not liable beyond the value of property he received from the decedent. What they may not stipulate Art 1306 contrary to law. Auto-contracts o Necessary for the existence of a contract that two distinct persons enter into it o No general prohibitions. Cases: y Gabriel v Monte de Piedad y Pakistan International Airlines v Ople Special disqualifications : o Art 87. only special prohibitions such as Art 1491 (Persons who cannot acquire by purchase.n dSemester. 5. INTRANSMISSIBLE CONTRACTS: a. Payment of money debts not transmitted to the heirs but to the estate Cases: y Manila Railroad Co v La Compana Transatlantica y DKC Holdings Corp v CA b. good customs. courts will look into the substance and not to the mere form of the transaction a. customs. Contrary to law Karichi E. They are free to do so as long as it s not contrary to law. even if they are represented by the same person. A. provided they are not contrary to law. morals. but by the number of parties .g. good morals. Very nature of obligation that requires special personal qualifications of the obligor c. Purely personal e. even at a public or judicial auction) o Auto-contracts are generally VALID Existence of a contract is not determined by the number of persons who intervene in it. No one may contract in the name of another Art 1317 No one may contract in the name of another without being authorized by the latter or unless he has by law a right to represent him. assigns and heirs EXCEPT in case where the rights and obligations arising from the contract are no transmissible by their nature or by stipulation or by provision of law. cannot enter into universal partnership 3. CLASSIFICATION OF CONTRACTS 1.g. Contrary to public order y Consideration of the public good. Services 2. More or less universal. Pactum de non alienado not to alienate Art 2130 A stipulation forbidding the owner from alienating the immovable mortgaged shall be void b. Cases: y Dizon v Gaborro i. Those stipulation must be limited to time. Do ut facias I give. by the provisions of Titles I and II of this Book. sometimes they only apply to certain communities or localities y E. ii. INNOMINATE without particular names Art 1307 Innominate contract shall be regulated by the stipulations of the parties. Contrary to good customs y Custom pertains to certain precepts that cannot be universally recognized as moral. Prohibitive 3. According to subject matter a. Contrary to morals y Man s innate sense or notion of what is right and wrong. by the rules governing the most analogous nominate contracts and by customs of the place . Liguez v CA d. peace and safety of the public and health of the community e. Things b. Expressly declare their obligatory character 2. Contrary to public policy y Court must find that the contract contravenes some established interest of the society y E. Do ut des I give. you do iii. Express fundamental principles of justice which cannot be overlooked by the contracting parties 4. or dispose of them. will or weal (welfare). you give ii. you do Karichi E. Any stipulation to the contrary is null and void.n dSemester.Y. A.g. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Impose essential requisites without which the contract cannot exist i. place and extent Cases: y Cui v Arellano y Arroyo v Berwin y Filipinas Compania de Seguros v Mandanas y Bustamante v Rosel E. Pactum leonina one party bears the lion s share of the risk Art 1799 A stipulation including one or more parties from any share in the profits or losses is void iii. According to a. b. Santos | UP Law B2012 . Facio ut facias I do. c.stipulation not to engage in competitive enterprise after leaving the employment. Ferrazzini v Gsel . name NOMINATE have their own individuality (names) and are regulated by special provisions of law. Labitag [2 Page 74 of 110 Laws a contract must not intervene: 1. Pactum commissorium automatic foreclosure Art 2088 The creditor cannot appropriate the things given by way of pledge or mortgage. commodatum or gratuitous deposit b. Commutative b. 4. Perfection moment when the parties come to agree on the terms of the contract c. purchase and sale c.g. According to form a. According to cause a.g. Onerous b. According to perfection a. By DELIVERY OF THE OBJECT (real) commodatum Art 1316 Real contracts such as deposit. you give 3.g. may be in keeping with good faith.g. degree of dependence a. Special or formal e. ending at the moment of agreement of the parties b. pledge and commodatum. b. Aleatory F. Facio ut des I do. Transfer of ownership e. purchase and sale Art 1315 Contracts are perfected by mere consent . AS DISTINGUISHED FROM A PERFECTED PROMISE AND AN IMPERFECT PROMISE (policitation) CONTRACT PERFECTED PROMISE IMPERFECT PROMISE Establishes and determines the Tends only to assure and pave the way for the obligation arising therefrom celebration of a contract in the future.g. nature of obligation produced a. he may demand its fulfillment provided he communicated his acceptance to the obligor before its revocation. Consummation or death fulfillment or the performance of the terms agreed upon in the contract G. agency 7. According to risk a. commodatum c. Common or informal e. Gratuitous or lucrative 9. usage and law. pledge. the parties are bound not only to fulfillment of what has been expressly stipulated but also to all the consequences which.Y.g.g. Accessory e.e. A. Labitag [2 Page 75 of 110 iv. STAGES OF CONTRACTS a. According to the nature of the vinculum produced. agency b.g. According to its relation to other contracts. according to their nature.g. Preparatory e. are not perfected until the delivery of the object of obligation. the rights and o bligations are no t yet determined Mere unaccepted o ffer H. Santos | UP Law B2012 . donations and mortgages of immovable property 6.g. mortgage or suretyship 5.n dSemester. Principal e. According to purpose a. Stipulations in favor of third persons acceptance is made prior to revocation (stipulation pour autrui) may demand its fulfillment provided the Art 1311 Par 2 If a contract should contain some stipulation in favor of a third person. Conveyance of use e. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. sale or barter b. WITH RESPECT TO THIRD PERSONS 1. and from that moment. Rendition of services e. By MERE CONSENT (consensual) e. loan b.g. A mere incidental Karichi E. until the contract is actually made. Reciprocal 8. Bilateral or sinalagmatico e. Preparation period of negotiation and bargaining. Unilateral . lease or sale c. 4. Stipulation in favor of third person is a part.n dSemester. REQUISITES OF CONSENT 1. y Art 1387 . Santos | UP Law B2012 . Existence of a valid contract b. Intelligent and free will 4. in such a case. Neither of the contracting parties bear the legal representation or authorization of the third party rd person was clearly and deliberately conferred to by parties d. The contracting parties must have conferred favor upon third person. Essential Requisites of Contracts CONSENT Art 1319 Consent is manifested by the MEETING of the offer and the acceptance upon the thing and the cause which are to constitute the contract. A. third persons who come into possession of the object of the contract are bound thereby. subject to he provisions of the Mortgage Law and the Land Registration laws. Creditors of the contracting parties Art 1313 Creditors are protected in cases of contracts intended to defraud them. Third person communicated his acceptance to the obligor before the latter revokes the same 2. Benefit to the 3 e. Must be MANIFESTED by the concurrence of the offer and acceptance Cases: y Rosenstock v Burke y Malbarosa v CA with respect to object and cause Karichi E. Knowledge by a third person of the existence of a contract c. Favorable stipulation not conditioned or compensated by any kind of obligation whatever c. Interference by the third person in the contractual relation without legal justification Cases: y Daywalt v La Corporacio de los Padres Agustinos Recoletos y So Ping Bun v CA 3. Capacity 3. Plurality of subjects 2. not the whole of the contract b. presumption of fraudulent alienation when debtor does leave sufficient property to cover his obligations y Creditor may ask for rescission Art 1177 (accion subrogatoria) and Art 1381 (accion pauliana) Interference by third persons Art 1314 Any third person who induces another to violate his contract shall be liable for damages to the other contracting party. is PRESUMED to have been entered into in the place where the offer was made . Possession of the object of contract by third persons only for real rights Art 1312 In contracts creating real rights . 1. it must be the purpose and intent of the stipulating parties to benefit the third person y Requisites of stipulacion pour autrui a. A qualified acceptance constitutes a counter-offer. The offer must be certain and the acceptance absolute. Acceptance made by letter or telegram does not bind the offerer except from the time it came to his knowledge The contract. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Labitag [2 Page 76 of 110 interest or benefit of a person is not sufficient. y clearly and deliberately Test of beneficial stipulation A mere incidental interest of a 3 rd person is not within the doctrine. Chapter II.Y.in rescissible contracts. Conformity of the internal will and its manifestation . y Liability for damages: third person s liability cannot be more than the party he induced (Daywalt v Recoletos) y Requisites of Interference With Contractual Relation by Third Person a. Express or tacit manifestation of will 5. Santos | UP Law B2012 . e. It must be: a. all of which must be c. o Not applicable to judicial sale wherein the highest bid must necessarily be accepted Case: y Jardine Davies v CA ACCEPTANCE an unaccepted offer does not give rise to consent y Contract is perfect when the offeror or counter-offeror learns about the acceptance! a. Period of acceptance Art 1324 When the offerer has allowed the offeree a certain period to accept y Offeree may accept any time until such period expires. Must be absolute (Art 1319) b. business advertisements of things for sale are mere invitation to make an offer . y Acceptance not made in the manner provided by the offeror is ineffective. or the fact of immediately carrying out the contract offered QUALIFIED (Art 1319) not an acceptance but constitutes a counter-offer c. Circumstances when offer becomes defective Art 1323 An offer becomes ineffective upon the party before acceptance is conveyed. insanity or insolvency of either Business advertisements of things for sale not definite offers Art 1325 Unless it appears otherwise. mailing if by letter 3. Cognition Theory knowledge of offeror of the acceptance Art 1319 Par 2 except from the time of his knowledge d. UNLESS the contrary appears. civil interdiction. does not bind the offerer except from the time it came Four theories on when the contract is perfected 1. Reception Theory receipt of the message of acceptance 4. not definite if object is not determinate y COMPLETE indicating with sufficient clearness the kind of contract intended and definitely stating the essential conditions of the proposed contract. of acceptance. not definite offers . d. as well as the non-essential ones desired by the offeror y INTENTIONAL should be serious and not made for fun or in jest b.n dSemester. but f. What may be fixed by the offeror time. place and manner of acceptance Art 1321 The person making the offer may fix the time. A. insanity or insolvency death. death. Manifestation theory counterofferee manifest his acceptance 2. Advertisement for bidders Art 1326 Advertisements for bidders are simply invitations to make proposals .Y. Kinds of acceptance EXPRESS (Art 1320) IMPLIED (Art 1320) arise from acts or facts which reveal the intent to accept such as the consumption of things sent to the offeree. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Labitag [2 Page 77 of 110 OFFERunilateral proposition which one party makes to the other for the celebration of the contract. When made through the agent accepted from the time acceptance communicated to the agent Art 1322 An offer made through an agent is accepted from the time acceptance is communicated to him. If made by letter or telegram Art 1319 Par 2 Acceptance made by letter or telegram to his knowledge . civil interdiction. and the advertiser is not bound to accept the highest of lowest bidder. place and manner complied with. Expedition Theory sending of the letter. Must be certain (Art 1319) y DEFINITE so that upon acceptance an agreement can be reached on the whole contract. Karichi E. y Extinguishment or annulment of offer o Withdrawal by the offeror o Lapse of the time for option period o Legally incapacitated to act o Offeree makes counter-offer o Contract becomes illegal Case: y Sanchez v Rigos e.n dSemester. as something paid or promised. Necessary LEGAL CAPACITIES of the parties Who cannot give consent Art 1327 The following cannot give consent to a contract: 1. The consent must be INTELLIGENT. Santos | UP Law B2012 . Insane or demented persons 3. Mistake as to the identity or qualifications of one of the parties will vitiate consent only when such identity or qualifications have been the principal cause of the contract . Acceptance not made in the manner provided by the offeror is ineffective. Deaf-mutes who do not know how to write When offer and/or acceptance is made During a lucid interval VALID In a state of drunkenness VOIDABLE utter want of understanding During a hypnotic spell VOIDABLE utter want of understanding 3. If offeror has not fixed the period. undue influence. or to those conditions which have principally moved one or both parties to enter into the contract. y Mistake and violence spontaneous and intelligence Effect of Defects of Will: Contract is VOIDABLE (Art 1330) VICES OF CONSENT a. intimidation. for a fixed period and under specified conditions. y Preparatory contract in which one party grants to the other. EXCEPT when the option is founded upon a consideration . Karichi E. violence. Contract of option Art 1324 the offer may be withdrawn at any time before acceptance by communicating such withdrawal. Art 1331 In order that MISTAKE may invalidate consent. Case: y Adelfa Properties v CA 2. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. fact or event which in reality does not exist. even if the option had already been accepted.Y. FREE. Offer implies an obligation on the part of the offeror to maintain it for such a length of time as to permit the offeree to decide whether to accept it or not. SPONTANEOUS and REAL Art 1330 A contract where consent is given through mistake. it should refer to the substance of the thing which is the object of the contract. the power to decide whether or not to enter into a principal contract y Must be supported by an independent consideration and the grant must be exclusive y If the option is not supported by an independent consideration. the offeree must accept immediately within a reasonable tacit period. Unemancipated minors 2. a belief in the existence of some circumstance. offeror can withdraw the privilege at any time by communicating the withdrawal to the other party. Labitag [2 Page 78 of 110 y y y y Acceptance beyond the time fixed is not legally an acceptance but constitutes a new offer. A. Mistake or Error a wrong or false notion about such matter. or fraud is VOIDABLE . Error in the value of thing c. or if the contract is in a language not understood by him.generally not . but to accessory matters in the contract. not as stipulated in the contract but as provided by alw b. As to substance of object Invalidates consent if refers to the substance of the thing But if mistake in lot number for instance.Y. Error must be as to the legal effect of an agreement includes rights and obligations of the parties. foreign to the determination of the objects Cases: y Asiain v Jalandoni y Theis v CA y Heirs of William Sevilla v Leopoldo Sevilla 2. Must be mutual c. As to quantity . 1. Error with respect to accidental qualities of the object of the contract b.generally not a ground for annulment of contracts y Ground of mistake based on error is limited to cases in which it may reasonably be said that without such error the consent would not have been given y Effect of mistake is determined by whether the parties would still have entered into the contract despite knowledge of true fact influence upon party a. Labitag [2 Page 79 of 110 A simple mistake of account KINDS OF MISTAKE shall give rise to its correction. As to principal conditions (essential or substantial in character) c. Error of law mistake as to the existence of a legal provision or as to its interpretation or application GENERAL RULE: Ignorantia legis neminem excusat Art 3 Ignorance of the law excuses no one from compliance therewith. EXCEPTION: Mutual error of law Art 1334 Mutual error as to the legal effect of an agreement when the real purpose of the parties is frustrated. Mistake of fact . the person enforcing the contract must show that the terms thereof have been fully explained to the former . y Requisites for mutual error of law a.g. Error which refers not to conditions of the thing. A. may vitiate consent . except when the qualification is the principal cause of the contract especially in gratuitous contracts For qualifications Invalidates consent Solvency of the party not a cause of nullity Error of account is a mistake in computation make proper correction Error as to quantity may vitiate a contract if the primary consideration is the quantity e. Cases: y Dumasug v Modelo y Hemedes v CA y Katipunan v Katipunan Karichi E. remedy is only reformation o f the contract Invalidates consent For identity/error as to person . As to identity or qualifications of one of the parties d. as distinguished from simple mistake of account Mistakes that do not affect the validity of the contract a. parcel of land was actually only 10 ha and not 30 ha b. Real purpose of the parties is frustrated When one of the parties is unable to read and fraud is alleged burden of proof on party enforcing the contract Art 1332 When one of the parties is unable to read. Santos | UP Law B2012 . and mistake or fraud is alleged. 2008-2009] OBLIGATIONS & CONTRACTS | Prof.n dSemester. but to submit 2. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. A threat to enforce one's claim through competent authority. That it produces a reasonable and well-grounded fear from the fact that the person from whom it come has the necessary means or ability to inflict the threatened injury Person not limited to life and physical integrity but also includes liberty ad honor. That the threat be real and serious. Physical force employed must be irresistible or of such a degree that the victim has no other course. Violence and Intimidation Art 1335 There is VIOLENCE when in order to wrest consent. to give his consent. serious or irresistible force is employed.Y. does NOTvitiate consent. Caused by manifest negligence b. There is INTIMIDATION when one of the contracting parties is compelled by a reasonable and well-grounded fear of an imminent and grave evil upon his person or property. although it may have been employed by a third person Karichi E. Labitag [2 Page 80 of 110 Inexcusable mistake knew the doubt. sex and condition of the person shall be borne in mind. That such force is the determining cause in giving the consent to the contract INTIMIDATION y Moral force or compulsion y Internal operating upon the will and induces the performance of an act y Influences the mind to choose between two evils. if the claim is just or legal. the age. Case: y Martinez v HSBC ANNUL the obligation. there being an evident disproportion between the evil and the resistance which all men can offer. leading to the choice of the contract as the lesser evil 4.n dSemester. covers all injuries which are not patrimonial in nature Reasonable fear the threat fear occasioned by the threat must be reasonable and well-grounded. intellectual capacity of the person who made the mistake y E. or must have caused the consent to be given 2.g. it must be commensurate with Effect of Violence and Intimidation Art 1336 Violence or intimidation shall who did not take part in the contract. descendants or ascendants. Intimidation must be the determining cause of the contract. between the contract and the imminent injury y Requisites of Intimidation 1. That the threatened act be unjust or unlawful 3. Santos | UP Law B2012 . y Party cannot alleged error which refers to a fact known to him or which he should have known by ordinary diligent examination of the facts y Courts consider not only the objective aspect of the case but also the subjective e. or upon the person or property of his spouse. DURESS : degree of constraint or danger either actually inflicted ( violence ) or threatened and impending (intimidation ) sufficient to overcome the mind and will of a person of ordinary firmness Seriousness of the evil or wrong measured both objectively (degree of harm that the evil in itself is likely to produce) and subjectively (determining the effect of the threat upon the mind of the victim in view of his personal circumstances and his relation to the author of the intimidation) VIOLENCE y Physical force or compulsion y External and generally serve to prevent an act from being done y Requisites of Violence 1. contingency or risk Art 1333 There is no mistake if the party alleging it knew the doubt. A. To determine the degree of intimidation. contingency or risk affecting the object of the contract. under the circumstances.g. fraud is compensated 2. only gives rise to action for damages Art 1344 Par 2 Incidental fraud only obliges the person employing it to pay damages. under the circumstances. or the fact that the person alleged to have been unduly influenced was suffering from mental weakness . without them. for the purpose of leading a party into error and thus execute a particular act. ground for annulment of contract Art 1338 without them. through insidious words or machinations of one of the contracting parties other is induced to enter into a contract which. without necessarily constituting estafa or some offense under the penal laws. he would not have agreed to . all the thousand and one forms of deception which may influence the consent of a contracting party.n dSemester. Induced the other party to enter into a contract (Art 1338) 3. or was ignorant or in financial distress . undue influence by a third person may also vitiate consent (Art 1336) d. he could not well resist.Y. Distinguished from intimidation UNDUE INFLUENCE INTIMIDATION There need not be an unjust or unlawful act Unlawful o r unjust act which is threatened and which causes consent to be given Moral coercion By analogy. fictitious names. . they cannot have action against each other. Must have a determining influence on the consent of the victim Compared with error ERROR FRAUD Vitiate the consent only when it refers to the matters mentio ned in Art 1331 Mistake induced by fraud will always vitiate consent when fraud has a decisive influence on such consent Requisites of Fraud 1. Must have been serious (Art 1344) 4. and which controlled his volition and induced him to give his consent to the contract which otherwise he would not have entered into. exaggeration of hopes or benefits. manipulations concealments. spiritual and other relations between the parties. Must have resulted in damage or injury to the party seeking annulment Art 1338 There is FRAUD when. but only refers to some particular or accident of the obligation. 2. he would not have agreed to . misrepresentation. Dolo incidente does not have such a decisive influence and by itself cannot cause the giving of consent. Labitag [2 Page 81 of 110 c. Cases: y Hill v Veloso y Woodhouse v Halili supra y Geraldez v CA supra Kinds of Fraud 1. Art 1337 There is UNDUE INFLUENCE when a person takes improper advantage of his power over the will of another. In some measure destroy the free agency of a party and interfere with the exercise of that independent discretion which is necessary for determining the advantages and disadvantages of a contract. Insidious words and machinations constituting deceit includes false promises. Dolo causante determines or is the essential cause of the consent. Must have been employed by one contracting party upon the other (Art 1342 and Art 1344) y If both party. The following circumstances shall be considered: the confidential. Santos | UP Law B2012 . qualifications or authority. A. duty to reveal them FRAUD Karichi E. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Undue Influence any means employed upon a party which. Fraud or Dolo every kind of deception whether in the form of insidious machination. depriving the latter of a reasonable freedom of choice. the Failure to disclose facts. abuse of confidence. family. opportunity to know the facts NOT FRAUD Art 1340 The usual exaggerations in trade. Misrepresentation 1.n dSemester. Made in good faith not fraudulent but may constitute error Art 1343 Misrepresentation made in good faith is not fraudulent but may constitute error. VIOLENCE AND INTIMIDATION BY 3R D PERSON: annuls the contract RD FRAUD BY 3 PERSON: does not annul unless it produces substantial mistake on the part of both parties JUSTIFICATION FOR THE DIFFERENCE: y Party has nothing to do with fraud by a third person and cannot be blamed for it y Intimidation can be more easily resisted than fraud 2. There is a special duty to disclose certain facts 2. Maria v CA Usual exaggeration in trade. import of opportunity to know facts Cases: y Azarraga v Gay y Trinidad v IAC Mere expression of an opinion Art 1341 A mere expression of an opinion former's special knowledge. GENERAL RULE: Fraud by third person does not vitiate the contract EXCEPTIONS: a. If 3 rd person is in collusion with one of the parties. constitutes FRAUD .Y. unless made by an expert and relied upon by the plaintiff DOES NOT signify fraud. According to good faith and usages of commerce the communication should have been made Cases: y Tuason v Marquez y Rural Bank of Sta. Nullity of the contract 2. the consent is vitiated. A. he is considered an accomplice to the fraud and contract becomes VOIDABLE b. Incidental fraud only obliges the person employing it to pay damages . Indemnification for damages Art 1344 In order that fraud may make a contract voidable. it should be serious and should not have been employed by BOTH contracting parties. when there is a duty to reveal them . when the other party had an opportunity to know the facts . unless such misrepresentation has created substantial mistake and the same is mutual. By a third person Art 1342 Misrepresentation by a third person does NOT vitiate consent. If 3 rd person not in connivance with any of the parties but leads them both into error (mutual error). are NOTin themselves fraudulent Aka tolerated fraud or lawful misrepresentation (dolus bonus) as long as they do not go to the extent of malice or bad faith such as changing the appearance of the thing by false devices and of preventing all verification or discovery of truth by the other party Caveat emptor! Do not give rise action for damages because of their insignificance OR because the stupidity of the victim is the real cause of his loss. Labitag [2 Page 82 of 110 Art 1339 Failure to disclose facts. contract is VOIDABLE. Karichi E. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. as when the parties are bound by confidential relations. Case: y Songco v Sellner e. unless made by an expert and the other party has relied on the Effects of Fraud 1. Santos | UP Law B2012 . GENERAL RULE: Silence or concealment does not constitute a fraud EXCEPTIONS: 1. NOT FRAUD. public order or public policy binds the parties to their real agreement. 1. for the purposes of deception the appearance of a juridical act which does not exist or is different from that which was really executed. the Parties have an agreement which they conceal under the parties not having intention to be bound guise of another contract VOID . when the parties conceal their true agreement. Illusory. The former takes place when the parties do not intend to be bound at all. good customs. when it does not prejudice a third person and is not intended for any purpose contrary to law. Labitag [2 Page 83 of 110 3. A relative simulation. Santos | UP Law B2012 . If does not have illicit purpose prove simulation to recover what may have been given 2. contract that the parties pretend to have executed 2. without any substance thereof. No contract may be entered into upon future inheritance except in cases expressly authorized by law. the latter. All services which are not contrary to law.n dSemester. right or service which is the subject-matter of the obligation arising from the contract Object of the contract and object of the obligation created thereby are identical What may be the Object of Contracts Art 1347 All things which are not outside the commerce of men . 2008-2009] OBLIGATIONS & CONTRACTS | Prof. mere phantom. morals. deliberately made by agreement of the parties in order to produce. Kinds of Simulated Contracts Art 1345 Simulation of a contract may be ABSOLUTEor RELATIVE . including future things. Ostensible acts apparent or fictitious. ABSOLUTE (simulados) RELATIVE (disimulados) Color o f contract. true agreement between the parties Recovery under simulated contract in absolute simulation 1. generally fraudulent purpose 1. If simulated has illegal object IN PARI DELICTO rules apply Cases: y Rodriguez v Rodriguez y Suntay v CA y Blanco v Quasha OBJECT OF CONTRACTS Thing. Active/passive o Applicable to legal capacity especially age Cases: y Mercado v Mercado y Braganza v Villa Abrille f. they may be made. good customs. Effects of simulation of contracts Art 1346 An absolutely simulated or fictitious contract is void.Y. may be the object of a contract. Simulation of Contracts declaration of a fictitious will. raised or acquired by the obligor after the perfection of the contract o Conditional subject to the coming into existence of the thing o Aleatory one of the parties bears the risk of the thing never coming into existence Karichi E.Does not legally exist. VALID except when it prejudices 3 rd persons or has an illicit injuring 3 rd persons. morals. A. All things not outside the commerce of man y Including future things do not belong to the obligor at the time the contract is made. public order or public policy may likewise be the object of a contract. Hidden act real. All rights which are not intransmissible may also be the object of contracts. status. Labitag [2 Page 84 of 110 Outside the commerce of man all kinds of things and interests whose alienation or free exchange is restricted by law or stipulation. y The succession must not have been opened at the time of the contract y Exception to future things Cases: y Blas v Santos y Tanedo v CA 6.g. Licit. marital authority. y E. Within the commerce of man (Art 1347) 2. honorary titles o Public offices. y What may NOT be the Objects of Contracts 1.g. patria postestas. Intransmissible rights 5. morals. pro vided it is possible to determine the same. morals. public policy or public order 2. Future inheritance. Possible (Art 1348) 4. Contrary to law. except when authorized by law Art 1347 Par 2 No contract may be entered into upon future inheritance except in cases expressly authorized by law. which parties cannot modify at will o Services which imply an absolute submission by those who render them. air and sea 2. good customs. perpetual servitude or slavery o Personal rights e.Y. good customs. capacity of persons.g. True Karichi E. without the need of a new contract between the parties. Outside the commerce of man 4. Indeterminable as to their kind 3. inherent attributes of the public authority. the immediate and most prox imate purpose of the contract. right of suffrage o Property while they pertain to the public dominion o Sacred things e. morals. sacrificing their liberty. All services not contrary to law. Santos | UP Law B2012 . All rights not intransmissible 3. Exist 2. public order or public policy Requisite of Object of Contracts 1. of impossible things: o Not susceptible of existing o Outside the commerce of man o Beyond the ordinary strength of power of man y Liability for damages o Debtor knew of impossibility liable for damages o Debtor is ignorant of impossibility and ignorance is justifiable no liability for damages o Both parties have knowledge of impossibility no liability for damages y Impossibility must be actual and contemporaneous with the making of the contract and not subsequent o ABSOLUTE or objective: nobody can perform it o RELATIVE or subjective: due to the special conditions or qualification of the debtor it cannot be performed _ TEMPORARY does not nullify the contract _ PERMANENT nullifies the contract CAUSE OF CONTRACTS Meaning of CAUSE Why of a contract. Determinate as to its kind Art 1349 The object of every contract must be determinate as to its kind . the essential reason which impels the contracting parties to enter into it and which ex plains and justifies the creation of the obligation through such contract Essential reason that moves the parties to enter into a contract Requisites of Cause 1. A. not contrary to law. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. independence or own beliefs or disregarding in any manner the equality and dignity of persons e. public policy or public order (Art 1347) 3. The fact that the quantity is not determinate shall not be an obstacle to the existence o f the contract. Impossible things or services Art 1348 Impossible things or services cannot be the object of contracts. political rights of individuals e.n dSemester.g.g. good customs. essential reaso n that compels contracting parties to celebrate the contract Never rejects any cause as insufficient. alienation is rescissible 2. Defective causes and their effects a. which does not affect the other and which does not impede the existence of a true distinct cause Objective of a party in entering into the contract Person s reason for wanting to get such objective Always the same for both parties Differs with each person GENERAL RULE: Motive does not affect the validity of the contract.Y. need not be material at all and may consist in moral satisfaction for the promissory Art 1350 In onerous contracts the cause is understood to be. CAUSE MOTIVE Objective. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. produce no effect whatever unlawful if it is contrary to law. the contract is likewise voidable. When the motive of a debtor in alienating property is to defraud his creditors. Licit As distinguished from object o Object is the starting point of agreement. a. fo r each contracting party. public order or public policy.g. Santos | UP Law B2012 .n dSemester. Onerous Contracts y Prestation or promise of a thing or service by the other y Need not be adequate or an exact equivalent in point of actual value especially in dealing with objects which have rapidly fluctuating price b. 3. Contracts of pure beneficence (Gratuitous) y Essentially agreements to give donations As distinguished from motive Art 1351 The particular motives of the parties in entering into a contract are different from the cause thereof. in case of intimidation the contract is voidable. Labitag [2 Page 85 of 110 3. A.g. without which the negotiations or bargaining between the parties would never have begun o Object may be the same for both of the parties o Cause is different with respect to each party As distinguished from consideration CONSIDERATION < CAUSE CONSIDERATION CAUSE Reason or motive or inducement by which a man is moved into bind himself by agreement Requires a legal detriment to the promisee more than a moral duety Why of contracts. the prestation or promise of a thing or service by the other. Absence of cause and unlawful cause produces no effect whatever Art 1352 Contracts without cause. and in contracts of pure beneficence . in remuneratory ones. the service or benefit which is remunerated. When the motive of a person induced him to act on the basis of fraud or misrepresentation by the other party. EXCEPTIONS: 1. intrinsic and juridical reason for the existence of Psychological. individual or personal purpose of a party to the contract itself the contract Essential reaso n for the contract Particular reason for a contracting party. When the motive of a person in giving his consent is to avoid a threatened injury. or with unlawful cause. good customs. Remuneratory Contracts y One where a party gives something to another because of some service or benefit given or rendered by the latter to the former where such service or benefit was not due as a legal obligation y E. the mere liberality of the benefactor. bonuses c. simulated contracts . The cause is Case: Karichi E. morals. y E. it is presumed that it exists and is lawful debtor proves the contrary. such as those referred to in (Sir refers to these as formal contracts) Art 748 Donation of movable Art 749 Donation of immovable Art 1874 Sale of piece of land through an agent Art 2134 Contract of antichresis. 2008-2009] OBLIGATIONS & CONTRACTS | Prof.Y. parties may compel each other to observe that form upon perfection of the contract) and Art 1358 (documents which must appear in a public document. .n dSemester. B. Ad esentia. ad solemnitatem Those required for the validity of contracts . mistake or undue influence. modification or extinguishment of real rights over immovable property. Cases: y Hernaez v De los Angeles C. GENERAL RULE: Contracts shall be obligatory . Santos | UP Law B2012 . in whatever form they may have been entered into. Cases: y Carantes v CA y Sps Buenaventura v CA Presumption of the existence and lawfulness of a cause. Lesion or inadequacy of cause VALID unless fraud. Karichi E. or that a contract be proved in a certain way. . 2. immovable property or real rights are contributed Art 1773 Partnership. inventory of immovable property contributed Art 1956 Interest for using someone else s money Art 2140 Chattel mortgage 2. the right of the parties stated in the following article cannot be exercised. parties VALID or Art 1356 However. sales of real property or of an interest therein a governed by Articles 1403. and 1405. Form of Contracts A. it also constitutes constructive delivery) (1) Acts and contracts which have for their object the creation. mistake or undue influence is present Art 1355 Except in cases specified by law. unless the Chapter III. Labitag [2 Page 86 of 110 y Liguez v CA b. but to make the contract effective as against third persons . provided all the essential requisites for their validity are present. when the law requires that a co ntract be in some form in order that it may be valid or enforceable. such as those covered by Art 1357 (if law requires a special form. though it is not stated in the contract Art 1354 Although the cause is not stated in the contract . No. EXCEPTION: When the law requires that a contract be in some form in order that it may be ENFORCEABLE (Anglo-American principle in Statutes of Fraud) indispensable and absolute. A. ( Spiritual system of the Spanish Code) all Art 1356 Co ntracts shall be obligatory. y Gross inadequacy suggest fraud and is evidence thereof c. provided essential requisites for their validity are present. if it should not be proved that they were founded upon another cause which is true and lawful. KINDS OF FORMALITIES REQUIRED BY LAW 1. Statement of a false cause in the contract VOID if there is no other true and lawful cause Art 1353 The statement of a false cause in contracts shall render them VOID . in whatever form they may have been entered into. amount of principal and of the interst Art 1771 Partnership. transmission. In such cases. Those required. not for the validity. that requirement is absolute and indispensable. lesion or inadequacy of cause shall not invalidate a contract UNLESS there has been fraud. Unilateral a. Mutual instrument includes something which should not be there or omit what should be there a. Causes failure of instrument to express true intention 2. inequitable conduct or accident . One party was mistaken b. Party in good faith may ask for reformation 3. Mistake of fact c. Meeting of the minds upon the contract 2. The failure of the instrument to express the true agreement is due to mistake. even a private 3. Other either acted fraudulently or inequitably or knew but concealed c. (4) The cession of actions or rights proceeding from an act appearing in a public document. the proper remedy is not reformation of the instrument but annulment of the contract . The true intention of the parties is not expressed in the instrument 3. fraud. All other contracts where the amount invo lved exceeds five hundred pesos must appear in writing. Santos | UP Law B2012 . there having been a meeting of the minds of the parties to a contract. 2 and 1405. Mutual b. Reason for Reformation of Instruments Equity dictates the reformation of instrument in order that the true intention of the contracting parties may be expressed. or any other power which has for its object an act appearing or which should appear in a public document. (3) The power to administer property . one . inequitable conduct or accident Cases: y Garcia v Bisaya y Bentir v Leande Causes for Reformation 1. Labitag [2 Page 87 of 110 (2) The cession. bad faith of drafter. such as those under the Statute of Frauds in Art 1403 Chapter IV. fraud. or accident has prevented a meeting of the minds of the parties. No. one of the parties may ask for the reformation of the instrument to the end that such true intention may be expressed. Unjust and inequitable to allow the enforcement of a written instrument which does not reflect or disclose the real meeting of the minds of the parties Court do not attempt to make a new contract for the parties. chattels or things in action are governed by Articles. repudiation or renunciation of hereditary rights or of those of the conjugal partnership of gains. negligence. by reason of mistake. Others specified by law to avoid frustration of true intent Example of cases where reformation is allowed Karichi E. If mistake. Ad probationem Those required for the purpose of proving the existence of the contract. their true intention is not expressed in the instrument purporting to embody the agreement.Y.n dSemester. 1403. or sho uld prejudice a third person. Mistake by 3 rd persons due to ignorance. Clear and convincing proof d. inequitable conduct. Reformation of Instruments Art 1359 When. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. but only to make the instrument express their real agreement Statute of Frauds is no impediment to the reformation of an instrument Distinguished from Annulment REFORMATION ANNULMENT Action presuppo ses a valid existing contract between the parties No meeting of the minds or the consent of either one was and only the document or instrument which was drawn up and vitiated by mistake or fraud signed by them does not correctly express the terms of agreement Gives life to the contract upon certain corrections Involves a complete nullification of contracts Requisites for Reformation of Instruments 1. fraud. lack of skill. A. clerk or typist 4. But sales of goods. the former may ask for the reformation of the instrument. Cases where no reformation is allowed 1. Art 1364 When through the ignorance. Labitag [2 Page 88 of 110 1. or his heirs and assigns . Cases: y Atilano v Atilano y Carantes v CA supra y Sarming v Dy Chapter V. y Generalia verba sunt generaliter intelligencia general things are to understood in a general sense Cases: y Borromea v CA y Kasilag v Rodriguez How to determine intention Karichi E. the courts may order that the instrument be reformed. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Art 1361 When a mutual mistake of the parties causes the failure of the instrument to disclose their real agreement. but concealed that fact from the former. Art 1366 There shall be no reformation in the following cases: (1) Simple donations inter vivos wherein no condition is imposed. if the mistake was mutual . Art 1363 When one party was mistaken and the other knew or believed that the instrument did not state their real agreement. the literal meaning of its stipulations shall control. y There has been election between two inconsistent remedies. Procedure of reformation Art 1369 The procedure for the reformation of instrument shall be governed by ROC to be promulgated by the Supreme Court. the instrument may be reformed. 3. Implied ratification Art 1367 When one of the parties has brought an action to enforce the instrument . Art 1362 If one party was mistaken and the other acted fraudulently or inequitably in such a way that the instrument does not show their true intention. he cannot subsequently ask for its reformation. Oral contracts there s nothing to reform at all! 2.n dSemester. heirs or assigns 1. Interpretation of Contracts (Compare with Rules on Statutory Construction) Primacy of intention Verba intentione non e contradebent inservare . said instrument may be reformed. 2. lack of skill. (3) When the real agreement is void. they shall not be understood to comprehend things that are distinct and cases that are different from those upon which the parties intended to agree . one in affirmance. negligence or bad faith on the part of the person drafting the instrument or of the clerk or typist . 2. A. Art 1372 However general the terms of a contract may be.words ought to be subservient to the intent. upon petition of the injured party . (2) Wills. Santos | UP Law B2012 .Y. not the intent to the word Look for the contractual intent Art 1370 If the terms of a contract are clear and leave no doubt upon the intention of the contracting parties. the other in disaffirmance Who may ask for reformation MUTUAL MISTAKE: either party or successor in interest MISTAKE BY ONE: injured party. otherwise . the instrument does not express the true intention of the parties. Art 1368 Reformation may be ordered at the instance of either party or his successors in interest . Also take note of the usage and customs of the place How to interpret a contract contemporaneous and subsequent acts shall 1. y Law in evidence. Applicability of Rule 12. some of which are doubtful Art 1374 The various stipulations of a contract shall be interpreted together.n dSemester. it shall be understood as bearing that import which is most adequate to render it effectual . their be principally considered. and shall fill the omission of stipulations which are ordinarily established. the contract shall be null and void . A. 10-19. Santos | UP Law B2012 . and the doubts refer to incidental circumstances of a gratuitous contract . most in keeping 4. In onerous contracts greatest reciprocity of interests 7. With respect to the party who caused the obscurity Art 1377 The interpretation of obscure words or stipulations in a contract shall not favor the party who caused the obscurity . In gratuitous contracts. but are effective as to other persons. attributing to the doubtful ones that sense which may result from all of them taken jointly . o Contracts of adhesion resolved against the party who prepared the contract and in favor of the one who merely adhered to it 6. 3. Rule 130) Art 1379 The principles of interpretation stated in Rule 123 of the Rules of Court shall likewise be observed in the construction of contracts. 2. When it contains various stipulations. 5. incidental circumstances least transmission of rights and interests b. When the doubts are cast upon the principal objects so that the intention cannot be known Art 1378 Par 2 If the doubts are cast upon the principal object of the contract in such a way that it cannot be known what may have been the intention or will of the parties. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. When it contains words that have different significations Art 1375 Words which may have different significations shall be understood in that which is with the nature and object of the contract .Y. without the consent of the creditor is ineffective as to the creditor. y Against voidable contract: ineffectiveness is produced ipso jure y Void or inexistent contract: can be made completely effective by the consent of the person as to whom it is effective or by the cessation of the impediment which prevents its complete ineffectiveness (1) assignment of the lease by the lessee without the consent of the lessor is ineffective only as regards the lessor. Rules of Court (now Secs. (2) transfer of a debt by the debtor to another. (3) the payment by a debtor to his creditor after the credit has been garnished or attached by a third person is ineffective to the latter DEFECTIVE CONTRACTS Karichi E. a. the doubt shall be settled in favor of the greatest reciprocity of interests . When it is absolutely impossible to settle doubts by the rules above Art 1378 Par 1 When it is absolutely impossible to settle doubts by the rules established in the preceding articles. the least transmission of rights and interests shall prevail. interpretation of documents) In between VALID and DEFECTIVE contracts is RELATIVELY INEFFECTIVE ineffectively only with respect to certain parties. When it contains ambiguities and omission of stipulations Art 1376 The usage or custom of the place shall be borne in mind in the interpretation of the ambiguities of a contract. When it contains stipulations that admit of several meanings Art 1373 If some stipulation of any contract should admit of several meanings. If the contract is onerous . Labitag [2 Page 89 of 110 Art 1371 In order to judge the intention of the contracting parties. Those who become subrogated. y Sir Labitag: thin band of contracts 2. A. as if it had never been executed or entered into Chapter VI. suffer lesion by more than ¼ of the value of things object y Same principle in relation to contracts by guardians 3. Things under litigation . cannot be deprived of property. Claims were acknowledged by the debtor after alienation. mortgage and other encumbrance AND not approved by court. Santos | UP Law B2012 . because if sale.n dSemester. no power to dispose without prior approval of court. Debtor has made subsequent contract. giving advantage to a 3 rd person (last resort) 3. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. 4. Rescissible Contracts Kinds of Rescissible Contracts Art 1381 The following are rescissible contracts: 1. in the rights of a creditor whose credits were prior to the alienation y Even secured creditors are entitled to AP y Conveyance was intentionally fraudulent which may be established by the presumption in Art 1387 y TEST OF FRAUD: Whether the conveyance was a bona fide transaction or a trick and contrivance to defeat creditors or whether it conserves to the debtor a special right. y GENERAL RULE: Credit is prior to the alienation y EXCEPTION: Credit is after alienation but entitled to accion pauliana because of some prior right 1. UNLESS RATIFIED in the manner PROVIDED BY LAW VOID AND NON-EXISTENT (contrato inexistente) contract which is an ABSOLUTE NULLITY and produces NO EFFECT. 3 rd person who received the property is an accomplice in the fraud y Credit must be existing at the time of the fraudulent alienation. Does it prejudice the right of creditors?? y Good consideration: creditor is not prejudiced becomes the property was merely replaced or substituted y Badges of fraud applicable 4. without knowledge and approval of litigant or of competent judicial authority y To secure the possible effectivity of a claim y Transferee of property in good faith who acquires property for valuable consideration. but origin of which antedated the alienation 2. But at the time of accion pauliana. 5. Only includes those which are ordinary course of management of estate of the ward. In fraud of creditors who cannot collect claims due them y Requisites of Accion Pauliana 1. Plaintiff asking for rescission (subsidiary action) has a credit prior to the alienation rd person 2. without knowledge of the litigation or claim of the plaintiff. the credit must already be due because it presupposes a judgment and unsatisfied execution which cannot exist when the debt is not yet demandable at the time the rescissory action is brought. Entered into by guardians whenever the wards suffer lesion by more than ¼ of value of things object y Guardian: authorized only to manage ward s property. it becomes unenforceable. Specially declared by law to be subject of rescission Characteristics of Rescissible Contracts Karichi E. Labitag [2 Page 90 of 110 1. but which contract is VALID until JUDICIALLY set aside UNENFORCEABLE contract that for some reason CANNOT BE ENFORCED. 3. Creditor has no other remedy but to rescind the debtor s contract to the 3 4. after the alienation. Act being impugned is fraudulent 5. 2. although not yet due. Agreed upon in representation of absentee . either because of WANT OF CAPACITY or because it is VITIATED .Y. founded on good consideration or is made with bona fide intent. RESCISSIBLE contract that has caused a particular damage to one of the parties or to a third person and which for EQUITABLE REASONS may be set aside even if valid VOIDABLE OR ANNULLABLE (contrato nulo) contract in which CONSENT of one of the parties is defective. reciprocal applicable to Even when contract is fully fulfilled Character Principal Remedy Secondary/Subsidiary Case: y Universal Food Corporation v CA MUTUAL DISSENT not the same with rescission. obligation) mainly econo mic injury or lesions Scope of judicial Court determines sufficiency of reason to justify Sufficiency of reason does not affect right to ask for control extension of time to perform obligatio n (whether slight rescission (cannot be refused if all the requisites are or casual breach) satisfied) Kind of obli Only to reciprocal Unilateral. 2008-2009] OBLIGATIONS & CONTRACTS | Prof.n dSemester. by means of the restoration of things to their condition at the moment prior to the celebration of said contract. even if initially valid. In order for rescission to take place. are also rescissible. They can be convalidated only by prescription and not by ratification RESCISSION Art 1380 Contracts validly agreed upon may be rescinded in the cases established by law. even if this should be valid. Presuppose contracts validly entered into and existing Rescission v. Art 1098 Partition. The contract is rescissible Art 1381 Kinds of rescissible contracts Art 1382 Payments made in a state of insolvency for obligations to whose fulfillment the debtor could not be compelled at the time (has not yet matured) they were effected. They are valid before rescission 3. not collaterally 4.g. Santos | UP Law B2012 . to secure the reparation of damages caused to them by a contract. or by a third person who is injured or defrauded 5. Relief for the protection of one of the contracting parties AND third persons from all injury and damages the contract may cause OR protect some incompatible and preferent right created by the contract Implies a contract which. Their defect consist in injury or damage either to one of the contracting parties or to third persons LESION: injury which one of the parties suffers by virtue of contract that is disadvantageous to him. A. 2.Y. They can be attacked only either by a contracting party. must be known or could have been known at the birth of contract and not due to subsequent thereto or unknown to the parties E. Labitag [2 Page 91 of 110 1. Annulment: the latter there is a defect which vitiates/invalidates the contract 2. Definition Remedy granted by law to the contracting parties and even to third persons. They can be attacked directly only. Mutual restitution when declared proper Who may Only by a party to the contract Party to the contract suffering lesion demand Third parties prejudiced by the contract Grounds Non-performance (implied tacit condition in reciprocal Various reasons of equity provided by the grounds. produces a lesion or pecuniary damage to someone Set asides the act or contract for justifiable reasons of equity Grounds for rescission can only be for legal cause Voidable contracts may also be rescinded Sir Labitag: Rescissible contracts are in between valid and void Rescission Art 1380 Distinguished from Resolution Art 1191 Art 1191 Resolution Art 1380 Rescission Similarities 1. the requisites must first be satisfied: Requisites for Rescission 1. The party asking for rescission has no other legal means to obtain reparation Karichi E. judicial and extra-judicial may be rescinded on account of lesion Art 1539 Sale of real estate of inferior thing Art 1542 Sale of real estate made for a lump sum 2. because mutual dissent is tantamount to a simple creation of new contract for the dissolution of the previous one. o GRATUITOUS _ Good faith does not protect him because he gave nothing. and the price with its interest 4. if not possible to return. y Right of transferee to retain alienation: Nature of transfer o ONEROUS _ Good faith no rescission _ Bad faith rescissible because of his complicity in the fraud not entitled for reimbursement because in pari delicto. it can be carried out only when he who demands rescission can return whatever he may be obliged to restore. o Period commences on the termination of the ward s incapacity or absentee s domicile is known Effect of Rescission If in fraud of the creditors: Property alienated reverts to the patrimony of the debtor and becomes liable to creditor who sought rescission. The object of the contract has not passed legally to the possession of a third person acting in good faith Art 1385 consequently. With respect to third persons who acquired the thing in good faith y Transferee of property in good faith who acquires property for valuable consideration. He is able to return whatever he may be obliged to restore if rescission is granted Art 1385 Rescission creates the obligation to return the things which were the object of the contract. indemnity for damages may be demanded from the person causing the loss. without knowledge of the litigation or claim of the plaintiff. y Art 1385 Par 3 In this case. Heirs of creditor injured 3. consequently. A. Karichi E. 5. under its original liability as a guaranty of the debtor s obligation Art 1385 Rescission creates the obligation to return the things which were the object of the contract together with their fruits. cannot be deprived of property. though not required to restore the fruits _ Bad faith rescissible because of his complicity in the fraud. the period of four years shall not begin until the termination of the former s incapacity or until the domicile of the latter is known. . For persons under guardianship and for absentees. Santos | UP Law B2012 . The action for rescission is brought within the prescriptive period of four years Art 1389 The action to claim rescission must be commenced within four years. rescissible. Art 1385 Par 3 Neither shall rescission take place when the things which are the object of the contract are legally in the possession of third persons who did not act in bad faith . together with their fruits. no rescission Presumptions of Fraud Art 1387 All contracts by virtue of which the debtor alienates property by gratuitous title are presumed to have been entered into in fraud of creditors .Y. indemnify the plaintiff. 3. Labitag [2 Page 92 of 110 Art 1383 The action for rescission is subsidiary .n dSemester. alienation is maintained even if transferee is in bad faith y Benefits only the plaintiff creditor. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Creditors of creditor injured (by virtue of accion subrogatoria) Extent of Rescission Art 1384 Rescission shall be only to the extent necessary to cover the damages caused. y Art 1385 Par 2 Neither shall rescission take place when the things which are the object of the contract are legally in the possession of third persons who did not act in bad faith . and the price with its interest. it cannot be instituted except when the party suffering damage has no other legal means to obtain reparation for the same. if not possible to return. not everyone y BUT if transferee is willing to pay. y As to the excess. Creditor injured 2. when the donor did not reserve sufficient property to pay all debts contracted before the donation. indemnify the plaintiff Who may bring action for rescission 1. it can be carried out only when he who demands rescission can return whatever he may be obliged to restore. Vitiated consent Characteristics of Voidable/Annullable Contracts 1.n dSemester. Voidable or Annullable Contract s Kinds of Voidable/Annullable Contracts Art 1390 Although no damage to contracting parties: 1.e. the design to defraud creditors may be proved in any other manner recognized by the law of evidence . Evidence of insolvency or large indebtedness 5.Y. Rebuttal by evidence that conveyance was made: o In good faith o For a sufficient cause Effect of Fraud: Does not necessarily make the alienation rescissible. A. In addition to these presumptions. Transfer is between father and son when some of above is present 7. They are susceptible of convalidation by ratification or by prescription ANNULMENT Annulment distinguished from Rescission NULLITY (Voidable) RESCISSION (Rescissible) Declares inefficiency which contract already carries in itself Merely pro duces inefficiency. They are binding until they are annulled by a competent court 3. pecuniary damages or rd perso ns) prejudice to one of the contracting parties or 3 Requires act of ratification to be cured Needs no ratification to be effective Based on a vice of the contract which invalidates it Compatible with the perfect validity of the contract Annulment is a sanction based on law Rescission is a remedy based on equity Demanded only by the parties to the contract Demanded even by third parties affected by it Public interest predominates Private interest predominates Grounds for Annulment Art 1390 1. Chapt er VII. Want of capacity 2. Sale on credit by insolvent debtor 4. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Fictitious/insufficient consideration 2. whenever. and so on successively . Labitag [2 Page 93 of 110 Alienations by onerous title are also presumed fraudulent when made by persons against whom some judgment has been issued . due to any cause. The decision or attachment need not refer to the property alienated. the first acquirer shall be liable first. It is only one of the requisites for accion pauliana. Incapacity to consent Karichi E. which did not exist essentially (intrinsic defect) in the contract (external defect i. Conveyance is after suit is filed and while it is pending 3. Their defect consists in the vitiation of consent of one of the contracting parties 2. Failure of vendee to take exclusive possession of the property Cases: y Oria v McMicking y Siguan v Lim y Suntay v CA supra Liability for acquiring in bad faith the things alienated in fraud of creditors Art 1388 Whoever acquires in bad faith the things alienated in fraud of creditors. and need not have been obtained by the party seeking the rescission. If there are two or more alienations. Santos | UP Law B2012 . it should be impossible for him to return them. Transfer of All or nearly all of debtor s property 6. Can be overruled by a transferee in good faith and for valuable consideration Badges of Fraud (indicia of fraud) rules by which fraudulent character of transaction may be determined 1. shall indemnify the latter for damages suffered by them on account of the alienation . he may ask for annulment e. MAY NOT: 1. MAY : All who are obliged principally or subsidiarily Art 1395: action does not require conformity of the other party who has no right to bring action for annulment Requisites: a. pay value if cannot return (both plaintiff and defendant) 1. want is only a ground for annulment 2. BUT PLAINTIFF WILLING TO PAY: Apply Art 1400. undue influence. Vices of consent: violence. the presumption is there is no benefit/profit to the incapacitated person If still in the patrimony at the time incapacity ceases. in the absence of such proof. 2. but NOT to third persons Effects of Annulment cleanses the contract from all its defect from the moment it was constituted (retroactive effect). If he asks for annulment. When one of the parties is incapacitated Art 1399 not obliged to make any restitution EXCEPT insofar as he has been benefited by the price/thing received Benefit not necessarily a material and permanent increase in fortune Proof of benefit incumbent upon the defendant. b. If he squanders.g. But when there is loss or suffered damages. injured party may be entitled to recover indemnity for damages. Parties who exerted intimidation.n dSemester.Y. even if at the time of the loss the plaintiff is still a minor or insane (Art 1401) y LOSS THROUGH FORTUITOUS EVENT. the other cannot be compelled to return y LOSS THROUGH PLAINTIFF S (party entitled to bring action) FAULT or FRAUD: Action is ex tinguished. Interest in the contract there must be legal capacity by being bound to the contract either principally or subsidiarily b. Labitag [2 Page 94 of 110 Not a requisite sine qua non of the contract. Isabela Sawmill) Case: y Singsong v Isabela Sawmill Prescription of Action for Annulment after prescription. intimidation. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. violence or undue influence: from the time consensual defect ceases 2. guarantors and sureties (Singsong v. UNLESS he can prove that the contract prejudiced his rights with respect to one of the contracting parties. When the thing is lost through the fault of the party obliged to return the same (i. Capable parties cannot allege the incapacity of those with whom they contracted 2. deemed to have been benefited. Incapacity: from the time guardianship ceases * Extinctive prescription applies not only to action for annulment.e. defendant) Art 1400 return the fruits received AND the value of thing at the time of loss. A. Third person who is a stranger to the contract. Art 1402 as long as one does not restore what he is bound to return. he must return it to the other party. services rendered in contracts of service ELIMINATES AWARD FOR DAMAGES. but also to the defense of nullity * Applies to the parties of to the contract. Victim and not the party responsible for the defect he who comes to the court must come with clean hands (so not applicable to the successor in interest of one who has contracted with a minor) B. Intimidation. it is ratification. mistake or fraud Who may and may not institute an Action for Annulment Art 1397 A. Mistake or fraud: from the time of discovery of the same 3. EXCEPT in cases provided by law (principle of unjust enrichment): compensation.Within 4 years Period shall begin: 1. together with fruits and the price with interest. Santos | UP Law B2012 . with interest from same date LOSS THROUGH FORTUITOUS EVENT: pay the value of the thing lost but not fruits and interests Karichi E. defendant should return but not including the interest because loss not due to his fault. violence or undue influence or employed fraud or caused mistake 3. contract can no longer be set aside Art 1391 . but does not prejudice rights of 3 rd persons acquire before the ratification Art 1396 a. MUTUAL RESTITUTION Art 1398 Restore to each other things which have been the subject matter of the contract. y LOSS OF FRUITS AND ACCESSIONS: Apply Art 1400. A.Right to ratify is transmitted to the heirs of the party entitled to such right. Bell & Co y Velarde v CA supra Extinguishment of the Action a. Ratification is made with the knowledge of the cause for nullity c. Art 1401 When the thing is lost through the fault of the person who has the right to file the action LOSS NOT THROUGH THE FAULT. Art 1396 The contract is cleansed retroactively from all its defects from the time it was constituted EXCEPTION: Right of 3rd persons prior to ratification Case: y Uy Soo Lim v Tan Unchuan Chapter VIII. e. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. consent of one party is defective) b.e.g. Contract is voidable/annullable (i. Do not comply with Statute of Frauds. Unenforceable Contracts Characteristics of Unenforceable Contracts 1.n dSemester. which are agreements unenforceable unless in written memorandum and subscribed by the party charged Karichi E.g. At the time of the ratification. the defendant cannot be obliged to make restitution to the plaintiff because of Art 1402 (cannot compelled to return if the other party does not return) Cannot extinguish action for annulment by any event not imputable to the fault or fraud of the plaintiff RATIFICATION Requisites of Ratification a.During the existence of incapacity . Art 1393 Express or tacit: execute an act which necessarily implies an intention to waive his rights E. They are susceptible of ratification 3. Hence. They cannot be enforced by a proper action in court 2. of EXPRESS: any oral or written manifestation of the person entitled to ask for annulment that he agrees to be bound by the contract or that he will not seek its annulment E. Entered into in the name of another person by one who has no authority or no legal representation OR acted beyond his powers 2. They cannot be assailed by third persons Art 1408 Unenforceable distinguished from Rescissible and Annullable UNENFORCEABLE RESCISSIBLE AND ANNULLABLE Produces NO legal effect unless ratified by competent court Produce legal effects unless set aside by competent court Kinds of Unenforceable Contracts 1. Labitag [2 Page 95 of 110 Cases: y Cadwallader & Co v Smith.Y. Art 1392 Action to annul is extinguished b. fortuitous event: not extinguished because extinguishment limited only to the loss by fault of plaintiff. of IMPLIED: silence or acquiescence acts showing approval or adoption of the contract acceptance and retention of benefits flowing therefrom b. Unjust enrichment if the loss is returned for the defendant to bear. Effects of Ratification a. the cause of nullity has already ceased to exist Forms of Ratification a.g. Art 1394 By the parties themselves or by the guardian in behalf of an incapacitated party . Art 1392 By ratification Confirmation/ratification: cures a defect of nullity Acknowledgment: remedies deficiency of proof b. Santos | UP Law B2012 . However. Merely regulates the formalities of the contract necessary to render it enforceable.Does not attempt to make contracts invalid if not executed in writing. representation without authority or legal representation makes the contract unenforceable) and principles of Agency in Title X of this Book .Y. (2) Violation of the contract y APPLICABLE TO: Executory and not to complete or executed contracts intention of the parties become apparent by their execution. Failure to object to the presentation of oral/parole evidence to prove the same 2. priced > P500 unless buyer accept and receive part of such goods and chattels or the evidences or some of them or pay at the time some part of the purchase money.Principal aims: (1) prevent commission of injustice due to faulty memory. Labitag [2 Page 96 of 110 a. Names of the parties 2. UNLESS principal ratifies it which cures the unauthorized contract. chattels or things in action . EXCEPTION: sale is by auction and entry is made by auctioneer in his sales book (because it constitutes sufficient memorandum) e. Santos | UP Law B2012 . Representation to the credit of a 3 rd person 3. then not within SoF. Date and place of the making of the agreement 5. partial performance must also be proven. y Exclusive list of agreements/contracts enumerated. Description of the subject matter sufficient to render it capable of identification 4. Sale of goods. Agreement made in consideration of marriage other than mutual promise to marry not limited to marrying parties but also to promises by a third person to one of the parties contemplating the marriage d. Terms and conditions of the agreement 3.Agent who binds his principal without authority to do so is liable to 3 persons. . A. Not to be performed within 1 year from the making If no time is fixed and nothing to show that it cannot be performed within a year.Provides for the manner which contracts under it shall be proved . Signature of the party assuming the obligation Cases: y PNB v Philippine Vegetable Oil Co y Limketkai Sons Milling Inc v CA y Swedish Match v CA How to ratify contracts under Statute of Frauds? Art 1405 1. rd . default or miscarriage of another Default or Miscarriage include liability for tort and are not to be restricted to defaults and miscarriages arising out of contracts. Special promise to answer for the debt. (2) discouraging intentional misrepresentations WRITTEN MEMORANDUM OR NOTE evidence of the agreement and is used to show the intention of the parties Minimum requirement for written memorandum: 1. Acceptance of benefits under them SoF cannot be invoked when the contract has been partly executed Case: Karichi E. Must be collateral only and not primarily liable for the debt c. Both parties are incapable of giving consent to contract Art 1403 Par 1 : Unauthorized contracts Governing rules in Unauthorized Contracts: Art 1404 Governed by Art 1317 (no one may contract in the name of the other without being authorized or unless he has by law a right to represent him. Partial performance also takes it out of SOF b. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Art 1403 Par 2: Contracts covered by the Statute of Frauds Statute of Frauds: descriptive of statutes which requires certain classes of contracts to be in writing.n dSemester. Rule of exclusion rd y A personal defense (hence cannot be raised by 3 persons) and the same may be waived y Does not determine credibility or weight of the evidence. Leasing for period longer than one year OR sale of real property or of an interest therein f. by requiring certain enumerated contracts and transactions to be evidenced by a writing signed by the party to be charged. merely concerned with the admissibility thereof Purpose of Statute: Prevent (and not to encourage it) fraud and perjury in the enforcement of obligations depending for their evidence upon the unassisted memory of witnesses.Does not having binding effect on the principal. only makes ineffective the action for specific performance . y NOT APPLICABLE TO: (1)Action for specific performance. BUT consent is law or is declared void by statute vitiated No contract. o The non-ratifying party may: enforce the contract OR ask for the annulment b. judgment of nullity is merely declaratory 3. even if Action for annulment prescribes in 4 years the cause of nullity ceased to exist Kinds of Void/Inexistent Contracts Art 1409 Contracts that are VOID Art 1409 Par 1 1. produces no effect Valid until set aside. either to one of the parties or to a 3 party Matter of law and public interest Based on equity and more a matter of private interest No legal effects even if no action is taken to set it aside No action. nullity can be set up as defense Void/inexistent contracts distinguished from other defective contracts VOID RESCISSIBLE rd Defect is inherent in the contract itself Defect is in their effects.ndSemester. or public policy Karichi E. validity may only be assailed directly. Labitag [2 Page 97 of 110 y Carbonell v Poncio Right of the parties when a contract is ENFORCEABLE BUT a public document is NECESSARY for its registration Art 1406 may avail of their rights under Art 1357 (parties may compel each other to observe the necessary form once the contract has been perfected) Art 1403 Par 3: Contracts executed by parties who are both incapable of giving consent to a contract Art 1407 a. but only appearance of one. Cannot be confirmed or validated (by prescription OR ratification). neither can the right to set up the defense of illegality be waived Art 1409 ACCION REIVINDICATORIA any person may invoke the inexistence of the contract whenever juridical effects founded thereon are asserted against him Action to Declare Nullity . cannot be enforced unless properly ratified VOID VOIDABLE One of those essential requisites is wanting. Void or Inexist ent Contracts Characteristics of Void/Inexistent Contracts 1. Effect of ratification by the parent or guardian of one of the parties: (express or implied) o Converts the contract into a voidable contract. permanent. object or purpose is contrary to law. Santos | UP Law B2012 . Void from the beginning 2. public order.Y.necessary because nobody can take the law into his own hands . good customs. Those whose cause. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. but if one party brings action to enforce it. either in fact or in Essential requisites for validity is present. A. at the option of the party who has not ratified. morals. Effect of ratification by the parents or guardians of both parties: validated from the inception Chapter IX. Produces no effect whatsoever nullity exist ipso jure. however.if the void contract is still executory . remains valid and produces all its effects Action to declare nullity of void contracts never prescribes Action to rescind prescribes in 4 years VOID UNENFORCEABLE Cannot be the basis of actions to enforce compliance Can never be ratified and become enforceable Can be ratified and thereafter enforced There is no contract at all There is a contract which. never even if not set aside by direct action (collateral attack allowed) by a 3 r d person Not susceptible of ratification May be rendered perfectly valid by ratification Action to declare nullity does not prescribe. no party need to bring an action. immoral or contrary to good conscience. Labitag [2 Page 98 of 110 a. BOTH parties at fault _ Neither party may recover what he has given by virtue of the contract _ Neither party may demand the performance of the other s undertaking 2. Art 1412 When the act is unlawful but does not criminal offense IN PARI DELICTO RULE 1. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. BOTH are in pari delicto _ No action against each other _ BOTH will be prosecuted _ RPC provision relative to the disposal of effects/instruments of a crime shall apply 2.Y. if the public interest will thus be subserved. improper. Art 1414 When the PURPOSE is illegal and money is paid or property delivered therefore maybe repudiated by one of the parties before the purpose has been accomplished OR before any damage has been caused to a 3 r d person . OR to contracts that are null and void ab initio. but merely prohibited y Prohibition is designed for the protection of the plaintiff y Plaintiff may recover what he paid or delivered if public policy is enhanced y ILLEGAL PER SE one that by universally recognized standards is inherently or by its very nature bad. Cases: y PBC v Lui She y Frenzel v Catito OTHER SPECIFIC EXCEPTIONS c. A. if interest of justice so demands Case: y Liguez v CA y Relloza v Gaw Cheen Hun Karichi E.ndSemester. d. ONLY ONE is guilty _ INNOCENT PARTY may claim what he has given _ INNOCENT PARTY not bound to comply with his promise Case: y Urada v Mapalad b. Art 1415 When the CONTRACT is illegal and one of the parties is INCAPABLE of giving consent courts may allow recovery of money/property delivered by the incapacitated person. Fictitious or simulated contracts don t have cause. Santos | UP Law B2012 . ONLY ONE is guilty _ INNOCENT PARTY may demand the return of what he has given without obligation to comply with his promise _ PARTY AT FAULT cannot recover what he has given by reason of the contract _ PARTY AT FAULT cannot ask for the fulfillment of what has been promised to him Not applicable to fictitious contracts because they refer to contracts with an illegal cause or subject-matter (criminal offense OR only illegal). Art 1411 When the act constitutes a criminal offense (illegality of cause or object) IN PARI DELICTO RULE 1. Case: y Modina v CA EXCEPTIONS TO THE IN PARI DELICTO RULE General Statement of the Exception (Art 1416): Agreement is not illegal per se. Courts may allow the party repudiating the contract to recover the money or property. Karichi E.Y. Art 1410 Does not prescribe. Those expressly prohibited are declared void by law Contracts that are INEXISTENT Art 1409 Par 2 1. Nature of contract requires indivisibility e. See Table of Defective Contracts in the next page. contract of compromise 2. However. Labitag [2 Page 99 of 110 e. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Art 1419 When a laborer agrees to accept a lower wage than that set by law entitled to recover deficiency h. i. Divisibility will only be followed when the nullity affects only the secondary or accessory obligations. Those which contemplate an impossible service 4. contract is considered as divisible or separable. enforce latter y In case of doubt. Intention of the parties is that the contract be entire e. Those where the intention of the parties relative to the principal object of the contract cannot be ascertained 5. Art 1418 When by virtue of contract a laborer undertakes to work longer than the maximum number of hours of work fixed by law worked may demand additional compensation for service rendered beyond the limit g.ndSemester. Art 1421 Is NOT available to 3 rd persons whose interest is not directly affected * Ratification may take the form of a new contract. in which case its validity shall be determined only by the circumstances at the time of the execution of the new contract. defect is permanent and incurable 2. Those whose cause or object did not exist at the time of the transaction Art 1409 Art 1409 Par 3 Right to set up defense of illegality cannot be waived The action or defense for the declaration of the inexistence of a contract 1. if what is void be the essential part.g. y EXCEPTIONS: 1. Art 1420 When the contract is divisible if illegal terms can be separated from legal ones. Those whose object is outside the commerce of man 3.g. Art 1422 When the contract is the DIRECT RESULT of a previous illegal contract also void and inexistent Art 1409 Par 4 Art 1409 Par 5 Art 1409 Par 6 Art 1409 Par 7 2. Santos | UP Law B2012 . Those which are absolutely simulated or fictitious Art 1345 Simulation of contracts may be ABSOLUTE (parties do not intend to be bound at all) or RELATIVE (parties conceal their true agreement) Art 1346 A bsolute or Fictitious: void 2. Art 1417 When the amount paid exceeds the maximum fixed by law any person paying in ex cess of the maximum price may recover such excess f. the same does not retroact to the constitution of the first contract. void the entire contract. A. plaintiff cannot return what must be restored c. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. plaintiff has other legal means to obtain reparation (subsidiary) b. plaintiff cannot VALID return what must be until rescinded By party litigant restored c. i.owner . Art 1098 Partition VALID until rescinded YES but only through DIRECT action for rescission No rescission if: a. A. object in the hands of 3 rd persons in good faith VALID until rescinded By plaintiff-creditor By heirs of creditor BY credito rs of creditors injured (accion By other subrogatoria) third parties prejudiced by the contract Within 4 years from kno wledge of fraudulent contract YES By prescription By credito Within 4 years from kno wledge of fraudulent contract YES By prescription By party l . Contract approved by court (Art 1386) Within 4 years from gaining (minor) or regaining (insane) capacity YES By ratification (Confirmation by the ward) By ward Within 4 years from kno wledge of domicile of absentee YES By prescription By absent Contracts which refer to things in litigation without the knowledge and approval of litigants or competent judicial authority All other contracts declared by law to be subject of rescission E.g. contracts entered into in fraud of creditors (Accion Pauliana) EFFECT ON CONTRACT ASSAILABLE? HOW? WHO CAN ASSAIL? By ward Or by guardian ad litem of ward during incapacity of ward in action against original guardian WHEN TO ASSAIL? CURABLE? HOW? WHO C RESCISSIBLE (Arts 1381 1389) Economic prejudice or damage to: .e. object in the hands VALID of 3 rd persons in good until rescinded By absentee faith d. Labitag DEFECTIVE CONTRACTS AS TO NATURE OF DEFECT Contracts of guardians (acts of administration) when wards they represent suffer lesion of more than 25% of the value of thing Contracts in representation of absentees when latter suffers lesion of more than 25% of value of thing Contracts entered into by debtor who is a state of insolvency.litigant Can generally be ASSAILED and CURED by: Injured Party EFFECTS: Mutual restitution YES but only through DIRECT action for rescission VALID No rescission if: until rescinded a.3 r dperson . A.n dSemester. plaintiff has other legal means to obtain reparation (subsidiary) b. Labitag [2 Page 100 of 110 DEFECTIVE CONTRACTS Professor E.Y. age . motion to dismiss complaint on the ground that contract is unenforceable 2. guarantors and sureties) Incapacitated party. violence. objection to presentation of oral evidence to prove contract By owner of property At any time one party attempts to enforce contract against the other through a court action By ratification Person in the contra entered in By acknowledgement By performance of oral contract By other party By his privies (heirs.violence and intimidation (duress) .n dSemester.Implied (silence or acquiescence. Action for annulment By parties By guardi of an inca party dur of incapac Within 4 years from: . Not by direct action but by DEFENSE of unenforceability of contract through motion to dismiss complaint on the ground that contract is unenforceable YES. misrepresentation VALID until annulled by co urt action YES.fraud. Labitag [2 Page 101 of 110 DEFECTIVE CONTRACTS AS TO NATURE OF DEFECT Want of capacity .mistake or error .undue influence . 2008-2009] OBLIGATIONS & CONTRACTS | Prof. acceptance and retention of benefits) VOIDABLE (Arts 1390 1402) Vitiated consent EFFECT: Cleanses defect of contract Does not prejudice right of 3P prior to ratification Mutual restitution Consent is vitiated by: . not the party with capacity Victim.cessation o f intimidation.discovery of mistake or fraud 2 By prescription UNENFORCEABLE (Arts 1403 1408) Contract entered into name of another witho ut authority o r in excess of authority VALID but cannot be ENFORCED by a proper action in court YES.Y.insanity EFFECT ON CONTRACT ASSAILABLE? HOW? WHO CAN ASSAIL? All who are obliged principally or subsidiarily (i. Both through direct and collateral attacks. representatives and assigns) At any time one party attempts to enforce contract against the other through a court action By failure to object seasonably to presentation of oral evidence By acceptance of benefits under the contract By party a the contra enforced Contracts covered by Statute of Frauds and not complying with requirement o f a written memo VALID but cannot be ENFORCED by a proper action in court . undue influence (consensual defect) .Express . Not by direct action but by DEFENSE of unenforceability of contract either through: 1. acts showing approval or adoption of contract. A.e. not the party who cause the defect WHEN TO ASSAIL? CURABLE? HOW? WHO C Within 4 years from cessation of (re)gaining capacity YES By ratification By prescription YES 1 By ratification . Contemplate an impossible service e. morals.Y. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Where intention of parties re: principal object of contract cannot be ascertained (Art 1402 Pars 2 to 6) DOES NOT CREATE RIGHTS AND CANNOT IMPOSE OBLIGATION YES. public order or public policy (Art 1401. Those whose cause or object did not exist c.n dSemester. Object o utside the commerce of man d. A. Labitag [2 Page 102 of 110 YES. object or purpose o f contract contrary to law. Par 1) DOES NOT CREATE RIGHTS AND CANNOT IMPOSE OBLIGATION YES. By an action for declaration for nullity By defense of nullity By 3rd persons whose interest are directly affected (If in pari delicto. By an action for declaration for nullity By defense of nullity By party who se protection the prohibition of the law is designed By 3rd party whose interests are directly affected Imprescriptible Cannot be cured . representatives and assigns) By guardian At any time one party attempts to enforce contract against the other through a court action Both parties are legally incapacitated to act VALID but cannot be ENFORCED by a proper action in court By parent guardians parties By confirmation Both part (re)gainin act VOID or INEXISTENT (Arts 1409 1422) By innocent party Cause. good customs. neither has an action against each other) Imprescriptible Cannot be cured One or some of essential requisites of valid contract lacking in fact or in law a. By an action for declaration for nullity By defense of nullity By any of the contracting parties By 3rd persons whose interests are directly affected Imprescriptible Cannot be cured Contracts expressly prohibited by law (Art 1409 Par 7) DOES NOT CREATE RIGHTS AND CANNOT IMPOSE OBLIGATION YES. Absolutely simulated b. Not by direct action but by DEFENSE of unenforceability of contract through motion to dismiss complaint on the ground that contract is unenforceable By other party By his privies (heirs. ndSemester, A.Y. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Labitag [2 Page 103 of 110 Title III. NATURAL OBLIGATIONS Four types of obligations in juridical science reduced to two by jurisprudence 1. Moral obligations duties of conscience completely outside the field of law 2. Natural obligations duties not sanctioned by any action but have a relative judicial effect 3. Civil obligations juridical obligations that are in conformity with positive law but are contrary to juridical principles and susceptible of being annulled; enforceable by action 4. Mix ed obligations full juridical effect; falls under civil obligations Definition Art 1423 Not being based on positive law but on equity and natural law, do not grant a right of action to enforce their performance, but after voluntary fulfillment by the obligor, they authorize the retention of what has been delivered or rendered by reason thereof. y Midway between civil and the purely moral obligation. Obligation without a sanction, susceptible of voluntary performance, but not through compulsion by legal means. y Real obligation which law denies action, but which the debtor may perform voluntarily. y Patrimonial and presupposes a prestation. Requisites of Natural Obligation 1. Juridical tie between two persons. 2. Tie is not given effect by law but instead by the conscience of man distinguishes it from civil obligations. As distinguished from Civil Obligations NATURAL CIVIL As to enforceability Not by court actions, but by good conscience of debtor As to basis Equity and natural justice Positive law Court actio n or the coercive power of public authority As distinguished from Moral Obligations NATURAL PURELY MORAL There is a juridical tie There is no juridical tie Performance by the debtor is a legal fulfillment of the obligation A true obligation with a legal tie between debtor and creditor Act is purely liberality Matter is entirely within the domain of morals Cases: y Villaroel Estrada y Fisher v Robb Conversion to Civil Obligation GENERAL RULE: Partial payment of a natural obligation does not make it civil; the part paid cannot be recovered but the payment of the balance cannot be enforced. applicable only to natural obligation because of prescription or lack of formalities (nullity due to form e.g. Art 1430) and NOT to natural obligation subject to ratification or confirmation. y Payment by mistake is not voluntary and may be recovered. Payment is voluntary when the debtor knew that the obligation is a natural one. One who pays a natural obligation, believing it to be civil, does not thereby recognize the natural obligation; and there being no civil obligation either, he can recover what he has paid. The debtor however has the burden of proving the mistake. 1. By novation 2. By confirmation or ratification Examples Art 1424 When the right to sue upon a civil obligation has lapsed by extinctive prescription, the obligor who voluntarily Karichi E. Santos | UP Law B2012 ndSemester, A.Y. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Labitag [2 Page 104 of 110 performs the contract cannot recover what he has delivered or the value of the service he has rendered. Art 1425 rd person pays a debt which the obligor is not When without the knowledge OR against the will of the debtor, a 3 legally bound to pay because the action thereon has prescribed, but the debtor later voluntarily reimburses the third peson the obligor cannot recover what he has paid. Art 1426 When a minor 18-21 entered into a contract without the consent of the parent or guardian, after the annulment of the contract, voluntarily returns the whole thing or price received, notwithstanding that he has not been benefited thereby, there is no right to demand the thing or price thus returned. When a minor 18-21 entered into a contract without the consent of the parent or guardian, voluntarily pays a sum of money or delivers a fungible thing in fulfillment of an obligation, there shall be no right to recover the same from the oblige who has spent or consumed it in good faith. - Not the voluntary payment that prevents reco very, but the consumption or spending of the thing or money in good faith. - This article creates an exception to the rule of mutual restitution. Minor would have been required to return whatever he received upon annulment of contract. - Good faith: belief that debtor has capacity to deliver the object of contract - Fungible thing: consumable - Non-consummable: debtor cannot recover if no longer in the po ssession of the creditor, because the right to recover presupposes existence of thing. When after an action to enforce a civil obligation has failed, the defendant voluntarily performs the obligation, he cannot demand the return of what he has delivered or the payment of the value of the service he has rendered. When a testate or intestate heir voluntarily pays a debt of a decedent exceeding the value of the property which he received by will or by the law of testacy from the estate of the deceased, the payment is valid and cannot be rescinded by the payer. When a will is declared void because it has not been executed in accordance with the fo rmalities required by law, but one of the intestate heirs, after the settlement of the debts of the deceased, pays a legacy in compliance with a clause in the defective will, the payment is effective and irrevocable. Art 1427 Art 1428 Art 1429 Art 1430 Karichi E. Santos | UP Law B2012 ndSemester, A.Y. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Labitag [2 Page 105 of 110 Title IV. ESTOPPEL Definition Art 1431 Admission or representation is rendered conclusive upon the person making it, and cannot be denied or disproved as against the person relying thereon. - Bar which precludes a person from denying or asserting anything to the contrary of that which in has, in contemplation of law, been established as the truth, either by the acts of judicial or legislative officers or by his own deed or representation, either express or implied. - Concludes the truth in order to prevent falsehood and fraud, and imposes silence on the party only when in conscience and honesty he should not be allowed to speak. - Origin is in equity and is therefore based on moral right and natural justice - Cannot be predicated on an illegal act EQUITABLE ESTOPPEL WAIVER May arise even when there is no intention on Voluntary and intentional abandonment or the part of the person estopped to relinquish relinquishment of a known right any existing right Frequently carries implication of fraud No implication of fraud Involves the conduct of both parties Involves the act or conduct of only one of the parties ESTOPPEL RATIFICATION Bound notwithstanding the fact that there was no such intention, because the other party will be prejudiced and defrauded by his conduct unless the law treats him as legally bound Bound because he intended to be Case: y Kalalo v Luz Kinds of Estoppel Art 1433: Estoppel may be in pais or by deed A. TECHNICAL ESTOPPEL 1. By record preclusion to deny the truth of matters set forth in a record, whether judicial or legislative, and also to deny the facts adjudicated by a court of competent jurisdiction i. E.g. conclusiveness of judgment (estoppel by judgment) on the parties to a case, which according to Sir is broader than res judicata 2. By deed bar which precludes on party to a deed and his privies from asserting as against the other party and his privies any right or title in derogation of the deed, or from denying the truth of any material facts asserted in it usually written documents B. EQUITABLE ESTOPPEL (estoppel in pais) because of something which he has done or omitted to do, a party is denied the right to plead or prove an otherwise important act y Essential elements of estoppel in pais in relation to the party sought to be estopped: 3. Knowledge, actual or constructive, of the real facts y Essential elements of estoppel in pais in relation to the party claiming the estoppel: 1. Lack of knowledge or of the means of knowledge of the truth as to the facts in question 2. Reliance, in good faith, upon the conduct or statements of the party to be estopped 3. Action or inaction based thereon of such character as to change the position or status of the party claiming the estoppel, to his injury, detriment or prejudice POSITIVE ESTOPPEL IN PAIS Karichi E. Santos | UP Law B2012 One who is silent when he ought to speak will not be heard to speak when he ought to be silent. b. Closely connected to ESTOPPEL BY ACQUIESCENCE: a person is prevented from maintaining a position inconsistent with one in which he has acquiesced. Justifiable reliance or irreparable detriment to the promise are requisite factors. for an unreasonable and unexplained length of time. if he received the sum for which a pledge has been constituted. one of them is misled by a person with respect to the ownership or real right over real estate. is not a mere question of time but principally a question of inequity or unfairness of permitting a right or claim to be enforced or asserted. Delay in asserting complainant s right after he had knowledge of the defendant s conduct and after he has had an opportunity to sue c. y Why? Mutuality is an essential element of an estoppel. Promissory estoppel An estoppel may arise from making of a promise. and if a refusal to enforce it would be virtually to sanction the perpetuation of fraud or would result in other injustice. y Requisites of laches: a. Party misled must have been unaware of the true facts 4. Conduct on part of the defendant. by virtue of Art 1432 which adopts principle of estoppel NEGATIVE ESTOPPEL IN PAIS 1. y Discretionary on the part of the court. Injury or prejudice to the defendant in the event relief is accorded to the complainant y Distinguished from prescription LACHES PRESCRIPTION Concerned with effect of delay Concerned with fact of delay Principally question of inequity of permitting a claim Matter of time Not based on statute but on equity Statutory Not based on fixed time Fixed time 2. It is not estopped by mistake or error on the part of its officials or agents. made by the other to a pledge who received the same in good faith and for value. could or should have been done earlier. an estoppel must bind both parties or neither is bound. discouragement of stale claims and laches. c. the latter is precluded from asserting his legal title or interest therein. the erroneous application and enforcement of the law by public officers does not prevent a subsequent correct application of the statute. Labitag [2 Page 106 of 110 1. Estoppel by laches failure or neglect. provided all these requisites are present: 1. y No estoppel against government. A. Fraudulent representation or wrongful concealment of facts known to the party estopped 2. A promise cannot be the basis of an estoppel if any other essential element is lacking. set up his own title to defeat the pledge of the property. Karichi E. Lack of knowledge or notice on the part of the defendant that the complainant would assert the right on which he bases his suit d. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Estoppel by acceptance of benefits (Art 1438 or estoppel from benefits) One who has allowed another to assume apparent ownership of personal property for the purpose of making any transfer of it. by exercising due diligence. Came from Anglo-American Law. Party precluded must intent that the other should act upon the facts as misrepresented 3.Y. giving rise to the situation complained of b. Mere innocent silence will not work an estoppel. even though without consideration. Estoppel by silence .ndSemester. Estoppel by representation or misrepresentation (Art 1437 or estoppel against owners) When a rd contract between 3 persons concerning immovable property. y Public policy requires for the peace of society. Party defrauded must have acted in accordance with the misrepresentation 2. there must also be some element of turpitude or negligence connected wit the silence by which another is misled to his injury. or one under whom he claims. cannot. to do that which. Persons bound Art 1439 Effective only as between the parties thereto or their successors in interest (privies in blood like heirs. 3. if it was intended that the promise should be relied upon and in fact it was relied upon. unlike statute of limitations. Santos | UP Law B2012 . and in estate like grantees). d. the former cannot subsequently set up his own title as against the buyer or grantee. Party defrauded must have acted in accordance with the misrepresentation One who has allowed another to assume apparent ownership of personal pro perty for the purpose of making any transfer of it. such title passes by operation of law to the buyer or grantee. if he received the sum for which a pledge has been constituted. as against the lessor or bailor. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. Labitag [2 Page 107 of 110 Case: y Manila Lodge No. one of them is misled by a person with respect to the ownership or real right over real estate. canno t. Party misled must have been unaware of the true facts 4. If a person in representatio n of another sells or alienates a thing. Art 1438 Estoppel from benefits Case: y Miguel v Catalino y Read the annotation on 32 SCRA 542 Karichi E. Art 1436 Tenant Art 1437 Estoppel against owner When a contract between 3 rd persons concerning immovable property. Santos | UP Law B2012 . made by the other to a pledge who received the same in good faith and for value. A lessee or a bailee is estopped from asserting title to the thing leased or received. the latter is precluded from asserting his legal title or interest therein. and later the seller or grantor acquires title thereto.ndSemester. Fraudulent representation or wrongful concealment of facts known to the party estopped 2.Y. Party precluded must intent that the other should act upon the facts as misrepresented 3. 761 Benevolent and Protective Order of the Elks v CA Cases where estoppels applies Art 1434 Subsequent acquisition of title Art 1435 When a person who is not the owner of a thing sells or alienates and delivers it. A. provided all these requisites are present: 1. set up his own title to defeat the pledge of the property. Sufficiently certain beneficiaries Karichi E. it may be proved by any EXCEPTION: competent evidence including parol evidence Requisites of Express Trust 1. The action (nature of a general demand for damages) can be maintained by cestui que trust or persons claiming under him or by creator of the trust only against the trustee. It involves the existence of equitahble duties imposed upon the holder of the title to the property to deal with it for the benefit of another 5. one in whom confidence is reposed as regards property for the benefit of another person is known as the trustee. Proof required for Express Trust Art 1443 No express trust concerning an immovable or any interest therein may be proved by parol evidence . A. It arises as a result of a manifestation of intention to create the relationship Governing rules in Trust Art 1442 Principles of the general law of trusts are transplanted to the Philippine soil Parties in a Trust Art 1440 A person who establishes a trust is called the trustor. y Cestui que trust: Not always necessary that should be named. y Disables the trustee from acquiring for his own benefit the property committed to his management or custody.Y. TRUSTOR Establishes a trust TRUSTEE One in whom confidence is reposed as regards property for the benefit of another person BENEFICIARY or cestui que trust Person for whose benefit the trust has been created y Liability of trustee who violates trust is personal. not one involving merely personal duties 4. Kinds of Trust Art 1441 Trusts are either express or implied. It is a relationship 2. EXPRESS TRUSTS can come into existence ONLY by the manifestation of an intention (manifested by conduct or by words) to create it by the one having legal and equitable dominion over the property made subject to it. A relationship with respect to property. Ascertainable trust res 4. IMPLIED trusts come into being by operation of law. A relationship of fiduciary character 3. Competent trustor 2. Characteristic of Trust 1. and the person for whose benefit the trust has been created is referred to as the beneficiary. Labitag [2 Page 108 of 110 Title V. the equitable ownership of the former entitling him to the performance of certain duties and the exercise of certain powers by the latter. at least while he does not openly repudiate the trust and make such repudiation known to the beneficiary.ndSemester. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. not for the validity but for the purposes of proof it is in the nature of a Statute of Fraud If property subject to trust is not real estate or an interest therein. Santos | UP Law B2012 . Writing necessary to prove it. TRUSTS Definition Trust is the legal relationship between one person having an EQUITABLE OWNERSHIP in property and another person OWNING THE LEGAL TITLE to such property. or even be in existence at the time the trust is created in his favor. Competent trustee 3. EXPRESS trusts are created by the intention of the trustor or of the parties. Case: y Salao v Salao 1. if the trust imposes no onerous condition upon the beneficiary. The duty to convey the property arises because it was acquired through fraud.ndSemester. Last part of the article (in loco parentis) 2. Why? To permit it to fail for this reason would be contrary to the intention of the trustor in creating a trust who is primarily interested in the disposition of the beneficial interest in the property. legitimate or illegitimate. or mistake or through breach of fiduciary duty or through the wrongful disposition of another s party. which will be made by the proper court UNLESS by the terms of the trust. a trust arises by operation of law in favor of the person Karichi E. it being disputably presumed that there is a gift in favor of the child. Implied trusts come into being by operation of law. IMPLIED TRUSTS come into ex istence either through implication of an intention to create a trust as a matter of law or through the imposition of the trust irrespective of and even contrary to any. the trust does not fail but a new trustee will be appointed. if there is no proof to the contrary. How to establish Implied Trusts Art 1441 Trusts are either express or implied . while the latter is the beneficiary. undue influence. Art 1449 Resulting Art 1450 Resulting . it being sufficient that a clearly intended. Where a trustee dies. E. he nevertheless is either to have no beneficial interest or only a part thereof. _ Sir Labitag: The trustee never intended to be a trustee. fraudulent transfers There is also an implied trust when a donation is made to a person but it appears that although the legal estate is transmitted to the done. The former is a trustee. CONSTRUCTIVE imposed where a person holding title to property is subject to an equitable duty to convey it to another on the ground that he would be unjustly enriched if he were permitted to retain it. Nevertheless.g. perhaps he intended to be the owner. other provision is made for the appointment of successor trustee. Labitag [2 Page 109 of 110 Form of an Express Trust Art 1444 No particular words are required for the creation of an express trust. However if the person to whom the title is conveyed is a child. and the matter of its administration is a subsidiary consideration. resigns. his acceptance shall be PRESUMED. and the legal estate is granted to one party but the price is paid by another for the purpose of having the beneficial interest of the property. Somebody else is the true beneficiary like an infant son If the price of a sale of property is loaned or paid by one person fo r the benefit of another and the co nveyance is made to lender or payor to secure the payment of the debt. such intention. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. did not comply with the proper formality b. RESULTING arises where a person makes or causes to be made a disposition of property under circumstances which raise an inference that he does not intend that the person taking or holding the property should have beneficial interest in the property _ Sir Labitag: effect of failure to create an express trust. of the one paying the price of the sale. a. trust is Want of Trustee Art 1445 No trust shall fail because the trustee appointed declines the designation.g. UNLESS the contrary should appear in the instrument constituting the trust. 2. The law imposed on him the obligation of the trustee because the real owner will be prejudiced (or will suffer irreparable damage) if no implied trust is created by law How to prove implied trust Art 1457 An implied trust may be Examples of implied trust Art 1448 Trust from payment Resulting There is an implied trust when property is sold. Express trusts are created by the intention of the trustor or of the parties. no trust is implied by law. Santos | UP Law B2012 proved by oral evidence . Actual contrary intention is proved e. Acceptance by beneficiary Art 1446 Acceptance by the beneficiary is necessary. A. duress. suffers any legal incapacity.Y. EXCEPTIONS: 1. E. Nakpil vs. there is an implied trust in favor of the person whose benefit is contemplated. If the fulfillment of the obligation is offered by the grantor when it becomes due. a trust is established by operatio n of law in favor of the person to whom the funds belo ng. he may demand reconveyance of the property to him. If property is acquired through mistake or fraud. A. guardian or other person holding a fiduciary relationship uses trust funds for the purchase of property and causes the conveyance to be made for him or to a third person. If two or more persons agree to purchase property and by common consent the legal title is taken in the name of one of them for the benefit of all. 2008-2009] OBLIGATIONS & CONTRACTS | Prof. or transfer it to another or the grantor.g. The latter may redeem the property and compel a conveyance thereof to him. considered a trustee of an implied trust for the benefit of the person from whom the property co mes. a trust is established by implication of law for the benefit of the true owner. Art 1452 Title in one co-owner Resulting Art 1453 Resulting Art 1454 Art 1455 Constructive in favor of the owner Art 1456 Cases: y Fabian v Fabian y Bueno v Reyes y Tamayo v Callejo Karichi E. the person obtaining it is. Santos | UP Law B2012 . a trust is created by force of law in favor of the others in proportion to the interest of each.Y. Labitag [2 Page 110 of 110 Art 1451 to who the money is loaned or for whom it is paid. When any trustee. Valdez in LegProf When land passes by succession to any person and he causes the legal title to be put in the name o f another. by force of law.ndSemester. If an absolute conveyance of property is made in order to secure the performance of an obligation of the grantor toward the grantee. When property is conveyed to a person in reliance upo n his declared intention to hold it for. a trust by virtue of law is established.
https://www.scribd.com/document/102003018/Obligations-and-Contracts-Kaichi-E-Santos
CC-MAIN-2017-13
refinedweb
54,997
56.55
A developer’s introduction to WebAssembly Are you ready to execute code faster than ever? Discover why WebAssembly is a very important part of the web platform of the future. In this tutorial by Flavio Copes, developers will learn how to use WebAssembly, how to compile their C programs, and how to call a WebAssembly function from JavaScript. WebAssembly is a very cool topic nowadays. WebAssembly is a new, low-level binary format for the web. It’s not a programming language you are going to write, but instead other higher level languages (at the moment C, Rust and C++) are going to be compiled to WebAssembly to have the opportunity to run in the browser. It’s designed to be fast, memory-safe, and open. You’ll never write code in WebAssembly (also called WASM); instead, WebAssembly is the low level format to which other languages are compiled to. It’s the second language ever to be understandable by Web Browsers, after the JavaScript introduction in the 90’s. WebAssembly is a standard developed by the W3C WebAssembly Working Group. Today all modern browsers (Chrome, Firefox, Safari, Edge, mobile browsers) and Node.js support it. Did I say Node.js? Yes, because WebAssembly was born in the browser, but Node already supports it since version 8 and you can build parts of a Node.js application in any language other than JavaScript. People that dislike JavaScript, or simply prefer writing in other languages, thanks to WebAssembly will now have the option to write parts of their applications for the Web in languages different than JavaScript. Be aware though: WebAssembly is not meant to replace JavaScript, but it’s a way to port programs written in other languages to the browser, to power parts of the application that are either better created in those languages, or pre-existing. JavaScript and WebAssembly code interoperate to provide great user experiences on the Web. It’s a win-win for the web, since we can use the flexibility and ease of use of JavaScript and complement it with the power and performance of WebAssembly. SEE ALSO: A developer’s introduction to GitHub Safety WebAssembly code runs in a sandboxed environment, with the same security policy that JavaScript has, and the browser will ensure same-origin and permissions policies. If you are interested in the subject I recommend to read Memory in WebAssembly and the Security docs of webassembly.org. Performance WebAssembly was designed for speed. Its main goal is to be really, really fast. It’s a compiled language, which means programs are going to be transformed to binaries before being executed. It can reach performance that can closely match natively compiled languages like C. Compared to JavaScript, which is a dynamic and interpreted programming language, speed cannot be compared. WebAssembly is always going to beat JavaScript performance, because when executing JavaScript the browser must interpret the instructions and perform any optimization it can on the fly. Who is using WebAssembly today? Is WebAssembly ready for use? Yes! Many companies are already using it to make their products better on the Web. A great example you probably already used is Figma, a design application which I also use to create some of the graphics I use in the day-to-day work. This application runs inside the browser, and it’s really fast. The app is built using React, but the main part of the app, the graphics editor, is a C++ application compiled to WebAssembly, rendered in a Canvas using WebGL. In early 2018 AutoCAD released its popular design product running inside a Web App, using WebAssembly to render its complex editor, which was built using C++ (and migrated from the desktop client codebase) The Web is not a limiting technology any more for those products that require a very performant piece to their core. SEE ALSO: A developer’s introduction to React How can you use WebAssembly? C and C++ applications can be ported to WebAssembly using Emscripten, a toolchain that can compile your code to two files: - a .wasmfile - a .jsfile where the .wasm file contains the actual WASM code, and the .js file contains the glue that will allow the JavaScript code to run the WASM. Emscripten will do a lot of work for you, like converting OpenGL calls to WebGL, will provide bindings for the DOM API and other browsers and device APIs, will provide filesystem utilities that you can use inside the browser, and much more. By default those things are not accessible in WebAssembly directly, so it’s a great help. Rust code is different, as it can be directly compiled to WebAssembly as its output target, and there’s an a tutorial available here.. What’s coming for WebAssembly in the future? How is it evolving? WebAssembly is now at version 1.0. It currently officially supports only 3 languages (C, Rust, C++) but many more are coming. Go, Java and C# cannot currently be (officially) compiled to WebAssembly because there is no support for garbage collection yet. When making any call to browser APIs using WebAssembly you currently need to interact with JavaScript first. There is work in progress to make WebAssembly a more first class citizen in the browser and make it able to call DOM, Web Workers or other browser APIs directly. Also, there is work in progress to be able to make JavaScript code being able to load WebAssembly modules, through the ES Modules specification. Installing Emscripten Install Emscripten by cloning the emsdk GitHub repo: git clone then dev cd emsdk Now, make sure you have an up to date version of Python installed. I had 2.7.10 and this caused a TLS error. I had to download the new one (2.7.15) from here, install it, and then run the Install Certificates.command program that comes with the installation. Then ./emsdk install latest let it download and install the packages, then run ./emsdk activate latest and add the paths to your shell by running: source ./emsdk_env.sh SEE ALSO: Create your first app with Vue.js Compile a C program to WebAssembly I am going to create a simple C program and I want it to execute inside the browser. This is a pretty standard “Hello World” program: #include <stdio.h> int main(int argc, char ** argv) { printf("Hello World\n"); } You could compile it using: gcc -o test test.c and running ./test would print “Hello World” to the console. Let’s compile this program using Emscripten to run it in the browser: emcc test.c -s WASM=1 -o test.html Emscripten gave us a html page that already wraps the WebAssembly program compiled, ready to run. You need to open it from a web server though, not from the local filesystem, so start a local web server, for example the http-server global npm package (install it using npm install -g http-server if you don’t have it installed already). Here it is: As you can see, the program ran and printed “Hello World” in the console. This was one way to run a program compiled to WebAssembly. Another option is to make a program expose a function you are going to call from JavaScript. SEE ALSO: JavaScript or WebAssembly: Is WASM the superhero JS needs? Call a WebAssembly function from JavaScript Let’s tweak the Hello World defined previously. Include the emscripten headers: #include <emscripten/emscripten.h> and define an hello function: int EMSCRIPTEN_KEEPALIVE hello(int argc, char ** argv) { printf("Hello!\n"); return 8; } EMSCRIPTEN_KEEPALIVE is needed to preserve the function from being automatically stripped if not called from main() or other code executed at startup (as the compiler would otherwise optimize the resulting compiled code and remove unused functions – but we’re going to call this dynamically from JS, and the compiler does now know this). This little function prints Hello! and returns the number 8. Now if we compile again using emcc: emcc test.c -s WASM=1 -o test.html -s "EXTRA_EXPORTED_RUNTIME_METHODS=['ccall', 'cwrap']" This time we added an EXTRA_EXPORTED_RUNTIME_METHODS flag to tell the compiler to leave the ccall and cwrap functions on the Module object, which we’ll use in JavaScript. Now we can fire up the Web Server again and once the page is open call Module.ccall('hello', 'number', null, null) in the console, and it will print “Hello!” and return 8: The 4 parameters that Module.ccall takes are the C function name, the return type, the types of the arguments (an array), and the arguments (also an array). If our function accepted 2 strings as parameters, for example, we would have called it like this: Module.ccall('hello', 'number', ['string', 'string'], ['hello', 'world']) The types we can use are null, string, number, array, boolean. We can also create a JavaScript wrapper for the hello function by using the Module.cwrap function, so that we can call the function as many times we want by using the JS counterpart: const hello = Module.cwrap('hello', number, null, null) Here’s the official docs for ccall and cwrap. This article was originally published on Flavio’s blog.
https://jaxenter.com/introduction-webassembly-152093.html
CC-MAIN-2022-27
refinedweb
1,529
63.59
Hi everyone, I'm new to C programming and I'm trying to write a program that can print text in columnar format with a maximum width. I've been trying with this but I get a seg fault. Am I going about this the right way? Any help would be really appreciated. Thanks, Cam PS I don't care if you say my code sucks, as long as you tell me how I can improve it :p #include "columnarText.h" #include <string.h> #include <stdio.h> void textPrint(const char *text, const int columnWidth){ int lineLength = 0; int count = 0; int stop = 0; int finish = 0; while(stop!=1){ char *currWord; int i=0; int k=count; while(strcmp(text[k]," ")!=0){ if(strcmp(text[k],"/0")==0){ finish = 1; break; } currWord[i]=text[k]; k++; i++; count=k; } currWord[i]="/0"; i=0; if((strlen(currWord)+lineLength)<column){ printf("%s",currWord); lineLength+=strlen(currWord); } else{ printf("/n"); printf("%s",currWord); lineLength = strlen(currWord); } if(finish==1){ stop=1; } } } int main(void) { char *s = "This is a test string to test my program with."; textPrint(s,10); return 0; }
https://www.daniweb.com/programming/software-development/threads/119136/text-program-help-needed
CC-MAIN-2018-30
refinedweb
190
66.54
Over the last several months, I have shown you all kinds of cool ways you can use OpenCV with C# to create some really cool applications. Today, at the request of a reader, I want to begin showing you how to create applications using OpenCV and Python. If you’ve ever taken a look at the OpenCV documentation with Python, you will know that it’s lacking in many ways. So, I want to take a few minutes and give you a crash course with getting OpenCV and Python to play nicely. Let’s begin. Before working with OpenCV and Python, you have an extra Python library you’ll need to download and install if you don’t have it already. I’m talking about “Numerical Python” or “NumPy” as it’s more commonly known. If you already have NumPy installed, make sure you are running at least version 1.6 as that is what our version of OpenCV for Python was compiled against. If you don’t already have NumPy, open a browser and head over to. There you will find a list of downloads for numpy-1.6. Since I’m running on 32bit Windows and using Python 2.7, I will be downloading numpy-1.6.1rc3-win32-superpack-python2.7.exe. Once you have downloaded NumPy, double-click the installer and follow the instruction screens. Note: You can usually keep clicking the Next button to fly right thru the installer. After you have installed NumPy, you are ready to begin playing with OpenCV and Python. If you don’t already have OpenCV installed, you can find links to download it from my new website. Again, since we’re working with Windows, we will click the Windows link under OpenCV at the “Learn Computer Vision” website and that take us to a page on SourceForge where we can click to download OpenCV. However, if you do not want to download and install OpenCV at this time, it’s not required for this example to work. Besides, the current version of OpenCV is 214MB. So, it will take some time to download. If you choose not to install OpenCV at this time, make sure you download the zipped example at the end of this article as it contains the required OpenCV binary for Python. Now that you have everything you need to use OpenCV with Python, it’s time to write some code. For this example, we are going to keep it very simple by demonstrating how to capture video from a standard webcam and display it in a window. To do that, we begin by adding a reference to the OpenCV binary that’s included with the zipped example at the end of this article. import cv2.cv as cv Next, we need to setup our capture device by calling the “CaptureFromCAM” function in our cv2 library. The parameter passed is the index for the camera you will be capturing video from. This is helpful when you have multiple cameras connected to the same computer you’ll be running your application from. In my case, I only have 1 camera attached. So, I simply pass 0 (zero) as my parameter. cap = cv.CaptureFromCAM(0) The next thing we need to do is to tell OpenCV that we want a window created. For that, we will call the “NamedWindow” function and pass it a reference name and some flags that tell our window how to behave. As you can see below, I’m passing 1 (one) as my second parameter which tells my window to act as a normal window with normal behavior and size. cv.NamedWindow(“Camera”, 1) Now you’re ready to begin capturing video from your camera and display it in the window you just created. For that, you will need to create an endless loop. Why an endless loop? Well, in order for OpenCV to have the opportunity to process your video feed, each frame of the video needs to be captured and passed one frame at a time. Most readers think that OpenCV processes video in its entirety. But, like I said, it doesn’t work that way. Video processing is done one frame at a time. That’s why we need our endless loop. However, what happens when you want the app to stop capturing frames from your video and exit? For that, we will tell OpenCV to listen for the Escape key to be pressed. Once the Escape key has been detected, OpenCV will stop capturing your video and will exit from the endless while-loop. Once you’re outside of the while-loop, you will need to tell OpenCV to close all windows that were created within the scope of your app. Here is the complete code that makes all of this possible. import cv2.cv as cv cap = cv.CaptureFromCAM(0) cv.NamedWindow("Camera", 1) while True: img = cv.QueryFrame(cap) cv.ShowImage("Camera", img) if cv.WaitKey(10) == 27: break cv.DestroyAllWindows() You can download this example, including the compiled OpenCV binary from here. PayPal will open in a new tab.
http://www.prodigyproductionsllc.com/articles/programming/getting-started-with-opencv-and-python/
CC-MAIN-2017-04
refinedweb
853
72.46
... it seems to be very complicated using Arduino 1.0.1 ... The more severe issue is, that the bootloader does not de-activate the watchdog upon reset, so that one can end up with endless resets. One issue is, that there is no watchdog function in the Arduino Library that would allow processor-independent implementation of such function; currently, registers have to be set directly. it seems to be very complicated using Arduino 1.0.1 and the current standard bootloader for the AVR boards to get watchdog functionality working. Thank you for the hints...with complicated, I just meant, I spent hours in the internet to find out in principle what to do. I know Arduino aims more on beginners than on hackers, but nevertheless, Arduino is usable for serious applications. And watchdog is missing in the libraries.There are other AVR mega chip built-in hardware functions that are not directly supported by the Arduino core libraries. The watchdog is just one of them. Sleep modes, pin change interrupts and others are not directly supported but has had many request to do so. This doesn't prevent a true hacker from accessing them if they study the AVR datasheet and read the existing arduino source code.Main thing is, I agree, to install the proper bootloader. Why does the pre-installed bootloader not deactivate the watchdog? This should not really be a technical problem, is it?Because the Arduino core libraries did not use or support WDT functions they saw no need to disable WDT interrupts as part of the bootloader start-up code. Others saw the flaw early on and had posted patched bootloader, such as ADAFRUIT, and made it available for downloading directly to users. The Arduino Co. was slow or reluctant to make the change, and I have no memory of the exact status of current arduino shipping bootloaders are at. I think Uno bootloader supports WDT, but Mega boards still do not?Anyway, do you have a link to a bootloader that officially supports Arduino Sketches on a Mega 2560? Sorry if this is a silly question, but I have no special knowledge which bootloaders are available and which one to use for which application.I don't have a link but I pretty sure there is a newer mega2650 bootloader available somewhere that handles the WDT correctly and fixes the !!! bootloader monitor problem. And watchdog is missing in the libraries. #include <avr/wdt.h>... wdt_enable (WDTO_1S); // reset after one second, if no "pat the dog" received... wdt_reset (); // give me another second to do stuff (pat the dog).... In terms of support by the bootloader. I'd call it's lack of support a bug, orat least an issue related to an unintended oversight, particularly givenit is usually a line or two of code to fix it with no other s/w impact.--- bill "watchdog function in the Arduino Library that would allow processor-independent implementation of such function" is there an example set of code that I can compile etc to try out, Please enter a valid email to subscribe We need to confirm your email address. To complete the subscription, please click the link in the Thank you for subscribing! Arduino via Egeo 16 Torino, 10131 Italy
http://forum.arduino.cc/index.php?topic=128717.msg1002638
CC-MAIN-2015-14
refinedweb
545
63.9
The following issue has been updated: Updater: Steven Traut (mailto:straut@bea.com) Date: Fri, 9 Jul 2004 12:20 PM Comment: SchemaEnum.zip containing SchemaEnum sample for review. Changes: Attachment changed to SchemaEnum.zip --------------------------------------------------------------------- For a full history of the issue, see: --------------------------------------------------------------------- View the issue: Here is an overview of the issue: --------------------------------------------------------------------- Key: XMLBEANS-42 Summary: Samples: Add MixedContent and SchemaEnum samples to sample set Type: Task Status: Unassigned Priority: Minor Project: XMLBeans Versions: unspecified Assignee: Reporter: Steven Traut Created: Fri, 9 Jul 2004 12:18 PM Updated: Fri, 9 Jul 2004 12:20 PM Environment: Any. Description: I have two samples to submit for review: MixedContent and SchemaEnum. Descriptions from their readmes are below. Seems to me that potential sample-related tasks are: - Review the code. Is it useful? Does it do what it should? Are there any poor practices illustrated? - If the code is acceptable... - Find a CVS location for the ZIPs. I suggest xml-xmlbeans/samples/<feature_area>/<sample_name>. So the SchemaEnum sample would have this structure in CVS: xml-xmlbeans samples schema schemaenum SchemaEnum.zip <exploded files from zip> - Explode the ZIPs and commit the ZIPs and their contents. - Incorporate samples into the test process. Rather than "asserting" the main sample code, I've included a separate test class in each ZIP that asserts for valid XML (the easiest thing to get a boolean on). I'm hoping this leaves the sample code itself in a useful copy/paste state while still supporting test integration. It's a very large-grained approach, and maybe not useful. I'm a novice at the test thing. I'm open to suggestions. - Create a "Samples" page on the web site and link to the ZIP files from it so they can be downloaded. ----- I tried to follow a few guidelines on package names. Let me know (or feel free to change) if these won't work. - Packages for main classes take the form: org.apache.xmlbeans.samples.schema.enumerations and org.apache.xmlbeans.samples.cursor - Schema namespace URIs (and therefore packages for generated types) take the form: <sample package>.samplemainclassname.<names as needed to disambiguate schemas> Each zip contains a readme. ----- SchemaEnum This sample illustrates how you can access XML values that are defined in schema as enumerations. When a schema containing enumerations is compiled, the generated Java types represent the schema enumerations with Java enumerations. You can access these through their constants and corresponding int values. MixedContent:
http://mail-archives.apache.org/mod_mbox/xml-xmlbeans-dev/200407.mbox/%3C843828120.1089400872050.JavaMail.apache@nagoya%3E
CC-MAIN-2016-40
refinedweb
409
68.06
Oracle Cloud Native Labs is focused on building customer-deployable cloud native and container native solutions to bridge the gap between Oracle Cloud Infrastructure and open source communities. This article was originally published at: Developers and enterprises are increasingly concerned with vendor lock-in and cloud sprawl. Companies are reluctant to adopt new technology if it means that they may find themselves unable to migrate from one vendor due to proprietary standards. At the same time, it has become a challenge to keep track of and manage an ever-growing list of providers and services. With that in mind, Oracle made data and metrics from Oracle Cloud Infrastructure service accessible to analyze and instrument with open source tools. We chose Grafana, the leading open source platform for analytics and monitoring, because of its popularity in the industry and the significant amount of demand it has generated amongst Oracle Cloud Infrastructure customers. We are excited to announce the availability of the Oracle Cloud Infrastructure Data Source for Grafana. a consolidated view of resources across providers. Oracle offers out of the box aggregated metrics for Oracle Cloud Infrastructure services and resources. It also provides you with the ability to discover and retrieve metrics via API. We worked closely with the team at Grafana to develop the plugin. This development effort was complemented by the work done to leverage the open source technology Prometheus within Oracle Cloud Infrastructure. By exposing the Oracle Cloud Infrastructure API as a Grafana data source you can visualize Oracle Cloud Infrastructure data in your Grafana instance and use it to create beautiful and useful dashboards. To install the data source make sure you are running Grafana 6.0 or later. Use the grafana-cli tool to install the Oracle Cloud Infrastructure Data Source for Grafana from the command line: grafana-cli plugins install oci-datasource The plugin will be installed into your Grafana plugins directory, which by default is located at /var/lib/grafana/plugins. Find more information on the CLI tool here. Alternatively, if you are running an earlier version of Grafana, you can manually download the .zip file and unpack it into your /grafana/plugins directory. Make sure you have access to the Monitoring Service and that metrics have been enabled for the resources you are trying to monitor. To pull metrics into Grafana we need to first authenticate against the Oracle Cloud Infrastructure API. To do so, we will use the Oracle Cloud Infrastructure CLI to authenticate between our local environment hosting Grafana and Oracle Cloud Infrastructure. The CLI is built on Python (version 2.7.5 or 3.5 or later), running on Mac, Windows, or Linux. This tool provides you with a way to perform tasks in Oracle Cloud Infrastructure from your command line rather than the Oracle Cloud Infrastructure Console. It does so by making REST calls. Begin by installing the Oracle Cloud Infrastructure CLI. Follow the installation prompts to install the CLI on your local environment. After the installation is complete, use the oci setup config command to have the CLI walk you through the first-time setup process. This will prompt you for various credentials related to your Oracle Cloud Infrastructure tenancy including a public API signing key. If you have not already uploaded your public API signing key through the console, follow the instructions here to do so. This information should come from the same user for whom you created the policy above. To pull metrics into Grafana we need an Oracle Cloud Infrastructure user with proper permissions. In the Oracle Cloud Infrastructure console under Identity > Groups click Create Group and create a new group called grafana. Add the user configured in the Oracle Cloud Infrastructure CLI to the newly-created group. Make sure you are in the root compartment. Under the Policy tab click Create Policy and create a policy allowing the group to read metrics from your tenancy. Add the following policy statements: Log into Grafana and on the Home Dashboard, click the gear icon on the left side of the page, and then click Add data source. Choose oracle-oci-datasource as your data source type. Fill in your Tenancy OCID, Default Region, and Environment. For Environment choose local. Click Save & Test to return to the home dashboard. After configuring the plugin, you will be able. Dimensions can be used to add specificity to your graphs. To use dimensions create a new graph or navigate to an existing one and click the Metrics tab. After selecting your variables click the + next to Dimensions and select one of the tag filters from the list. For example, select availabilityDomain from the list. Next, click select tag value and choose from the newly populated list of tag values. If you chose availabilityDomain as your tag filter, you should see tag values corresponding to the availability domains in which you currently have services provisioned, for example US-ASHBURN-AD-1. Dashboard Templating enables you to dynamically interact with graphs. This makes it easy to change graphs on the fly to visualize additional information about your environment. Using the query template will create a dynamic list of variables to choose from, allowing for users to quickly switch between regions or compartments or other variable as seen in the example below. In order to configure templating, click on the gear icon in the upper right corner of the dashboard creation page from the previous step. This will take you to the Settings page. Click the Variables tab and then click the Add variable button. Add the region variable to this page. Give the variable the name region, choose oracle-oci-datasource from the list of data sources, and for Query enter regions(). The page will load a preview of values available for that variable. Scroll down and click Add to create a template variable for regions. Repeat the process for the following Oracle Cloud Infrastructure variables: The final result will look like this: Oracle Cloud Infrastructure allows for the creation of custom metrics namespaces, which can be used to ingest data from sources in addition to the native Oracle Cloud Infrastructure resources available by default. For example, an application could be instrumented to gather statistics about individual operations. The resource posting custom metrics must be able to authenticate to Oracle Cloud Infrastructure using either using the Oracle Cloud Infrastructure CLI authentication mentioned above or using instance principals. In the example below you can see the option to select custom_namespace from the Namespace drop down. You can also see two custom metrics CustomMetric and CustomMetric2 from the Metric dropdown. You can find more information about using the solution on the Oracle Cloud Infrastructure Data Source for Grafana page on the Grafana Labs site and a Readme with links to detailed installation walkthroughs on the Oracle Cloud Native Labs page. For more information about Oracle's contributions to the open source and cloud native space, head over to.
https://blogs.oracle.com/cloudnative/data-source-grafana
CC-MAIN-2019-51
refinedweb
1,154
54.32
Pigeon Maps ReactJS maps without external dependencies.: - ~20KB minified - ~5KB gzipped Missing: - Double tap and then swipe touch zooming Install One of: # with yarn yarn add pigeon-maps # still on npm npm install --save pigeon-maps Code import Map from 'pigeon-maps' import Marker from 'pigeon-marker' import Overlay from 'pigeon-overlay' const map = ( <Map center={[50.879, 4.6997]} zoom={12} width={600} height={400}> <Marker anchor={[50.874, 4.6947]} payload={1} onClick={({ event, anchor, payload }) => {}} /> <Overlay anchor={[50.879, 4.6997]} offset={[120, 79]}> <img src='pigeon.jpg' width={240} height={158} </Overlay> </Map> ) Inferno support Pigeon Maps works very will with Inferno. Just use these import paths: import Map from 'pigeon-maps/inferno' import Marker from 'pigeon-marker/inferno' import Overlay from 'pigeon-overlay/inferno' Here's the same demo running in Inferno Plugins pigeon-overlay (demo) - an anchored overlay pigeon-marker (demo) - a simple marker component If you're interested in making a new plugin, check out the code of pigeon-marker as a starting point. Feel free to clone the repo and rename every mention of pigeon-marker to pigeon-myplugin. You'll get a demo and linking system out of the box. More documentation about this coming soon. Contributions welcome. API Map defaultCenter - Coordinates of the map center in the format [lat, lng]. Use if the component is uncontrolled. center - Coordinates of the map center in the format [lat, lng]. Use if the component is controlled, e.g. you'll be listening to onBoundsChanged and passing a new center when the bounds change. zoom - Current zoom level 12 width - Width of the component in pixels. Must be set. height - Height of the component in pixels. Must be set. provider - Function that returns a TMS URL: (x, y, z) => url. animate - Animations enabled, true. zoomSnap - Snap to discrete zoom increments (14, 15, 16, etc) when scrolling with the mouse or pinching with touch events, false. attribution - What to show as an attribution. React node or false to hide. attributionPrefix - Prefix before attribution. React node or false to hide. onClick - When map is clicked `function ({ event, latLng, pixel })`` onBoundsChanged - When the bounds change, function ({ center, zoom, bounds, initial }). Use this for a controlled component, then set center and zoom when it's called. This callback also gets called on the initial mount (when the first bounds become known). In this case the prop initial will be set to true. It will be false on all subsequent calls. onAnimationStart - Called when the map starts moving onAnimationStop - Called when the map stops moving zoomOnMouseWheel - Should we zoom if you scroll over the map with the mouse wheel? Defaults to true. mouseWheelMetaText - What text to show if trying to zoom by scrolling, but it's disabled? Defaults to Use META+wheel to zoom!, where META is automatically replaced with either "⌘" or "⊞", depending on Mac vs non-Mac. Set to null to disable. Overlays <Map /> takes random React components as its children. The children may have these special props: anchor - At which coordinates [lat, lng] to anchor the overlay with the map. offset - Offset in pixels relative to the anchor. The children get passed these special props: left - Pixels from the left of the map, calculated from anchor and offset top - Pixels from the top of the map, calculated from anchor and offset mapState - An object { center, zoom, bounds, width, height } that gets updated at every animation frame. latLngToPixel - A helper function (latLng, center, zoom) that returns the position in pixels [x, y] for any [lat, lng]. The last 2 arguments are optional. pixelToLatLng - A helper function (pixel, center, zoom) that converts any pixel coordinates [x, y] to [lat, lng]. The last 2 arguments are optional. Use these two functions to create beautiful widgets. See a sample overlay. Add the class pigeon-drag-block to disable dragging on the overlay. Add the class pigeon-click-block to disable map background clicks on the element. Alternatively use the <Overlay /> component. It accepts anchor, offset and classNames as its props and positions itself accordingly.
https://reactjsexample.com/reactjs-maps-without-external-dependencies/
CC-MAIN-2022-27
refinedweb
673
58.99
This action might not be possible to undo. Are you sure you want to continue? iii The Unofficial Guide to LEGO® MINDSTORMS™ Robots Jonathan B. Knudsen O’REILLY Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo iv The Unofficial Guide to LEGO® MINDSTORMS™ Robots by Jonathan B. Knudsen Copyright: © 1999 O'Reilly & Associates, Inc. All rights reserved. Printed in the United States of America. Published by O'Reilly & Associates, Inc., 101 Morris Street, Sebastopol, CA 95472. Editor: Mike Loukides Production Editor: Nicole Arigo Printing History: October 1999: First Edition. This book is published solely by O'Reilly & Associates, Inc., and its purpose is to enable you to creatively program LEGO® MINDSTORMS™ brand robots. This book is not sponsored by The LEGO® Group. Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logo are registered trademarks of O'Reilly & Associates, Inc. The association of the image of a mechanical toy rabbit with the topic of LEGO® MINDSTORMS™ robots is a trademark of O'Reilly & Associates, Inc. LEGO® is a registered trademark of The LEGO® Group. MINDSTORMS™ and Robotics Invention System™ are trademarks of The LEGO® Group. All other trademarks, service marks, and the like are the property of their owners.. ISBN: 1-56592-692-7 [12/99] [M] vii Table of Contents Preface xi 1. Welcome to MINDSTORMS 1 What Is a Robot? 2 Mobile Robots 2 What Is MINDSTORMS? 6 What Now? 11 Online Resources 11 2. Hank, the Bumper Tank 14 About the Building Instructions 14 Building Instructions 16 A Simple Program 25 Wheels 27 Bumpers and Feelers 31 Gears 31 Multitasking 36 Online Resources 37 3. Trusty, a Line Follower 39 Building Instructions 40 Some Tricky Programming 44 The Light Sensor 48 Idler Wheels 50 Using Two Light Sensors 50 Online Resources 52 4. Not Quite C 53 A Quick Start 54 RCX Software Architecture 55 NQC Overview 58 Trusty Revisited 77 Online Resources 81 viii 5. Minerva, a Robot with an Arm 82 Building Instructions 83 Programming 103 Directional Transmission 107 Pulleys 109 Mechanical Design 110 Two Sensors, One Input 112 Where Am I? 113 Online Resources 115 6. pbFORTH 116 Replacement Firmware 116 pbFORTH Overview 117 About Forth 121 pbFORTH Words 126 An Expensive Thermometer 137 Minerva Revisited 138 Debugging 142 Online Resources 143 7. A Remote Control for Minerva 145 Two Heads Are Better Than One 145 The Allure of Telerobotics 146 Building Instructions 147 Programming the Remote Control 151 Programming Minerva 154 Online Resources 157 8. Using Spirit.ocx with Visual Basic 159 You May Already Have Visual Basic 159 About Spirit.ocx 160 Calling Spirit.ocx Functions 161 Immediate and Delayed Gratification 163 Programs, Tasks, and Subroutines 164 Tips 165 Retrieving the Datalog 168 Online Resources 171 Future Directions 240 Index 242 . a Game for Two Robots 173 Building Instructions 174 Subsumption Architecture 179 Online Resources 188 10. RoboTag.ix 9. Make Your Own Sensors 216 Mounting 216 Passive Sensors 219 Powered Sensors 221 Touch Multiplexer 224 Other Neat Ideas 226 What About Actuators? 226 Online Resources 227 A. A pbFORTH Downloader 235 C. legOS 189 About legOS 189 Development Tools 190 Hello. Finding Parts and Programming Environments 230 B. legOS 192 Function Reference 193 New Brains for Hank 204 Development Tips 211 Online Resources 213 11. xi Preface This is a book for people who build and program LEGO® robots with the Robotics Invention System (RIS)™ set. This book will take you there. In high school. this book is an introduction to the most important developments in that community—alternate programming environments and advanced building techniques.000 of these sets in 1998 and sold every one. and more fun. But this book goes farther than that. This book is the answer to the question. you'll probably be itching for more: more complex robots. the chance to make LEGO models that moved. sensed. and thought! The LEGO Group made 80. painting a backdrop of the theories and practices of mobile robotics. the RIS has also hypnotized many people in their 20s. 11 and older. a little LEGO set was the high point of my six-week convalescence. Although The LEGO Group was aiming for young adults. When I was five and broke my leg. inventive online community sprang up around MINDSTORMS robots. A vibrant. About This Book For many of us. and beyond. The LEGO Group released the Robotics Invention System (RIS). a set that was part of a new product line called MINDSTORMS™. I shifted into the TECHNIC™ product line—what could be better than cars with real shifting and pistons that worked? In the Fall of 1998. . In some ways. more sensors. more powerful programming environments. plastic LEGO bricks are the best toy money can buy. This set entered the world like a lightning bolt—finally. 30s. wearing grooves in the ends of my fingernails from endlessly putting together and taking apart my creations. I grew up building spaceships and planetary rovers. "How can I push this thing as far as it will go?" Once you've built a few robots and written a few programs. Make Your Own Sensors.ocx with Visual Basic. in a sense. pbFORTH. legOS. including code examples and debugging tips. Minerva. NQC is an excellent environment for programming robots. all in the spirit of fun and learning. This book is designed to take you to the next level of building and programming. and how to write programs that can deal with the real world. This chapter discusses basic mechanical features like gears and bumpers. You'll learn about directional transmissions and other neat stuff. a Game for Two Robots. It's fun to build something that moves and thinks. Using Spirit. Chapter 10. Chapter 5. The chapter includes descriptions of NQC's functions as well as many examples. talks about how to control and program your robots using Microsoft's Visual Basic. . C++.xii Building and programming robots is exhilarating. It uses a light sensor to follow a black line on the floor. complete with building instructions and programs. RoboTag. Chapter 7. a Robot with an Arm. discusses legOS. discusses an innovative programming environment based on a language called Forth. introduces the Not Quite C (NQC) language. the Bumper Tank. Using a second robot kit. a programming environment that enables you to program your robots with C. Four chapters describe various programming environments for LEGO MINDSTORMS robots. at the same time. a Line Follower. covers a slightly trickier robot—a line-follower. is the first building project—a tank-style robot that avoids obstacles in its path. contains another building project—by far the most complex robot in the book. A Remote Control for Minerva. describes how you can build sensors for your robots easily and inexpensively. Hank. Chapter 8. you're learning a lot about how things work. Five chapters have robot projects. The first and last chapters don't fit in either category. This book's chapters come in two basic flavors. Chapter 2. Trusty. Chapter 3. or assembly code. Chapter 9. Here's a description of each chapter in this book: Chapter 1. Chapter 4. Robotics and MINDSTORMS. introduces the field of mobile robotics and describes how the LEGO MINDSTORMS Robotic Invention System fits in the larger picture of the field. mechanically. Chapter 6. Chapter 11. Not Quite C. is another project-based chapter. shows how to create a pair of robots that play tag. you can build a remote control for the robot from Chapter 5. Future Directions. describes various parts you can get to expand your RIS set and where to find them. It also includes a summary of the programming environments that are available for RIS.7 legOS The March 30. Finding Parts and Programming Environments. This site also provides a listing of the "Online Resources" that appear at the end of each chapter.7 Downloading All of the examples in this book can be downloaded from. A pbFORTH Downloader. describes some interesting emerging technologies related to LEGO robots.oreilly. 1999 build.xiii Appendix A.0. About the Examples Versions This book covers a handful of rapidly evolving technologies.1. Appendix C. Appendix B.0 NQC Version 2. contains the source code for a program that downloads Forth code to your robots. The versions used in this book are as follows: RCX Version 1. These are ideas or projects that weren't fully baked as this book went to press. a patched version of 0.com/catalog/lmstorms/ .0b1 pbFORTH Version 1. It's a supplement to Chapter 6. Font Conventions Constant width is used for: • Function and subroutine name • Source code • Example command-line sessions—the input you type is shown in boldface . We take your comments seriously.xiv Italic is used for: • Pathnames and filenames • New terms where they are defined • Internet addresses. or Canada) (707) 829-0515 (international or local) (707) 829-0104 (fax) bookquestions@oreilly. and will do whatever we can to make this book as useful as it can be.com Please let us know what we can do to make the book more helpful to you. Thanks to Mike. Request for Comments If you find typos. You can reach O'Reilly by mail. telephone. 101 Morris Street Sebastopol. CA 95472 (800) 998-9938 (in the U. This is a note with information that supplements the text. Acknowledgments This book is the result of a crazy idea I had in mid-1998. LEGO robots sounded like something O'Reilly readers would like to play with—why not write a book about them? I'd like to thank Mike Loukides and Tim O'Reilly for having the vision to believe in this book. inaccuracies. again. when I first heard that the Robotics Invention System was coming.S. or email: O'Reilly & Associates. fax. Inc. for excellent help and feedback. such as domain names and URLs Boldface is used for the names of buttons. This is a warning with a cautionary message for the reader. . or bugs. please let us know. Did you ever expect something like this? Many thanks go to my wife. sweetheart. Daddy's working right now. This book has had an excellent set of technical reviewers. she is able to keep a straight face when we tell people I'm writing a book about LEGO robots. ''Want to see Daddy. I promise. for helping to create this book. not just the bendy purple things. Suzanne Rich. Daddy play LEGOs. cropped. and manipulated to produce the instructions that you see in the book. Kristen took over 475 photographs with a regular camera. I first sketched out the building instructions with photos from a digital camera. I owe many thanks to Rob Romano for his hard work on these instructions. We selected the best and sent them off to the O'Reilly illustration department. ActivMedia Robotics (. She first suggested its project-oriented organization. Once these were finished." she said one day. John Tamplin. You can build robots someday too. and Ben Williamson provided insightful and authoritative feedback on a draft of this book. "No. Thanks also to Stephan Somogyi for encouraging me to include more information about using a Macintosh with MINDSTORMS. I'm grateful to my daughter. she got me RolyKits to help organize my pieces. Kristen explained.activrobots. Russel Nelson. if you wish. just for being great guys.com/ ). I'll let Daphne play with the whole set. Daphne. no. Daphne said." Someday. edited. Kristen." With tears in her eyes. The building instructions in this book were a special challenge. she stayed up late nights helping me finish the book. she gave me excellent feedback on many of its chapters. Luke and Andrew. These photographs were scanned in and meticulously touched up. Todd Lehman. And thanks to my sons. "Daddy's not working. Ralph Hempel. who finally believes that building LEGO robots is part of my job.xv I'd like to thank my parents for buying me LEGO sets when I was a kid. . Part of this book is about building robots.1 1 Welcome to MINDSTORMS In this chapter: • What Is a Robot? • Mobile Robots • What Is MINDSTORMS? • What Now? • Online Resources This is a book about creating robots with the LEGO® MINDSTORMS™ Robotic Invention System (RIS)™. Aside from the "official" software that comes with RIS.∗ You can build anything you can imaging. But you also have lots of options for programming your robot. if you build something cool. are a kind of lingua franca for mechanical design. you can build and modify other people's creations. the inventive MINDSTORMS community has produced a bevy of other options. LEGO bricks. robots that seek light. The RIS set is a common ground for building robots. or a monorail car that traverses your living room on a string. ∗ Internet links to pictures of some of these robots are included in the "Online Resources" section at the end of this chapter. LEGO bricks. and robots that simulate a Tsunami and a tornado. making them move and respond to their surroundings. RIS gives you a chance to breathe life into LEGO creations. robots that play tag. other people will be able to build it too. can be assembled in many different ways. You can create a tank that scurries into the dark. If you've always dreamed of building and programming your own robots. You have many options when it comes to building and programming robots. working computer peripherals like a plotter and an optical scanner. it includes five projects that you can build yourself. by owning the RIS set. Similarly. . therefore. You can create robots that hop. four. walking robots with two. of course. and drive around with a mind of their own. or even eight legs. robots that can be controlled over the Internet. this is your big chance—the RIS set makes it easy to get started. you become part of a worldwide community of enthusiasts. Furthermore. There are a lot of enthusiastic RIS owners out there already: other people have built robots that pick up empty soda cans. walk. The most important ones are described in this book. six. Actuators allow the robot to move. These robots can move their bodies around from place to place. a far cry from the talking androids you might be thinking of.2 This chapter describes the basic concepts of robotics and creates a backdrop for the MINDSTORMS product line. This is a broad definition—it includes things like VCRs and microwave ovens. Usually the brain is a computer of some kind. What Is a Robot? A robot is a machine whose behavior can be programmed. The last component is not always obvious: 5. Sensors give a robot information about its environment. Position and rotation sensors are used so the robot knows where the sprayer is and what direction it's pointing. Its brain is probably a garden-variety desktop computer. 3. Finally. The body is a big arm with a paint sprayer at the end. . 4. Mobile Robots Mobile robots present special challenges. If you're in a hurry to start building something. A touch sensor. actuators. I'll also cover different approaches to programming mobile robotics. such as hydraulic pistons. For example. can tell a robot that it has come in contact with something else. think about a robot that spraypaints cars in a factory. The whole thing is plugged into a wall socket for power. Hank. A robot's body is simply the physical chassis that holds the other pieces of the robot together. although there are many other possibilities. A power source supplies the juice needed to run the brain. These are usually motors. for example. I'll describe the RIS set itself. 2. The actuators are motors or pneumatic pistons that move the arm around. the Bumper Tank. Robots have five fundamental components: 1. A brain controls the robot's actions and responds to sensory input. and sensors. Why is this capability difficult? Many more things can go wrong if your robot is free to move around rather than being bolted to one place. skip ahead to Chapter 2. Being mobile multiplies the number of situations your robot needs to be able to handle. and not cheaply. you need to find a power supply that will run the robot for long enough to clean at least one room. not simply. It all comes down to one fact: it's very hard to deal with the real world. After years of sweat and expense. These robots need to bring everything along with them. the world would be full of them. If it wasn't so hard to make autonomous mobile robots. which adds a lot of weight to the robot. Add a rocking chair. Autonomous mobile robots are even more challenging. Suppose you modify your vacuum cleaner so that it can move around on its own. and you'd probably have to start all over again. Have you ever seen an autonomous mobile robot. To understand this. but only under very closely controlled conditions. or toys.3 Mobile robots actually come in two varieties: tethered and autonomous. think about how you might try to make a robot to vacuum your living room. . If you have been lucky enough to see such a robot. Just consider the staggering complexity: • How does the robot keep from getting tangled up in its own power cord. or your cats? You can answer these questions. • How does the robot know where it's been already? How does the robot know where it is? How does it know where to go next? • How does the robot navigate around obstacles like table legs and furniture? • How does the robot recognize things it shouldn't vacuum. not weigh a ton. by adding more motors and a small computer brain. possibly relying on a desktop computer and a wall outlet. The power supply is typically an array of batteries. A tethered robot "cheats" by dumping its power supply and brain overboard. and be frugal about sucking power out of the batteries. but not well. besides in the movies? Probably not. at least as far as the tether will allow. The brain is also constrained because it has to fit on the robot. did it work? Probably not. assuming it's a tethered robot? If it's not tethered. If the robot was supposed to do something useful. Control signals and power are run through a bundle of wires (the tether) to the robot. This is a pretty simple task to describe: basically you just want to move the vacuum back and forth over the rug until the whole thing is clean. This Is Tough Stuff The field of autonomous mobile robotics is extremely challenging. including a power supply and a brain. Wouldn't it be nice to have a robot do your laundry or drive you to the airport? But the cold truth is that it's unbelievably difficult to make a robot that can do even the simplest of tasks. was it doing something useful? Probably not. which is free to move around. or drop a child's toy in the middle of the room. like money. you might produce a robot that could vacuum a room. too. again. Suppose that you want to go down in your basement and build a mobile robot. is often a collaborative effort. which implies a bulky. universities. while heavy-duty computers analyze all the sensor data and attempt to build a map. heavy power supply. Finally. . the robot takes input from its sensors and tries to build a map of its surroundings. The heavy computing requirements of the AI approach consume a lot of power. This process alone is very complicated: the robot might use a pair of video cameras or some more exotic sensors to examine its surroundings. including: • An electrical engineer chooses the brain. sensors. which makes it even more complex. and power supply) so that everything fits together mechanically. are still confined to the research programs of colleges. the robot is expected to think like a human being. It is very rare for a single person to be knowledgeable in all of these fields. This is the traditional Artificial Intelligence (AI) approach to robotics. or picking up an object. and governments. then. you might even want to have a chemical engineer to select or design the power supply. and actuators that the electronics and mechanical people have chosen. sensors. and wires them all together. or some other simple task." more or less the same way that a human does. as well. actuators. This research is divided into two camps: the big robot people and the little robot people. highly paid engineers. In this approach. the robot can be pretty big and expensive. for the most part. Hence. and maybe the actuators. The mechanical person needs to be familiar with the other components of the robot (brain.4 Another reason that robotics is so challenging is that it spans many different disciplines. sensors. This person probably selects the power supply. • For specialized designs. This task usually requires intimate knowledge of the brain. • A mechanical engineer designs the body and possibly selects the actuators. in a process called task planning. In this respect. Without some sort of kit. Designing a mobile robot. Autonomous mobile robots. • A computer programmer writes the software for the robot. Big Is Beautiful The big robot people believe that the robot should understand its environment and "think. you'd probably need to take along a team of highly educated. the robot tries to figure out how it will accomplish an objective—getting from one point to another. Small robots are usually based on an existing. off-the-shelf parts. He's My Robot A good example of the "big iron" approach to mobile robots is Ambler. If you take the small robot approach. Ask it to walk and it sucks up just about 4000 W. cheap microprocessor. achieving decent results at a fraction of the cost and complexity of big robotics. It makes robotics accessible to sophisticated hobbyists—people with technical knowledge and some extra time and money.0ft) wide. which eliminates the need for a chemical engineer to design a power supply. • The computer programmer still needs a pretty low-level understanding of the microprocessor and the attached sensors and actuators. you'll probably use standard batteries for power. But you still need quite a bit of expertise: • The electrical engineer still has to select sensors and actuators and wire them to the microprocessor. One of the interesting ideas behind small robot research is the idea that quantity might get the job done rather than quality.5 He Ain't Heavy. You can see a photograph of Ambler at. . Just sitting still. These parts are inexpensive and can be bought from hobby stores or electronics part stores.oact. • You still need a mechanical engineer to design the robot's body. is up to 7m (23.8 in) per minute.4ft) tall. it consumes 1400 W of power. why not send a thousand robots the size of mice to do the same job? So what if a few of them fail? Small robots offer a new and innovative way to approach big problems. tremendously expensive machines that don't have the dexterity of a six-month-old baby. They like to see themselves as mavericks. which makes the electrical engineer's job a little easier. Small Is Beautiful Little robot people like to tease the big robot people for building tremendously large. developed by Carnegie Mellon University and the Jet Propulsion Laboratory.gov/telerobotics_page/Photos/Ambler. It moves at a blistering 35 cm (13. Instead of building a single bulky. This behemoth stands about 5m (16.nasa. The small robotics approach reduces the number of engineers you need in your basement. complex robot to explore the surface of Mars. and weights 2500 kg (5512 lb).jpg . The little robot people make small mobile robots based around inexpensive.hq. What Is Mindstorms? MINDSTORMS is the name of a product line sold by The LEGO Group. ∗ Some people think RCX stands for Robotic Controller X. This approach saves you the trouble of selecting a microprocessor and getting it running. It makes the challenges and excitement of mobile robotics accessible to anyone with $200US and a desktop computer (PC). According to the MINDSTORMS web site. is the MINDSTORMS™ Robotics Invention System itself. a set for building robots. of course. The LEGO Group has a handful of product lines that cater to different age groups.6 The sophisticated hobbyist can do all of these things alone. There are a couple of ways to make things easier: • You could buy a prebuilt robot brain. researchers and students at the Massachusetts Institute of Technology (MIT) have been using LEGO bricks for mechanical prototyping for over a decade. The RIS set eliminates many of the difficulties of building mobile robots: • The set comes with a robot brain called the RCX. Representative LEGO Product Lines Product Line Name Suggested Ages LEGO® PRIMO™ 3 months to 24 months LEGO® DUPLO™ 18 months to 6 years LEGO® SYSTEM™ 3 years to 12 years LEGO® TECHNIC™ 7 years to 16 years LEGO® MINDSTORMS™ 11 years and older The centerpiece of MINDSTORMS is the Robotics Invention System (RIS). • You could use a modular construction kit to build the robot's body. . Best of all. But you have to be determined and have a lot of free time and money. It gives you a chance to solve problems in innovative ways. some of which are shown in Table 1-1. LEGO® bricks are one possibility—in fact. but you still have to select sensors and actuators and attach them to the brain somehow. An even better simplication. it's a lot of fun.∗ The RCX is a small computer that is neatly packaged in a palm-sized LEGO brick. Some companies sell kits that are designed specifically to be used as robot brains. Table 1-1. RCX stands for Robotic Command Explorer. it's likely you'll repeat the steps many times as you gradually improve the mechanical design and software of your robot. It also includes a power jack. Like the sensors. . but it would cost more and would not be nearly as easy to use. Download the program to the robot. You could build a comparable setup by buying the pieces separately. The set includes an IR tower that attaches to one of the serial ports on your PC. Just point the tower at the RCX. 2. they can be connected to the RCX by just snapping LEGO bricks together. Figure 1-1 illustrates the basic setup. of course. Is it a good deal? Yes. Build the robot's body. You can supply power in either polarity. your robot is ready to go. sensors. • The set includes more than 700 LEGO pieces that you can use to build the body of the robot. even AC. 3. Write a program for the robot using software tools on your PC. 4. • The set also includes two motors. This is only a sketch of the process. You can create a program on your PC using the MINDSTORMS software. Programs are sent to the RCX over an infrared (IR) data link. and actuators that come with the RIS set are easy to hook up. highly visual programming environment on your PC. And you don't need a mechanical engineer because building a body is as simple as building a LEGO model. Wiring the sensors to the RCX is as simple as snapping LEGO bricks together. Run the program. Once the program is downloaded.7 • Two touch sensors and one light sensor are included in the RIS set. from 9V to 12V. • You can write programs for the brain using an intuitivé. • The RCX uses six standard AA batteries for power. Then you need to download it to the RCX using the IR link. You don't need an electrical engineer anymore because the brain. Building a robot using MINDSTORMS consists of four steps: 1. You don't need a computer programmer anymore because the programming environment is easy to use. and you're ready to download programs. are located near the center of the brick. . Various types of sensors can be attached to these ports to allow the RCX to find out about its environment. are provided. B. and C. Figure 1–2 shows a photograph of the top of the RCX. labeled A. a robot brain The RCX is a small computer with the following features: outputs Three output ports. Basic MINDSTORMS setup Figure 1-2. The robot's actuators (motors or lights) can be attached to these ports. Figure 1-1.8 Meet the RCX The RCX is a robot brain in the form of a bulky LEGO brick. inputs Three input ports. The RCX. 2. labeled 1. and 3. the official environment that comes with RIS is only one of them. This book will introduce you to four powerful alternate programming environments. Basically it can all be distilled down to three pieces: documentation The RIS software includes extension tutorials about setting up and programming the RCX.9 screen The RCX includes a small LCD screen. When you first begin using the software. sound The RCX is capable of producing beeps of different frequencies. This screen displays helpful information such as sensor readings and output port settings. programming environment The RIS software includes an environment you can use to write programs that will run on the RCX. front panel buttons Four buttons are provided to control the RCX. . program downloader Once you've written a program for the RCX. there are many ways to write programs for your RCX. This is a good way to get used to the software and the RCX. You can select a program. You can also view the values of attached sensors or check the settings on output ports. step-by-step instructions. which means the software tells you what to do next. In the computer world. similar to that on a television remote control. In this case. movies. It knows how to transmit your robot programs into the RCX using the IR link. this technique is called cross-compiling. The RIS software includes a program downloader for this purpose. it is in guided mode. meaning you write a program on one computer that you intend to run on another. you use your PC to write a program that will be run on the RCX. you need to know how to run it. It can also communicate with other RCXs through this link. These include animations. The program downloader is a special application that runs on your PC. IR communications link The RCX communicates with your PC through the IR (infrared) link. As you'll see. About the Software The CD-ROM that comes with RIS contains a lot of software. and detailed. and stop it. start it. If you have MacOS or Linux. See Appendix A for details. Finding Parts and Programming Environments. the MINDSTORMS product line also includes expansion sets. It's oriented towards robots that can play different sports.com/~dbaum/lego/macmind/index. lists the different packages that are available. however. Appendix A. A third expansion set. and an additional motor. Other Sets RIS isn't the only game in town. See Appendix A.10 What About MacOS and Linux? Currently. for details. each selling for about $50US : Extreme Creatures This set comes with about 150 LEGO pieces and is designed so you can add decorative jaws and claws to your robots. the software that comes with RIS runs only on Windows. The following web page describes the issues of programming the RCX from MacOS. by themselves. is NQC. should be released sometime in 1999. the consensus is that the expansion sets are not as good a value as the RIS set itself. These sets provide additional parts and software to supplement the RIS set.html . Among LEGO enthusiasts. which is described in Chapter 4. two balls. Both sets are based on the same technology as RIS. two pucks. . it might be better to buy a LEGO TECHNIC set instead. They have more limited capabilities than RIS with the intent of making them easier to use. Exploration Mars. There's one final wrinkle if you want to program from MacOS: you'll need a suitable cable. You can purchase a Macintosh IR tower cable from Pitsco LEGO DACTA for $15US. Two such sets exist. The best option. If you're looking for extra pieces. It includes a light that can be attached to one of the output ports of the RCX. there are other ways to get these. including cables:. you can purchase ROBOLAB. If you really want visualstyle programming (like RCX Code). which provides a similar (but more powerful) environment on MacOS. Robosports This expansion set includes about 90 LEGO pieces.enteract. Expansion Sets Aside from the basic RIS set. If you're looking for additional sensors and motors. In 1999. two new MINDSTORMS sets were released: the Droid Developer Kit and the Robotics Discovery Set. just not with the official software. Finding Parts and Programming Environments. at least to get started. you can still program your robots. legomindstorms. This URL will take you to the top level of the LEGO robotics discussion groups.oreilly. When you're thirsty for more. and have fun with your new toy. It will tell you everything you need to know to push your MINDSTORMS set as far as it can go. These cover a broad range of topics: clever mechanical designs. . follow the instructions on the MINDSTORMS CD.com/ Tis is the official site of The LEGO Group. LUGNET is an outstanding. which is further subdivided into more specific interests.11 What Now? Now that you have some background in mobile robots and LEGO MINDSTORMS. LEGO Worlds. come back and read the rest of this book. Online Resources One of the most exciting things about MINDSTORMS is the online community that supports it. Robotics There's a lot of information out there. many unofficial sites have appeared. It contains handy tips and mildly informative articles. where you can post pictures of your creations and even the programs that run them. LEGO's official MINDSTORMS site provides some interesting information as well as a chance for RIS owners to exchange designs and ideas. a whole hierarchy of them is devoted to robotics. It's a good place to go to browse through different product lines and to get a sense of the entire company's product offerings.lugnet. Read the manuals. novel sensors.com/ This is the official site of MINDSTORMS.lego. my lists are also available online at. I'll list references to online resources at the end of each chapter in this book. even a new operating system for the RCX. LEGO MINDSTORMS. alternate programming environments. you can sign up for your own little corner of this web site. But in the months since the release of MINDSTORMS.com/robotics/ LUGNET (the international fan-created LEGO Users Group Network) forms the hub of the online LEGO universe. LUGNET hosts many useful discussion groups. what should you do? Play. On the one hand. If you own a MINDSTORMS RIS set. searchable resource. Browsing the MINDSTORMS web ring is a good way to acquaint yourself with the MINDSTORMS online community. You can traverse forward or backward through the entire ring if you wish. pbFORTH. and legOS.nifty. a ''minor deity" in the online MINDSTORMS world. RCX Internals Ben Williamson is a very gifted mechanical designer.edu/~kekoa/rcx/ This page presents the results of Kekoa Proudfoot's reverse engineering efforts on the RCX. and other pearls. maintained by Russell Nelson. maintained by someone named Joe. LEGO MindStorms Gallery. or visit sites in a random order. but the pictures are fascinating. many different robots. this page is fascinating reading. to quote Russell Nelson. Kekoa is. including a working plotter.hvu. This visually clean web site details Ben's creations. an intelligent truck.html A web ring is a set of sites that are all linked to each other. Ben's Lego Creations. includes photographs and descriptions of many.crynwr. CyberMaster™.12 Lego Mindstorms Internals. It contains.svc.jp/mindstorms/ This Japanese web site.com/~ssncommunity/webrings/legoms_index.stanford. LEGO MINDSTORMS WebRing. a detailed description of a MINDSTORMS-based optical scanner.pobox. a treaded robot with a grabber arm.ne. contains many fascinating nuggets of information about RIS and the things you can do with it. .mop.com/lego-robotics/ This page. which enabled the development of interesting technologies like NQC. Lego Simen Svale Skogsrud maintains this fascinating site. LEGO on my mind: Roboworld. including several flavors of walkers. even if you can't read the text. The text is mostly in Japanese.no~simen/lego. among other interesting things. For hardcore geeks.nl/brok/legomind/robo/ This comprehensive unofficial site contains a helpful section that introduces MINDSTORMS RIS and its TECHNIC doppelgänger. com/whatsnew/robotvac.htm I'm not the only one who doesn't want to vacuum the floor.mit. What's New at Eureka. This web site provides an overview of the E&L group and describes its aspirations and current projects. around obstacles and over electrical cords. Supposedly it will navigate through a room.eureka. Crickets: Tiny Computers for Big Ideas. you'll find photographs and descriptions of a MINDSTORMSbased Tsunami and tornado. vacuuming as it goes.www. take a look at Crickets. but this site can give you the inspiration to build your own tiny robots. another project from the fine people at MIT.www. Crickets are not publically available. Crickets are a very tiny mobile robot platform.html This web site belongs to Marcus Fischer-Mellbin.media.13 Lego. Looking through this site is like leafing through the RCX's family photograph album. a ten-year-old with a penchant for natural disasters.fischer-mellbin.mit. The MIT Programmable Brick The Epistemology and Learning Group (E&L group) at MIT's prestigious Media Lab basically developed the RCX that is the centerpiece of MINDSTORMS.mit. My favorite part: "Switch on the robot vac and you'll hear a robotic tone" What's a robotic tone? . Hardly larger than a nine-volt battery.media.edu/groups/el/projects/programmable-brick/ The MIT Programmable Brick is the forerunner of the RCX. Along with other models. This page at Eureka describes the Eureka Robot Vac.edu/people/fredm/projects/cricket/ If MINDSTORMS robots aren't small enough for you. The Epistemology and Learning Group. a kind of concept car in the world of vacuum cleaners. Hank is a fairly simple robot that will serve as a good jumping-off point to discuss: • Various means of locomotion • Bumper design • The use of gears • Motors • Software multitasking Figure 2-1 shows a picture of the completed robot. bushings. however. There are. This chapter includes complete building and programming instructions so that you can build Hank yourself. Whenever he bumps into an obstacle. I suggest you begin by building and programming Hank. shafts. About the Building Instructions The building instructions for the robots in this book are comprised of pictures. and wire bricks. turns away from the obstacle. Then come back and read the rest of the chapter. gears. so that I don't end up describing everything as a ''doo-hickey" or a "little gray thingy. the Bumper Tank In this chapter: • About the Building Instructions • Building Instructions • A Simple Program • Wheels • Bumpers and Feelers • Gears • Multitasking • Online Resources Hank is the first robot we'll be building. Each step shows you the parts you need as well as how they fit together." The parts you need to know are beams.14 2 Hank. like a chair leg or a shoe. He is a friendly robot who explores the floor of a room. plates. some names with which you should be familiar. he backs up. with a little bit of explanation here and there. and goes forward again. where I'll talk about some of Hank's interesting features. . Let him run around your floor for a while. a friendly robot Beams. plates. and shafts and their lengths Gears. ." Figure 2-2. There are two types of bushings in the RIS kit: regular and half-size. A 24t gear. plates. are described by the number of teeth they have. Hank. Figure 2-4 shows the bushings. The "u" stands for "units.") Figure 2-3 shows a photograph of the various types of gears that come with the RIS kit. Both fit on shafts and are used for securing a shaft in place or for spacing. this corresponds to how many studs (bumps) are on the beam. plates. for the most part. (The "t" stands for "teeth. and shafts are characterized by their length. has 24 teeth. For beams. for example. and shafts with their corresponding lengths.15 Figure 2-1. Some beams. at least. Figure 2-2 shows a photograph of some beams. This piece is used to make an electrical connection between a sensor or motor and the RCX. Full and half-size bushings Finally. Figure 2-5.16 Figure 2-3. the term wire brick refers to the part shown in Figure 2-5. A wire brick . Gears Figure 2-4. 5. you'll need to fit the tread wheel and another bushing on the end. and the bumpers.5 are slightly different than those in RIS 1. .17 Building Instructions∗ Create Hank's main chassis as shown in the next two steps. ∗ The parts included with RIS 1. Attach the shafts as shown. Hank's treads will be mounted on these shafts. you should use two bushings instead of the green pieces in Step 2. If you're building Hank using RIS 1. the motors. The front pair do not rotate. Don't push the front pair all the way in.0. this will hold the RCX. while the rear pair should. 18 The back tread wheels are anchored to the shafts with the 16t gears. . 19 . .20 Next. start building support for the drive motors. then anchor them down with the yellow plates. .21 Place the wire bricks on the motors. The wires themselves will fit into the grooves on the top of the motors. .22 Attach the motor wires to output A and output C. build the platform for the front bumpers. Next. .23 The touch sensors are attached only by the shaft that runs through them. and the other side won't. The bushings are pushed onto the plate in the next step. A light touch on the bumper pushes the touch sensor. one side will push into the plate. Hank's right bumper works exactly the same way. Note that the bushings are not symmetrical.24 Hank's left bumper is next. . you need a program to make it work. The rubber bands keep the bumpers from swinging forward. Hank's mission in life is to explore the world. . A Simple Program Now that you've built a robot. Slide the blue rubber bands onto the bumpers and anchor them to the bushings from the last step.25 Finish Hank by attaching the bumper touch sensors to input 1 and input 3. Use the menus on the left side of the screen to click and drag out different program ''blocks. Choose Program RCX from the main menu. trying to avoid things he bumps into. Hank's program To create this program. The program assumes that the two motors are attached to outputs A and C. either the printed material or the computer-based tutorial.26 His basic program works something like this: go forward if I've bumped into something back up turn away from the obstacle start over This program translates pretty simply into the RIS programming environment. . (You can download or save a program by right-clicking on the main program block. this would be a good time to introduce them to your new toy. Figure 2-6. you should probably go back and take a look at LEGO's official documentation. If you have pets. Once you have created the program.) If everything goes right. enter the RIS software. then RCX Code. as shown in Figure 2-6. download it and run it." If you're not familiar with this process. Hank should amble around on your floor. while the touch sensors should be attached to inputs 1 and 3. you should choose a locomotion method based on what kind of terrain you're expecting your robot to encounter. read on. Treads Hank's treads have some interesting properties. I'll describe Hank's most interesting features in the rest of this chapter. but you still may run into trouble: • If your robot spins in place or goes backward instead of forward. Treads are good for driving on jagged or slippery terrain. Both treads slip on the driving surface. (I'll explain why it's a radius a little later. The large surface of the treads is one of their other assets. in which two wheels are each driven by a motor. is accomplished with a good deal of friction. but without the slipping of the treads. Hank should do pretty well driving over uneven obstacles. Tanks in Veteran's Day parades can really chew up roads this way. like a small pile of LEGO bricks. Once you've got things running smoothly. If the robot is moving backward instead of forward. Different designs have different merits . .27 Hank is a pretty simple robot. like the treads. you may need to adjust the wires that connect the motors to the outputs. however.) Each tread is driven by one of the motors. turn both wires around. the robot moves forward. and the robot will spin in place. Locomotion Hank gets around in the world on a pair of treads. Remove one of the wires and turn it 180° around. Figure 2-7 shows a top view of such a robot. • Hank may not run well on very thick carpet. If you run them both forward at the same speed. Independent drive wheels behave a lot like treads. so all you need to do to turn is move the treads in opposite directions at the same speed. like a tank or a bulldozer. The wheels are mounted on either side of the robot. This will reverse the direction of the attached motor. because there's not much space between the bottom of the body and the floor. This design also exhibits zero turning radius. Run the drive wheels in opposite directions. Foremost among these is zero turning radius. This turning. which is a fancy way of saying that a treaded robot can turn around in one place. This is just one approach to the general problem of locomotion. Differential Drive Treads are a special kind of differential drive. you can calculate with a fair degree of accuracy the location of the robot relative to its starting point.) Once you know how far each wheel on a differential drive robot has traveled. The idler wheels don't drive or steer the robot.28 Figure 2-7. An idler wheel . Figure 2-8. Figure 2-8 shows a typical idler wheel. They can turn freely to point in whatever direction the rest of the robot is moving. (You could do this using rotation sensors. Independent drive wheels Zero turning radius is nice in robots that measure how far each wheel travels. They exist to keep the robot from tipping over. with enough parts. Figure 2-9 shows how this looks. (You can't spin in place in your car. Consider Figure 2-10 again—the inside back wheel has a smaller distance to go than the outside wheel. two in front and two in back. as you'll know if you've ever tried to parallel park a car. this design does not have a zero turning radius. Whichever system you choose.29 Cars Modern automobiles demonstrate another popular approach to locomotion. Figure 2-10. The back wheels drive the robot (or car) forward and reverse. . the back wheels must turn at different speeds. The other subtlety of this design involves the back drive wheels. Cars have four wheels. But you could obviously build front-wheel drive robots.) The term turning radius comes from what happens when a car-style robot drives in circles. as shown in Figure 2-10. Turning radius of a car This type of design can be difficult to maneuver. Car-style locomotion Rear-wheel drive is simpler because it decouples the drive mechanism from the steering mechanism. Figure 2-9. while the front wheels are used for steering. When the car turns. In this scheme. Each of the wheels pivots on its vertical center. is used for steering. The tri-star wheel is another interesting idea. In this design.30 This means that you can't simply connect the two drive wheels with a shaft and hook it up to a motor. Figure 2-12 shows a side view of a tri-star robot and a close-up of the wheel assembly. A simple variation on the car design is the tricycle design. The key to building synchro drive robots is a piece called a large turntable. The first of these is synchro drive. see Appendix A. This has the interesting side effect that the robot can change direction even though its body stays oriented the same. the robot swivels the wheels to point in a new direction. instead of a pair. the robot has three or more identical wheels. as shown in Figure 2-11. Exotic Drives There are three other interesting drives that should be mentioned. Side view of the tri-star design . You can order these pieces from Pitsco® LEGO DACTA®. Figure 2-12. This property could be useful for robots that need to communicate with the computer over the IR link. a single wheel. called a differential (not the same as differential drive). All of the wheels point in the same direction. Synchro drive To turn. Finding Parts and Programming Environments. for details. You need something trickier. Figure 2-11. The shaft on the larger gear will turn more slowly but more powerfully than the shaft on the smaller gear. You can trade speed for power by using a small gear to drive a larger gear. The bumper needs to trigger the touch sensor when the robot bumps into something. A slightly different approach is to make a bumper that is held tightly against the sensor. Instead. and so forth. it should not trigger the touch sensor when the robot starts or stops moving abruptly or when it's driving over a bumpy surface. Gears have three primary purposes: 1. the entire wheel assembly rolls on its center axis. trees. A gear. On the other hand. Gears Gears are clever mechanical devices that can be used to trade speed for power or to translate motion from one axis to another. It's really too exotic to describe here. walls. 2. The robot drives these wheels to move. because then it could be activated only in one specific spot. When the bumper collides with something. But it's not really enough to put a touch sensor just on the front of your robot. rocks. The trick with bumpers is to make them sensitive but not too sensitive. When the bumper is pressed anywhere along its length. When a large obstacle (like a step) is encountered. pets. the touch sensor is then also pressed. This large wheel size enables the tri-star design to drive over large obstacles. . the sensor actually turns off instead of on. It has a space in its center where you can put a shaft. In essence. The idea of a bumper is to make a large area sensitive to touch so that the robot can detect collisions with a wide variety of objects . The shaft on the smaller gear will turn faster than the one on the larger gear. is a disk with teeth on its edge.chair legs. Hank uses bumpers that rest lightly against the touch sensors. the "Online Resources" lists two web pages that contain photographs and diagrams of this platform. Hank uses a pair of bumpers to detect touches across the entire front of the robot. The opposite effect—trading power for speed—occurs if you use a large gear to drive a smaller gear. in essence. Killough's platform is an interesting variation on the wheels-within-a-wheel concept. the entire wheel assembly acts like a large triangular wheel. Bumpers and Feelers Hank uses the touch sensors to figure out when he bumps into something.31 Each wheel assembly is actually composed of three wheels arranged in a triangular fashion. but with less power. you'll need to anchor it down somehow. There's no way to turn the other gear and have it translate to motion in the worm gear. for example. gears are named based on the number of teeth they have. The 40t gear. The gears in the bottom row of Figure 2-3 can be used to transfer motion between perpendicular axes. 16t. Figure 2-13. Using gears to transfer motion The Palette of LEGO Gears LEGO offers an impressive array of gears. Specialty Gears You're probably comfortable with the 8t. They can be put together to transfer rotational motion from one axis to another. The worm gear is a real character. and 40t gears. 2. The worm gear really works only one way: you drive the worm gear. In particular. You can use gears to transfer motion from one axis to another. The gears in Hank's body transfer motion from the motors to the drive axles of the treads. For the most part. . and it drives another gear. for two reasons: 1. it shows the gears that come with RIS and their names. The LEGO community has adopted names for these gears. Refer back to Figure 2-3. as shown in Figure 2-13. so the 24t gear has a radius exactly three times as large as the 8t gear. 24t. has 40 teeth.32 3. The number of teeth is directly proportional to the gear's radius. which I will use throughout this book. these gears are used to transfer motion between parallel axes. Two of these are bevel and crown gears. If you want it to stay in one place. While the other gears attach firmly to the shaft. the worm gear can slide freely along the shaft. which is a measure of the power in a turning shaft: τ = Fr In this case. it's easy to figure out the ratios of torque and angular velocity for two mating gears. the angular velocity of the 24t gear is exactly one third of the angular velocity of the 8t gear. For the example I just described (an 8t gear driving a 24t gear). then. Here's the equation for torque. .33 Do the Math The mathematics of gears can be described in a high school physics class. This is the same as the radius of the gear. and r is the distance from the center of the rotation to the point where the force is applied. just by figuring out the ratios of gear teeth. For a gear. F is force. that you have an 8t gear driving a 24t gear. this is the distance from the center (where the shaft runs through) to the teeth. The angular velocity of a shaft can be expressed in terms of the velocity of a point on the gear as follows: ω= v r Here. ω is the angular velocity. If you use an 8t gear to drive a 40t gear. then. τ is torque. The two important equations have to do with torque and angular velocity. The force is the same where the teeth of the two gears meet. you'll end up with fives times the torque and one fifth the angular velocity. You can figure this out because the velocities of the gear teeth must be the same: ω8 = v r v ω8 = 3r 3 ω 24 = In general. v is the velocity of the point on the gear. Suppose. the torque on the shaft on the 24t gear is exactly three times the torque on the 8t gear's shaft: τ 24 = 3Fr = 3τ 8 Angular velocity is the measure of how fast a shaft rotates. Therefore. The equation for the torque of the 8t gear's shaft is this: τ 8 = Fr The radius of the 24t gear is exactly three times the radius of the 8t gear. and r is the distance between the point and the center of the gear. They are more efficient than the standard motor. It is an ungeared motor. when electricity is applied. Figure 2-14. you'll probably have to use gears to reduce its output speed. The geared motor . Most electric motors turn too fast and with too little power to be useful. Gears are usually used to swap speed for power until a good balance is achieved. but it could be useful for lighter tasks. which means its output shaft rotates very rapidly. To do any useful work with it. The geared motor is shown in Figure 2-14. They are internally geared so that the output shaft has enough power to drive your robot around. This process is called gearing down or gear reduction. geared motor Two of these motors come with the MINDSTORMS RIS kit. It's harder to find than the other motors. micro motor This is a tiny motor with low speed and low power. which means that the motor case actually contains an electric motor and some number of gears. This means you can attach wheels directly to these motors to drive your robot around. with little power. You probably can't use this motor to move your robot.34 Of Geared and Ungeared Motors There's one more topic related to gears that's important. The output shaft is already adjusted to turn at a reasonable speed with a reasonable amount of power. The motors that come with RIS are internally geared. The LEGO group makes four different kinds of motors that can be driven from the outputs of the RCX: standard motor This has been the standard motor of the LEGO TECHNIC line for many years. The train motor can be controlled by your RCX. where it's converted back to the movement of the shaft. Use one of the "wire bricks" to attach two motors to each other. and less bulky than the standard motor. This service is available in the United States at (800) 835-4386. . What's going on here? Just as you can supply power to make the motor turn. as a matter of fact. The shaft on the second motor turns at nearly the same speed as the first motor. You can get another motor in the RoboSports expansion set. For a Rainy Day To see exactly how efficient the geared motors are. You can order extra motors from the LEGO Shop-at-Home service. one of The LEGO Group's best-kept secrets. you can make an "intelligent" train by mounting the RCX in one of the cars. but there are three outputs on the RCX. item 5225 • Train motor. item 5300 You can also order the first three motors from Pitsco LEGO DACTA: (800) 362-4308. Of course.35 train motor LEGO sells an entire line of train sets. you haven't actually built anything useful. They have a variety of sets and spare parts—the item numbers for the motors are as follows: • Standard motor. item 5119 • Geared motor. The micro motor is hard to find and not strong enough for most tasks. try this experiment. which means very little energy is lost in converting mechanical energy to electrical energy and vice versa. When you turn the shaft of one motor. more convenient. This power is transferred to the other motor. It is more efficient. see Appendix A. you'll probably always use a geared motor. How can you get more motors? RIS comes with two motors. But it's a good demonstration of the efficiency of these motors. For more information on extra parts and ordering. If you have a choice of motors. the other motor's shaft will turn simultaneously. but it'll cost you $50. item 5114 • Micro motor. turning the motor with your hand generates power. the robot backs up. you could try putting in longer delay times in Hank's program. This is a term from the computer world—it just means that the RCX can do more than one thing at a time. When one of the bumpers is touched. turns. one of the alternate programming environments for the RCX. while the watcher code is still executing. Tasks and subroutines are declared explicitly in NQC. Not Quite C. and they can actually execute at the same time.) The sensor watchers in RCX Code exhibit another interesting property. The main program starts Hank moving forward. the watcher code starts over again from the beginning. for details. See Chapter 4. A slightly dangerous program . touch one of Hank's bumpers to trigger the first task. Figure 2-15. waits. At first glance. it makes sense. Figure 2-15 shows how the multitasking nature of the RCX can get you into trouble. If you trigger a sensor watcher. then touch the other bumper shortly afterward. If you trigger the same sensor watcher again. Each of the two instruction sequences hanging off the touch sensor watchers is a separate task. To see this in action.36 Multitasking Don't be fooled by the simplicity of the RIS programming environment—it hides some pretty messy details. waits. The figure shows an alternate program for Hank. (To really see this effect. the code for that watcher begins executing. and starts going forward. Hank's simple program demonstrates a powerful feature of the RCX software: multitasking. The relationship between the programs you create in RCX Code and the tasks that run on the RCX is not always clear. For sheer mechanical finesse.pd This is an outstanding paper about building with LEGO parts. It doesn't matter if the sensor watchers are interrupted before they finish. it is a real bonanza of information and advice. that the bumper on input 1 is triggered again. First.mit. Finally. you can be more explicit about controlling outputs. for example. and the robot spins in place again. instead of moving forward.media. will begin spinning the other direction instead of moving backwards.edu/people/fredm/projects/6270/ For a deeper treatment of many aspects of small mobile robotics.net-info. now. The sensor watcher routine will begin again. Hank. The robot travels backwards for half a second. this page is hard to beat. and the Killough platform. I highly recommend this paper.37 A serious problem occurs if the same bumper is quickly hit twice. In this class. in Figure 2-6.media. It includes helpful tips on making strong structures and using gears. students build robots from the ground up. It begins executing its sensor watcher code by reversing the direction of the motors. Instead of just reversing the output directions in the sensor watcher routines. they will be much less likely to be interrupted. read the course guide for MIT's famous 6.270 Home Page. reversing the direction of both the motors. and the robot moves forward. you could specifically set the directions and turn on the motors. Doug's LEGO Technic Tri-Star Wheel ATV and Robotics page. output C's direction reverses.270 Robot Builder's Guide was written by Fred Martin.edu/pub/people/fredm/artoflego. because the directions of the motors are always set explicitly. This technique is shown in Hank's first program. Suppose the bumper on input 1 is hit once. then output A reverses direction and the robot spins in place. therefore.mit. one of the people at the MIT Media Lab whose programmable brick work formed the basis of the RCX. before output C's direction is reversed again. Suppose.270 class. The 6. Then output A's direction reverses. Online Resources The Art of LEGO Design. There are two solutions to this problem. If your sensor watchers don't have any delays built into them. Doug Carlson's fascinating page is full of pictures of his implementations of the tri-star design. The paper is written by Fred Martin. Fred's 6. . especially if you are having trouble getting things to fit together. synchro drive. The other solution is to structure your program differently. but you can call and order a catalog.38 Killough's mobile robot platform This page has photographs of my own synchro drive robot. which has three wheels and a compact design. Dacta Spares from Pitsco. Many of the interesting things that Pitsco LEGO DACTA sells are not listed online.nl/~leo/lego/killough.com/jknudsen/Synchronicity/Synchronicity.wins. Pitsco LEGO DACTA This unofficial site contains images of some of the interesting pages in the Pitsco LEGO DACTA catalog.html This part of Leo Dorst's acclaimed site gives some background and explanation of the Killough platform.edu/~jmathis/dacta. This is the place to order the Robolab software that allows you to program your RCX from a Macintosh. LEGO Motors. as Pitsco has an entirely different catalog that doesn't have anything to do with LEGO.uva.com/~dbaum/lego/motors.com/ This is the official home page of Pitsco LEGO DACTA. Synchronicity. including the pages with the motors and sensors. . Make sure you get the LEGO DACTA catalog.html This page contains a concise description of the three kinds of motors.ee.enteract. shown in Figure 3-1. a Line Follower In this chapter: Building Instructions Some Tricky Programming The Light Sensor Idler Wheels Using Two Light Sensors Online Resources In this chapter. you'll build Trusty. Trusty will follow the large black oval on this paper faithfully until he runs out of battery power. The light sensor can distinguish between the white background of the Test Pad and the black line drawn on it. a line follower As you can see in Figure 3-1. As . can drive along a sort of ''track" defined by a thick black line on the floor. Figure 3-1. This means that Trusty. a simple robot that exhibits a behavior called line following. Your RIS kit includes a "Test Pad.39 3 Trusty." which is simply a large piece of white paper with some black lines and other marks on it. This sensor is the key to line following. Trusty. Trusty's main feature is a downward pointing light sensor. this feature doesn't make line following easy to program.40 you'll discover. Building Instructions . but it does make it possible. .41 In Step 4. the idler wheel will be locked in place. make sure the top bushing allows the idler wheel to rotate freely by putting the round side next to the plate. If you put it on the other way. Be sure to attach the wire bricks to the motors before putting them on Trusty. build the support for the light sensor.42 Next. . 43 The 2u beams between the motors will hold the ends of the drive shafts. Make sure that you can see the holes. . as we discussed in Chapter 1. (A lot of things in mobile robotics are urprisingly hard.) The simplest way to describe the program is this: . Some Tricky Programming It's surprisingly hard to convince our robot to follow a black line on the floor. Robotics and MINDSTORMS. while the light sensor is attached to input 2. The motors are attached to output A and output C.44 Flip the robot over and attach the wires as shown. 45 if I'm on the line, go straight forward if I'm off the line, find the line and start over It's the "find the line" part that's difficult. When Trusty's light sensor goes off the black line, Trusty has no way of knowing if he's on the right or the left side of the line. Ideally, Trusty would turn back to the line and start going straight again. He would proceed in a zigzag fashion along the line. State Even if Trusty doesn't know which side of the line he's on, he can make a pretty good guess. If he knows he drove off the left side of the line last time, it's a pretty good bet he'll drive off the right side the next time. Figure 3-2 shows a likely path as Trusty tries to stay on the line. Figure 3-2. Trusty zigzags along the black line With this in mind, Trusty's algorithm can be more specific: if I'm on the line, go straight forward if I'm off the line { turn back the opposite direction from the way I turned last time if I still don't find the line, turn farther back the other direction } Another way of looking at this is to say that Trusty now has two possible states: 1. Just turned left (turn right next) 2. Just turned right (turn left next) By keeping track of this state, Trusty can figure out the best way to turn the next time he drives off the black line. Could I Please Have a Variable? Some kind of variable is needed if Trusty is to keep track of his state. Said another way, Trusty needs some kind of memory to remember which way he last turned. This highlights one of the weak points of RCX Code (the RIS programming environment), its lack of variables. 46 The environment does provide a counter, which we'll use in lieu of a variable to hold the turning direction. Although you can't assign values directly to the counter, you can do two things: reset it to zero and add one to it. Trusty will use just two values, 0 and 1, to mean turn left and turn right, respectively. Coping with Failure Our basic assumption about Trusty is that he will drive off the black line on alternating sides. But this probably won't really happen all the time, particularly if the black line has curves in it. What Trusty needs is some way to figure out if he's turning the wrong way, away from the line instead of toward it. For this purpose, we'll use a timer. If Trusty doesn't find the line within a certain time interval, we'll have him switch state and turn back the other way. The real world is a very challenging place. You should always assume that bad things will happen to your robot and try to create a program that responds appropriately. The Program Figure 3-3 shows Trusty's basic program. It begins by setting the two motors to the forward direction at speed 4. The central decision point is the light sensor watcher. If the sensor sees the black line, Trusty moves straight ahead. If the sensor sees the white background, then the program resets the timer and calls a subroutine called toggle. This subroutine turns the robot left or right, alternating each time it is called. Figure 3-3. A top-level view of Trusty's software 47 Use your own values for the thresholds of the light sensor watcher. The values shown in Figure 3-3 are calibrated to my particular light sensor and may not work with yours. The timer is used in case Trusty happens to turn the wrong way. Suppose, for example, that he runs off the right side of the black line twice in a row. The first time, he would turn left to find the line again. The second time, however, he would turn right, away from the line. The timer is used to limit this behavior. If Trusty is turning and the timer goes off, then Trusty automatically turns back the other way. Figure 3-4 shows the timer watcher, which calls the same toggle subroutine if the robot is still off the line. You might be wondering why the timer counts for one half second. Why not three quarters of a second, or a full second? Remember that the timer keeps Trusty from turning around completely. The timer value is based on observation—if Trusty is turning toward the line, he will find it within a half second. If he is turning away from the line, he can be pretty sure he's missed it after a half second. A line-follower with a different mechanical design might need a different timer value. Figure 3-4. Details of Trusty's software Figure 3-4 also shows the toggle subroutine itself. All it does is examine the value of the counter. If it's 0, then the robot is set to turn left and the counter value is changed to 1. The next time toggle is called, the robot turns right and the counter value is reset to 0. It's useful to have toggle as a subroutine because it is called from two places in Trusty's program. 48 The Light Sensor Working with the light sensor can be a little tricky. As measured by the RCX, the light sensor outputs a value from 0 (dark) to 100 (bright). However, the signal generated by the sensor has some noise in it, which means the value jumps around unpredictably. To use a light sensor effectively, then, you need to figure out what the interesting values are and how to respond to them. Testing Light Sensor Values The easiest way to figure out what values your light sensor is generating is to use the RCX's View button. Press View repeatedly until a little arrow appears under the input with the sensor. The RCX's screen should show the value of the sensor. You can place Trusty so the light sensor is over the line, and then observe the value. Now see what values you get when Trusty is off the line. You should also try the green area of the Test Pad, and try all the measurements with the room both dark and light. This should give you a good feel for the values that are important. The View button only works if the input is configured to measure a light sensor. To have the input configured correctly, you'll either have to run a program that sets it up or use the Test Panel, in the RCX Code section of the RIS software. Click on the appropriate input until the light sensor appears. Then click on the Get Sensor Values button to get the current readings. The choice of 35 and 40 in Trusty's program is based on my measurements; you may want to adjust these values for your specific conditions. Don't expect to get the same readings from two different light sensors, even under the same conditions with the same RCX. Always test the values before you use them in a program. The Light Sensor Watcher What's going on with that sensor watcher in Figure 3-3? It's actually two sensor watchers rolled into one. The following pseudocode shows how it works: if the sensor execute if the sensor execute value is in the range from 0 to 35 (but wasn't previously), the "dark" commands value is in the range from 40 to 100 (but wasn't previously), the "bright" commands 49 Figure 3-5 shows a hypothetical graph of the light sensor value, along with the times when the dark and bright commands will be executed. Nothing happens until the sensor value enters either the dark or bright value ranges. Figure 3-5. The sensor watcher Remember that the RCX runs some tasks at the same time. If the dark commands and bright commands both take a while to execute, it's possible they may overlap. If the light sensor reading gets into the bright range and abruptly drops back into the dark range, the dark commands will start running while the bright commands are still in progress. You should be aware of this possibility and structure your code to deal with it. In Trusty's program, the dark and bright commands both execute quickly so they won't overlap. Ambient Light You have to be careful with the light sensor; its value depends on all the light it receives. This includes the reflected light from the red light that's part of the sensor as well as room light and sunlight.∗ In a line-following robot like Trusty, you really want to measure only the reflected light. In this case, it's in your interests to block out the room lighting, sunlight, light from your kid brother's flashlight, and anything else distracting. The light level that's present in a certain place is called the ambient light. In a robot like Trusty, you might try surround the light sensor with dark bricks to block out the ambient light. This can improve the accuracy of your sensor measurements. In this particular case, I didn't think it was necessary, but you might like to give it a whirl. ∗ The light sensor is even sensitive to the infrared light that is produced from the IR port. It repeats this cycle over and over. Adding the Sensor To add the second light sensor to Trusty. In an alternate firmware such as legOS.) Inside the light sensor. twitching. By adding one more light sensor to Trusty. has a red light on it? How did that happen? And how is that possible with only two wires connecting the sensor to the RCX? The basic role of the RCX's inputs is to measure the value of the sensor. or turns. An idler wheel provides support for the robot but doesn't constrain its motion. You can leave the original one attached to input 2 and just add the second one to input 3. Figure 3-6 shows how to do this. Ideally. an idler wheel can easily swivel in response to changes in the robot's direction. the idler wheel broke off the bottom. the RCX also provides power to the sensor. Make your idler wheels sturdy! One of Trusty's early designs could follow a line just fine. It does this by very quickly alternating between providing power and taking a measurement. For certain types of sensors. Using Two Light Sensors You can buy more light sensors for about $20US each (see the ''Online Resources" section at the end of this chapter). But after about a minute of backand-forth turning. an input device. just move over the one that's already there. as are the casters under furniture.1 ms. You've already seen Trusty's idler wheel in Figure 2-8. and Trusty was left lying on his back.50 Where's That Red Light Coming From. It does this by rotating freely on a vertical axis. Trusty's third wheel is a good example of an idler wheel. (These timings only apply to the standard firmware. an electronic circuit smooths out the pulses and provides steady power to the red light. like the light sensor. Anyhow? Isn't it odd that the light sensor. we can simplify his program and make his movement along the black line smoother. Trusty can't balance and will tip forward or backward. . the timings are entirely different. backward. The front wheels on shopping carts are idler wheels. Idler Wheels Trusty's two main drive wheels determine whether he moves forward. But without at least one more wheel. The RCX sends power to the light sensor for about 3 ms (thousandths of a second) and takes a measurement for about . Adding a second light sensor to Trusty Programming With two side-by-side light sensors. the robot must already be turning and should return to the line soon. If both sensors go off the line. the value of the other is examined. If both sensors are on the line. . the motors are set according to Table 3-1. we don't do anything. In Chapter 4. Table 3-1. Based on the values of the two sensors. This logic can be represented by a simple map from the sensor values to the motor settings. Whenever either sensor sees light or dark. Mapping from Sensor Inputs to Motor Outputs Left Light Sensor (2) dark dark bright bright Right Light Left Motor(A) Right Motor(C) Sensor (3) dark bright dark bright forward stop forward forward forward stop Result Go forward Turn left Turn right No change It's cumbersome to implement this algorithm in RCX Code. one for each light sensor.51 Figure 3-6. which is based around two sensor watchers. I'll show you how this algorithm (as well as the single-light-sensor Trusty) can be reprogrammed in NQC. If only one of the sensors is on the line. The program centers around two sensor watchers. But go ahead and try it out. Figure 3-7 shows the program. Trusty's algorithm is pretty simple. as shown in Table 3-1. it works well even if it looks kind of strange. we simply turn back to the line. we just drive forward. and even a remote control that sends messages to the RCX's IR port.com/usr/gasperi/light. You can even buy an extra RCX. although you can probably get it cheaper at a local retailer. It includes a photograph of the circuit board inside the sensor. although it's a much better value to spring for a whole RIS kit. . and photographs. touch sensors. It describes how the sensors work.com/usr/gasperi/lego. However. LEGO Light Sensor. how you can modify sensors. It includes schematic diagrams. Programming Trusty with two light sensors Online Resources LEGO World Shop. handy graphs. light sensors. a schematic diagram. like extra motors. LEGO MINDSTORMS Sensor Input. the online store also carries items you won't find locally.htm This is the authoritative resource for RCX sensor information.htm For the real skinny on LEGO's light sensor.52 Figure 3-7.plazaearth.plazaearth.legoworldshop.com/ The RIS kit itself is available at this online store. check out this page. and how you can build your own sensors. and graphs of the sensor's response with and without the LED. with copious . The counter was always a 0 or a 1. But it's tough going. Most of this software is available. But RIS is exceedingly popular with programmers and other technically savvy people. who are frustrated by the limitations of RCX Code. I'll describe the syntax and commands of this language. Likewise. The LEGO Group aimed the Robotics Invention System at people who had never programmed before. to be able to show values on the display. In this chapter. indicating whether the robot should turn left or right. It would be nice if your robot could remember things. it feels a little constrictive. on the Internet. the counter is not going to get the job done. NQC allows you to write programs for your RCX with a text-based language. In RCX Code. the only thing remotely resembling a variable is the counter. The lack of variables is only one of the limitations of RCX Code. a Line Follower. Two other important limitations are: • Although you can define subroutines (called "My Commands"). free of charge. I'll describe one of the most popular packages: Not Quite C (NQC). Back in Chapter 3. this probably includes you. It would be really nice. you can't call one subroutine from another. for debugging purposes. Since RIS was released in the Fall of 1998. there aren't any variables. a subroutine can't call itself. I used the counter to remember which way to turn. For this group. • You can't control the RCX's display very well. Trusty. RCX Code is a gentle way to get started with programming mobile robots. the MINDSTORMS community has produced an amazing stream of clever. like how many obstacles it's encountered or what the temperature was three minutes ago. For one thing.53 4 Not Quite C In this chapter: • A Quick Start • RCX Software Architecture • NQC Overview • Trusty Revisited • Online Resources Once you've written a few programs in RCX Code. innovative software designed to overcome the limitations of RCX Code. If you're reading this chapter. and if you try anything more complicated. com/~dbaum/lego/nqc/ ). 4.0b1. this chapter contains software for Trusty written in NQC. OnFwd(OUT_C). NQC will look familiar. you need to understand the software that's running on the RCX. Wait(TURN_TIME). This chapter provides a detailed listing of NQC's commands. OnFwd(OUT_A). OnFwd(OUT_A). this chapter begins with a simple example. SENSOR_TOUCH). the robot from Chapter 2. enter the following program using a text editor. If you have never programmed in C. } } } . and follow the instructions to download and install the latest version. Linux. SetSensor(SENSOR_3. Hank. Wait(TURN_TIME). Navigate to the NQC web site (. Once it's installed. This chapter presents NQC in four steps: 1. To get you started with NQC. Save the program in a file called Hank. 3. If you've programmed in C. #define BACK_TIME 50 #define TURN_TIME 80 task main() { SetSensor(SENSOR_1. with examples. To understand how NQC works. Finally. 2. and Windows. NQC is easy to learn.54 examples. This chapter describes the important pieces of the RCX's software architecture. you'll need to download and install NQC. don't worry. OnRev(OUT_A + OUT_C). the Bumper Tank.nqc. It's available for MacOS. OnFwd(OUT_C). OnFwd(OUT_A + OUT_C).enteract. The examples in this book were written with the NQC version 2. This program operates Hank. } if (SENSOR_3 == 1) { PlayTone(880. SENSOR_TOUCH). Wait(BACK_TIME). First. 50). while (true) { if (SENSOR_1 == 1) { PlayTone(440. Wait(BACK_TIME). OnRev(OUT_A + OUT_C). 50). A Quick Start Let's get right to the good stuff with a working example. RCX software architecture ROM The RCX is a small computer that is based on a Hitachi H8/3292 microcontroller. RCX Software Architecture Writing a program for the RCX involves a handful of software layers. use the -S option. Figure 4-1 shows an overview of the important pieces. nqc gives you a list of errors. come back and get some background on the software that runs the RCX.nqc C:\> If you made a mistake typing in the program. The RCX contains two kinds of memory: Read Only Memory (ROM) and Random .55 Now compile the source code using the nqc command: C:\>nqc Hank. Otherwise. Figure 4-1.nqc Downloading Program:….complete c:\> (If you need to specify a serial port different from the default.. both on the development PC and on the RCX itself. you're ready to download the program with the -d option: c:\>nqc -d Hank.) Go ahead and run the program. When you're done playing. the contents of the RAM are erased.ocx to download the programs to the RCX. download firmware to the RCX. It also provides a way for programs to be downloaded.ocx handles interaction with the RCX via the IR link. It can recognize an respond to the View button. such as "turn output 2 on with full power. It provides the click-and-drag programming environment that you're already familiar with. It shows a clock on the display of the RCX. The RCX Code programming environment sits on top of Spirit. The actual robot programs are not H8 machine code. The firmware is. It provides access to the RCX's inputs and outputs. stored. the batteries preserve the contents of the RAM. RAM." bytecode instructions are more powerful. essentially. a piece of software called Spirit. It is programmed at the factory and cannot be changed. and stopped. These routines can run the motors or access the sensors. Most importantly. Spirit. Spirit. The RCX's ROM routines know a little bit about the RCX's hardware. Together with the H8 machine code in ROM. this is not the case. Most importantly." The firmware interprets the bytecode and performs the appropriate action. Under normal circumstances. When you first get your RCX.ocx. an operating system for your RCX. however. which means its functions are accessible from programming languages like Visual Basic and Visual C++. . ROM cannot be written. the firmware defines an operating system for the RCX. it has some stuff in ROM and an empty RAM. such as "move this value to register 1. The firmware is actual Hitachi H8 machine code. and receive data from the RCX. with one catch: it needs power. RCX Code converts these graphic programs into bytecode and uses Spirit.56 Access Memory (RAM). Although at first it sounds like the firmware and the robot programs are the same kind of animal. on the other hand. As its name implies. can be written and read as many times as you want.ocx can execute bytecode commands on the RCX. it can receive robot programs over the IR port and run them. Whereas the H8 machine instructions are very rudimentary. download new programs to the RCX. If you take the batteries out of your RCX. They are defined at a higher level called bytecode.ocx On the PC side.ocx is a regular ActiveX control. started. The firmware is capable of more than just processing the ROM routines. the ROM routines know how to receive code from the IR port and place it in RAM. About Spirit. Firmware One of the first things you have to do with your RCX is download the firmware. The routines in ROM know how to download a set of firmware from the IR port and store it in RAM. 57 Spruce Up That Resume Writing programs for the RCX is an example of cross-compiling for an embedded system. microwave ovens and mobile phones both contain embedded systems. RCX Code uses Spirit. 3. programs are downloaded to the RCX over the IR link and stored in RAM. First. The program is now available in RAM. Second. particularly for people who haven't programmed before. The cross-compilation step is a little different. RCX Code compiles your program to bytecode. The RIS software simplifies this process in two important ways. because RCX programs are bytecode rather than machine code. For example. When the embedded system boots up. The final step would be to physically place the memory chip in the embedded system. 2. The usual way to develop software for a chip like the Hitachi H8 would be to use a cross compiler running on a PC. . An embedded system is a computer that is part of some other device. the firmware interprets the bytecode in your program and performs the appropriate tasks. Then you would probably use a special PC peripheral. The program's life begins when you create something in RCX Code. When you run it. to place the machine code on some sort of programmable memory chip.ocx to download the program to one of the RCX's five program slots. the software you just wrote will run. too. called a burner. You would write source code (probably in C or assembly language) on your PC and use the cross-compiler to create H8 machine code from the source. a phrase that is bound to sound good on your resume. Cross-compiling means that you are writing programs on one computer (your PC) that will run on another computer (the RCX). This feature eliminates the complexity of dealing with memory chips and burners yourself. as well. it provides a graphic programming environment that's very accessible. A Day in the Life of a Program Let's examine the typical life of a robot program: 1. But it's still cross-compilation: the end result is bytecode rather than H8 machine code. Modern cars contain dozens of embedded systems. The compiled bytecode is transferred to the RCX via the IR link. Although NQC is fairly easy to use all by itself. I've included lots of example programs to demonstrate how things work. Because NQC talks to the IR tower directly. If you define other tasks. ∗ As this book goes to press. Now you can run NQC on MacOs without MPW. When the Run button is pressed. His web site also includes pithy documentation for the language. I won't cover NQC exhaustively. This chapter covers the important commands of NQC. Every program should have a special tasks called main. several excellent web pages detail the entire language. The main task is the only one that is automatically run by the RCX. If you're using NQC on Windows. NQC runs on MacOS (using MPW). . the RCX begins the program by running main. you have to explicitly start and stop them. C++. the syntax and control structures will look familiar. main NQC programs are organized into one or more tasks. a standalone MacOS version of NQC is being released in beta test form. RCX Code. real-time control of the RCX. NQC source code is stored in simple text files. you might want to also use RCX Command Center (RcxCC). by contrast. A task is simply some set of instructions that execute in order. push-button compilation and downloading. who maintains the official web site at. both RCX Code and Spirit. or Java source code.ocx.ocx. RcxCC is a Windows application that wraps around NQC. RcxCC gives you an even smoother ride.∗ NQC was developed by Dave Baum. A single program may consist of several tasks that execute at the same time. it is very portable. just like C. and NT. NQC compiles these source files to bytecode and can download them to the RCX using the IR tower. See the "Online Resources" section at the end of this chapter for details. and a host of other useful features. and of course Windows 95. without depending on Spirit. If you have a background in C programming. don't worry: NQC is easy to learn. A task is analogous to a thread in other programming environments. See the "Online Resources" at the end of this chapter for a URL and more information. Linux. It provides a syntax-colored program editor. NQC is a good way to overcome the limitations of RCX Code. But because it produces bytecode programs.enteract. I'll explain more about starting and stopping tasks later. only runs on Windows. Tasks have names. 98.com/~dbaum/lego/nqc/. If you don't have a background in C.58 NQC Overview Where does NQC fit in? NQC is a replacement for the software on the PC. it's still subject to the limitations of the firmware's bytecode interpreter. No power is sent to the output. The outputs should be some combination of the constant values OUT_A. calling On()is enough to get the motors running. NQC provides two handy "combination" commands: OnFwd(const outputs) This command turns on the specified outputs in the forward direction. . You've already seen one of these. and power explicitly. in our first simple example. but the shaft of an attached motor will turn freely. Multiple outputs can be specified by adding them together. Toggle(const outputs) To switch the direction of one or more outputs. expression speed) This command sets the power of the given outputs. OUT_HALF (4). OUT_B. You can set the direction of outputs with the following three commands: Fwd(const outputs) Use this command to set the direction of the specified outputs to forward. This is a useful option if you want your robot to coast to a stop. all three outputs are set to full power and the forward direction. and OUT_C. use this command. OnRev(const outputs) This command turns on the specified outputs in the reverse direction. OnFwd. you should set its mode. Therefore. On(const outputs) This command turns on the specified outputs. For motors. putting them in brake mode. You may use the constant values OUT_LOW (1). and OUT_FULL (7) if you desire. its current power and direction are consulted to determine what actually happens. Rev(const outputs) This command sets the direction of the specified outputs to reverse. Any expression that evaluates to a value from one to seven can be used as the speed. Off(const outputs) This command turns off the specified outputs. When an output is turned on. To determine the output power. as shown in the first example.59 Output Commands NQC includes several commands for controlling the outputs of the RCX. To fully determine an output's actions. direction. By default. Float(const outputs) Float() is really a variation of Off(). use the following command: SetPower(const outputs. this means that the motor shaft will be hard to turn. If you explicitly set the directions of your outputs. the outputs are turned off. Off(). your program will be clearer. 100). Input Commands Before you can read a value from one of the RCX's inputs. Rev(). but you should still set the power level explicitly with a call to SetPower(). waits one second. your program is more likely to behave as you expect. In general. 100). and Toggle() commands are really shorthand for these lower-level output commands: SetOutput(const outputs. expression time) This command turns on the specified outputs for the given time. Rev(OUT_A + OUT_C). After another second. or OUT_TOGGLE. OnFor(OUT_A + OUT_C. measured in hundredths of a second. Float(). you need to tell the RCX what type of sensor is attached to the input. Fwd(OUT_A + OUT_C). const direction) This command determines the direction of the supplied outputs. For timed actions. and OUT_FLOAT. the following command will come in handy: OnFor(const outputs. } The On(). I recommend you don't call SetDirection() with the OUT_TOGGLE value. Furthermore. then reverses outputs A and C. NQC provides a command that does just this: . Fwd(). OUT_REV. Then the given outputs are turned off (in brake mode. OUT_OFF. in programs with more than one task.60 These commands set the mode and direction of the outputs in one fell swoop. The outputs are specified in the same way as in the Fwd() and Rev() commands. The following example runs outputs A and C forward. OnFor(OUT_A + OUT_C. not in float mode). OUT_TOGGLE is a special value that sets the direction of the output to the opposite of its current value. OUT_HALF). task main() { SetPower(OUT_A + OUT_C. const mode) This command sets the mode for the given outputs. The direction parameter should be OUT_FWD. SetDirection(const outputs. The value of mode should be one of the constants OUT_ON. The SENSOR_PULSE configuration counts the times the touch sensor has been pressed. which lists the sensors that are available for the RCX. for input 1. which represent the three inputs of the RCX. The values returned from an input depend on the input's configuration and are described in Table 4-1. or 2. Table 4-1. Their first purpose is to identify the inputs on the RCX to commands like SetSensor(). and SENSOR_3. The SENSOR_PULSE and SENSOR_EDGE configurations are variations on SENSOR_TOUCH. and SENSOR_3.61 SetSensor(expression sensor. Valid values for sensor are SENSOR_1. These are shorthand for the following command: SensorValue(const input) This command returns the current value of the given input. SENSOR_2. and SENSOR_3. SENSOR_2. the input value is the accumulated count. while SENSOR_EDGE counts the transitions from on to off and from off to on. SENSOR_1. SENSOR_2. Finding Parts and Programming Environments. The sensor configurations are detailed in Table 4-1. . The configurations that keep a count can be reset with a call to ClearSensor() (as shown in Table 4-1): ClearSensor(expression sensor) This command resets the current count for the given input to 0. there are two distinct uses for SENSOR_1. Their second purpose is to retrieve values from the inputs. 1. input 2. and input 3 respectively. and SENSOR_3 actually have a dual purpose in life. See Appendix A. NQC Sensor Modes Configuration SENSOR_TOUCH SENSOR_LIGHT SENSOR_ROTATION SENSOR_CELSIUS SENSOR_FAHRENHEIT SENSOR_PULSE SENSOR_EDGE Sensor Touch Light Rotation Temperature Temperature Touch Touch Type Input 1 (pressed) or 0 (not pressed) 0 (dark) to 100 (bright) 16 units per full rotation Celsius degrees times 10 Fahrenheit degrees times 10 Count of presses Count of state transitions Value ClearSensor() yes yes yes The actual sensor value can be read using SENSOR_1. Thus. When you read the value of an input in one of these configurations. which should be 0. SENSOR_2. const configuration) This command tells the RCX how to configure the given input. 62 Edges and Pulses If you examine the output of a touch sensor. ClearSensor(SENSOR_1). it looks something like this: The transitions from 0 to 1 and from 1 to 0 are called edges. while a transition from 1 to 0 is a falling edge. If it is 4. The input type describes the electrical characteristics of the attached sensor. SENSOR_PULSE is a little more selective—it counts rising edges only. repeatedly testing the value of input 1. task main() { SetSensor(SENSOR_1. A transition from 0 to 1 is a rising edge. a sound is played. rising or falling. It begins by configuring input 1 to count touch presses with the SENSOR_PULSE configuration. The SENSOR_EDGE configuration counts all edges. If you need finer control over the inputs than you can get from SetSensor(). and the count for input 1 is reset. over time. use the SetSensorType() and SetSensorMode() commands: . while(true) { if (SENSOR_1 == 4) { PlaySound(SOUND_DOWN). Then it enters an endless loop. } } } The SetSensor() command actually configures an input's type and mode at the same time. SENSOR_PULSE). while the mode determines how the sensor values are interpreted. The following example plays a sound after every fourth press on the touch sensor. Input Mode Constants Mode Constant SENSOR_MODE_RAW SENSOR_MODE_BOOL SENSOR_MODE_EDGE SENSOR_MODE_PULSE SENSOR_MODE_PERCENT SENSOR_MODE_CELSIUS SENSOR_MODE_FAHRENHEIT SENSOR_MODE_ROTATION Description Raw sensor value from 0 to 1023 Either 1 or 0 Counts transitions from 1 to 0 and vice versa Counts transitions from 1 to 0 Percent from 0 to 100 Celsius temperature Fahrenheit temperature Shaft angle. for example. The other modes perform a mathematical scaling operation on the raw input value. The modes are listed in Table 4-3. Three of the modes count events: SENSOR_MODE_EDGE. 16 counts per full revolution Internally. For example.) Table 4-2. supplies power to the sensor. (I described this back in Chapter 3. Raw values are converted to the input values that your program sees by a process that depends on the input mode. the RCX converts the raw value into a percent according to the equation: . SENSOR_MODE_PULSE. const mode) Use this command to set the mode of the given input. This command specifies how the RCX should treat an input. electrically speaking. and SENSOR_MODE_ROTATION.63 SetSensorType(expression sensor. Table 4-3. input values initially have a raw value from 0 to 1023. While the SetSensorType() command is used to specify the electrical characteristics of the input. if the input mode is SENSOR_MODE_PERCENT. The SENSOR_TYPE_LIGHT type. const type) This command specifies the type of sensor attached to the given input. Input types are listed in Table 4-2. the SetSensorMode() command specifies how the input value should be processed. Input Type Constants Type Constant SENSOR_TYPE_TOUCH SENSOR_TYPE_TEMPERATURE SENSOR_TYPE_LIGHT SENSOR_TYPE_ROTATION Sensor Type Touch sensor Temperature sensor Light sensor (powered) Rotation sensor (powered) SetSensorMode(expression sensor. SENSOR_MODE_CELSIUS). For example. ClearTimer(const n) This command resets the value of the given timer to 0. 1. Input Configurations. They count in increments of 100 ms. Table 4-4 shows what types and modes correspond to the configurations that SetSensor() recognizes. 1. The command for generating random numbers is: Random(const n) This command returns a random number between 0 and n. and Modes Input Configuration SENSOR_TOUCH SENSOR_PULSE SENSOR_EDGE SENSOR_LIGHT SENSOR_CELSIUS SENSOR_FAHRENHEIT SENSOR_ROTATION Timers The RCX has four internal timers. Random Numbers NQC has a simple command for creating random numbers. or once every 1/10 seconds. and 3. NQC includes two commands for interacting with the timers: Timer(const n) This returns the value of the specified timer. or 3. SetSensorMode(SENSOR_2.64 If you wanted to attach a temperature sensor to input 2 and measure Celsius values. Random numbers are often useful in robot programming. 2. Table 4-4. The SetSensor() command. The timer begins counting up again immediately. is a convenient way of specifying both an input type and an input mode. Types. Input Type SENSOR_TYPE_TOUCH SENSOR_TYPE_TOUCH SENSOR_TYPE_TOUCH SENSOR_TYPE_LIGHT SENSOR_TYPE_TEMPERATURE SENSOR_TYPE_TEMPERATURE SENSOR_TYPE_ROTATION Input Mode SENSOR_MODE_BOOL SENSOR_MODE_PULSE SENSOR_MODE_EDGE SENSOR_MODE_PERCENT SENSOR_MODE_CELSIUS SENSOR_MODE_FAHRENHEIT SENSOR_MODE_ROTATION . numbered 0. a robot that tries to drive around obstacles can easily get stuck in a corner if it always backs up and turns exactly the same way to get away from an obstacle. The number returned is the number of 1/10 seconds since the timer was cleared. you would do the following: SetSensorType(SENSOR_2. which I described first in this section. 2. A robot that backs up for a random amount of time and turns for a random amount of time is less likely to get stuck in this way. which should be 0. SENSOR_TYPE_TEMPERATURE). The following command waits for a condition to become true: until (boolean condition) [statements] Use this command to wait for the given condition to become true. Note that this only applies to the current task—other tasks will continue to execute. which means it won't do anything each time the condition is tested—it simply waits until the condition is true. conditional expressions are very different from evaluations. Waiting Although it might not seem important. for example. SENSOR_PULSE). until (SENSOR_1 == 4) { PlaySound(SOUND_CLICK). this will look familiar. like a press on a touch sensor.65 Program Flow You've seen how to control the RCX's outputs and inputs. or you want to give a sound time to play. In this section. The following program beeps every half second until you press a touch sensor on input 1 four times: task main() { SetSensor(SENSOR_1. This particular until has an empty body. Use == to compare values and = to assign values. A variation on this theme is the concept of waiting for an event. The command is: Wait(expression ticks) This command causes the current task to pause for the supplied hundredths of a second. This is often useful if you need to allow some time for something to happen—maybe the robot needs to move forward or turn for a little while. You could. NQC includes a command that tells the robot to do nothing for a certain amount of time. wait for the value of input 1 to become 4 like this:∗ until (SENSOR_1 == 4). I'll talk more about tasks a little later. Wait(50). I'll sketch out NQC's program control commands. NQC supports a standard set of conditional branches and loops. a call to Wait(100) will pause the task for a full second. or a certain time of day. if you've ever programmed in other languages (particularly C). . } } ∗ As in C. But robot programs aren't very interesting unless they can make decisions and repeat actions. the statements after the else are executed. if (boolean condition) [statements] This command executes the given statements only if condition is true. } On(OUT_A + OUT_C). . which is not true for a while loop. Rev(OUT_C). use the if command. Wait(50). while (boolean condition) [statements] This loop repeats the supplied statements until condition is no longer true. OUT_FULL). Let's look at an example. The following example turns different directions depending on the value of input 2: SetPower(OUT_A + OUT_C. The statements will always be executed at least once. } Notice how curly braces are used to bracket the statements that belong to the while loop. you can omit the braces like this: while (SENSOR_3 < 35) Wait(50). do [statements] while (boolean condition) This loop is similar to while but the statements are executed before the condition is tested. if (SENSOR_2 < 50) { Fwd(OUT_A). If you have only one command in the body of the while. } else { Rev(OUT_A). Fwd(OUT_C). NQC offers three flavors of loop: repeat (expression value) [statements] This command simply repeats the given statements value times. The following code plays a sound every half second while a light sensor attached to input 3 sees dark: while (SENSOR_3 < 35) { PlaySound(0).66 Loops A loop is a series of commands that you want to be executed repeatedly. if (boolean condition) [statements] else [statements] This is a simple variation on the basic if command. If the condition is false. Conditionals To test a condition. i. i += 1. Although this may not seem like a big deal. Once a variable is declared.67 Variables To use a variable. This is really shorthand for the following: i += 1. The += operator. while (i < 10) { PlaySound (0). You can also assign input values to variables. like this (not part of the example): i = SENSOR_2. In the following line. it is. Values are assigned to the variable using the = operator: i = 0. The variable. #define lets you create . On(OUT_A + OUT_C). Only integer variables are supported. is shorthand for this: i = i + 1. Wait(5 ∗ i). task main() { i = 0. one is added to the value in variable i: i++. } } This example beeps at successively longer intervals. POWER). Here's a simple example: int i. you simply need to declare its name. is declared in the very first line: int i. This is a idiom that will be familiar to C programmers. you can assign the variable values and test it in the body of the program. in turn. } NQC replaces every occurrence of POWER with 5 in your source code before compiling it. Here is an example: #define POWER 5 task main() { SetPower(OUT_A + OUT_C. Using #define for Constants and Macros Constant values can be assigned meaningful names using #define. 68 readable names for things that might otherwise be cryptic. power). Second. using the following command: PlaySound(const n) This command plays the sound represented by n. right(OUT_HALF). If you later decide you want the power level to be 7. instead of finding all the places in your program where the output power is set. Instead of explicitly putting 5 all the way through your program. as detailed in Table 4-5. You can also create macros with #define. power). that is used in the body of the macro. Off(OUT_A + OUT_C). #define right(power) \ SetPower(OUT_A + OUT_C. left(OUT_HALF). #define left(power) \ SetPower(OUT_A + OUT_C. OnFwd(OUT_C). each macro has a parameter. Usually you'll define a macro for something you want to do frequently. Wait(100). task main() { forward(OUT_FULL). Your program. Wait(100). power. \ OnRev(OUT_A). you just have to change the definition of POWER. power). Table 4-5. \ OnFwd(OUT_A + OUT_C). RCX System Sounds Sound Name SOUND_CLICK SOUND_DOUBLE_BEEP Description Short beep Two medium beeps (table continued on next page) . the macros are split out to multiple lines by using a backslash. Wait(100). for example. OnRev(OUT_C). It also lets you define things that might need to be adjusted throughout your program in one place. might have multiple places where it set the outputs to power level 5. } The preceding example shows off two features of macros. you can use the constant value POWER. First. The following program uses three macros: #define forward(power) \ SetPower(OUT_A + OUT_C. NQC includes constant names for each available sounds. A macro is a kind of miniature program. \ OnFwd(OUT_A). Sounds and Music Your RCX can play various prepackaged sounds. so don't expect the pitches to be exactly in tune. SIXTH). The frequency is in Hz. #define #define #define #define SIXTH 12 HALF 3∗SIXTH BEAT 2∗HALF GRACE 6 task main() { PlayTone(330. PlayTone(311. Subsequent calls to PlayTone() will not fit on the queue and the tones you've requested will not be played. The following example demonstrates this technique. If you want to play a sequence of notes. Wait(2∗BEAT + 2∗SIXTH). SIXTH). PlayTone(247. RCX System Sounds (continued) Sound Name SOUND_DOWN SOUND_UP SOUND_LOW_BEEP SOUND_FAST_UP Description Descending arpeggio Ascending arpeggio Long low note Quick ascending arpeggio (same as SOUND_UP but faster) If you'd prefer to make your own music. with-out waiting for the sound you've requested to finish playing.69 (table continued from previous page) Table 4-5. PlayTone(330. the command returns almost immediately. it plays part of Quando men vo. SIXTH). The queue is long enough to hold eight tones. PlayTone(208. so 440 is the pitch of the A above middle C on a piano. 2∗BEAT). Wait(4∗SIXTH + 2∗BEAT + 2∗SIXTH). PlayTone(208. SIXTH). you have to be a little tricky about it. SIXTH). 2∗BEAT). the queue will fill up. If you want to play a sequence longer than this. you can play individual notes with the PlayTone() command: PlayTone(const frequency. const duration) This command plays a note with the given frequency for the specified duration. The tone you've requested is put in a queue. Each time you call PlayTone(). If you call PlayTone() repeatedly. No one expects your little robot to sound like Pavorotti. You can only specify integer values for the frequency. PlayTone(115. . SIXTH). PlayTone(247. SIXTH). from Giacomo Puccini's La Bohème. the system plays it while the rest of your program executes. The duration is in hundreths of a second. PlayTone(115. you should insert calls to Wait() in your program so that the queue has time to empty out as notes are played. . HALF). HALF). PlayTone(277. PlayTone(311. PlayTone(311. HALF). ClearMessage() This command clears the incoming message. SIXTH). HALF). PlayTone(208. PlayTone(277. HALF). Wait (2∗HALF). HALF). HALF). HALF). PlayTone(220. The Display Although you can't control the display directly in NQC. PlayTone(330. HALF). GRACE). PlayTone(330. to avoid responding more than once. 2∗BEAT). PlayTone(311. Wait(GRACE + 5∗HALF + 2∗BEAT + HALF). } IR Communication Your robot can send and receive data over its IR port. PlayTone(370. HALF). Wait(GRACE + 5∗HALF + 2∗BEAT + HALF). HALF). 3∗BEAT). PlayTone(247. Wait (2∗HALF). PlayTone(311. You may want to do this after responding to an incoming message. PlayTone(277. In NQC. Wait(4∗SIXTH + 3∗BEAT + HALF). you can configure it to some degree: SelectDisplay(expression v) This command tells the RCX to show the data source represented by v on its display. You can achieve the same results by pressing the View button on the front of the RCX to show the state of the inputs or outputs. Message() Use this command to return the last byte of data received on the IR port. 2∗BEAT).70 PlayTone(311. HALF). HALF). PlayTone(247. PlayTone(277. The legal values for v are shown in Table 4-6. PlayTone(220. PlayTone(277. HALF). GRACE). three commands handle sending and receiving data: SendMessage(expression m) This command sends the given byte of data out the IR port. PlayTone(330. PlayTone(208. but the SelectDisplay() command allow you to do this as part of a program. The following example waits for a touch sensor on input 1 to be pressed. The Datalog With the default firmware. The datalog is simply a list of numbers. AddToDatalog(expression v) This command adds a value to the datalog. your RCX supports an interesting option called a dtalog. The datalog commands are: CreateDatalog(const size) This command tells the RCX to make space for the given number of elements. the value of timer 0 is stored in the datalog. count = 0.71 Table 4-6. For each press. Unfortunately. const minutes) Use this macro to set the current time of the RCX's clock. ClearTimer(0). which holds 20 values in this example: int count. nothing happens. SetSensor(SENSOR_1. until (count == 20) { until(SENSOR_1 == 1). . SENSOR_TOUCH). AddToDatalog(Timer(0)). There is only one datalog. task main() { CreateDatalog(20). You can create a new datalog and put numbers into it. Datalogs can be uploaded to your PC for analysis or display. only constant values can be used. If you try to add values after the datalog is full. Display Values Value 0 1 2 3 4 5 6 Description System clock View Input 1 View Input 2 View Input 3 View Output A View Output B View Output C You can set the clock in the RCX using the following macro: SetWatch(const hours. so this command will erase any previous datalog. It's up to you to keep track of how many values are in the datalog. It looks kind of like a pie. which simply dumps the values to the screen: C:\>nqc -datalog 8 12 16 19 23 25 27 29 31 33 39 47 52 56 59 62 65 68 71 75 C:\> The datalog actually stores the source of every value. To upload a datalog to the PC. until(SENSOR_1 == 0). Every program must have a main task which is executed when the program is first started.72 count++. Tasks NQC gives you powerful control over tasks and subroutines. which is another way of saying that the RCX is multitasking. Each of the RCX's five programs is made up of one or more tasks. If you use a tool like RCX Command Center. Other tasks must be started and stopped explicitly: . it can show you the source of each value in the datalog. as you add values to the datalog the pie fills up. I'll show you how to write your own program in Visual Basic to retrieve the contents of the datalog. In Chapter 8. Tasks are defined using the task command. Using Spirit. you'll notice the RCX shows the status of the datalog on the right side of the display. These tasks can execute at the same time.ocx with Visual Basic. you can use nqc's -datalog option. } } When you run this program. PlayTone(330. PlayTone(208. PlayTone(247. PlayTone(311. HALF). HALF). PlayTone(277. SIXTH). PlayTone(247. HALF). task main() { start sing. OnRev(OUT_C). PlayTone(311. HALF). Wait(4∗SIXTH + 3∗BEAT + HALF). HALF). 2∗BEAT). OnFwd(OUT_C). PlayTone(115. 2∗BEAT). sing. HALF). PlayTone(311. SIXTH). PlayTone(311. PlayTone(370. PlayTone(220. SIXTH). Wait(100). while (true) { OnFwd(OUT_A). } } #define #define #define #define SIXTH 12 HALF 3∗SIXTH BEAT 2∗HALF GRACE 6 task sing() { PlayTone(330. Wait(GRACE + 5∗HALF + 2∗BEAT + HALF). its commands will never be executed. The sing task has to be started from main. SIXTH). Wait(100). SIXTH). PlayTone(247. GRACE). Wait(2∗BEAT + 2∗SIXTH). PlayTone(220. OnRev(OUT_A). otherwise. SIXTH). .73 start taskname This command starts the named task. HALF). PlayTone(115. 3∗BEAT). Wait (2∗HALF). The following program controls its outputs from main and uses another task. Wait(4∗SIXTH + 2∗BEAT + 2∗SIXTH). PlayTone(330. SIXTH). SIXTH). HALF). PlayTone(277. 2∗BEAT). PlayTone(208. PlayTone(277. to play some music. stop taskname Use this command to stop the named task. PlayTone(330. OnRev(OUT_A). wiggle(). HALF). Multithreaded programming is powerful but tricky. HALF). You could accomplish the same sorts of things with subroutines and macros. Wait(GRACE + 5∗HALF + 2∗BEAT + HALF). If we turned off the motors and then stopped the main task. Wait (2∗HALF). Subroutines in NQC are defined in much the same way as tasks. } When the sing task is done playing music. stop main. it stops the main task with the stop command. but subroutines are more .74 PlayTone(277. Each RCX program can have up to ten tasks. Subroutines offer a way to clean up your source code and reduce the size of compiled programs. Off(OUT_A + OUT_C). PlayTone(208. PlayTone(311. } Subroutines execute as part of the task from which they are called. PlayTone(311. The nice thing about subroutines is that their code is defined once. PlayTone(208. Wait(200). PlayTone(277. It works just as if the call to wiggle() was replaced with the commands it contains. Wait(20). OnFwd(OUT_C). PlayTone(247. called wiggle(). HALF). Then it turns the motors off. The main task shows how this subroutine is called: task main() { wiggle(). Float(OUT_A + OUT_C). Subroutines A subroutine is a group of commands that you will execute frequently. PlayTone(330. HALF). but you can call it as many times as you like from other places in your program. GRACE). Wait(20). OnRev(OUT_C). HALF). it's possible that main would turn on the motors again before it was stopped. 2∗BEAT). } sub wiggle() { OnFwd(OUT_A). HALF). The order is critical. The following program has one subroutine. . } You can have more than one argument. This actually makes inlines appear a little more capable than subroutines: they can call other inlines or even subroutines. OnRev(OUT_C). To get around restrictions like these. the entire macro body would be placed at each point where it was called. you can define inlines with a parameter. Wait(waitTime). almost like a macro or constant definition. something that makes your source code look pretty but doesn't necessarily result in better efficiency. First. you can't call another subroutine from within a subroutine. Wait(20). Off(OUT_A + OUT_C). Arguments to inlines can be passed in four different ways. if you wish. } Inlines are called the same way as subroutines. which is defined in the firmware. Table 4-7 summarizes the options. Wait(waitTime). In source code. OnFwd(OUT_C). OnRev(OUT_A). The compiler actually places the code of the inline wherever it is called. the inline subroutine. Inlines NQC does offer another interesting option. Third. for example. you can't pass parameters to a subroutine or get a return value. Wait(20). you'll need to use a different firmware. In NQC version 2. OnRev(OUT_A). a subroutine also cannot call itself. Just remember that inlines are really an example of syntactic sugar. no more than eight subroutines can be defined for a single program. like this: void wiggleTime(int waitTime) { OnFwd(OUT_A). With a macro. OnFwd(OUT_C).75 efficient because the code is just compiled once. These limitations are imposed by the RCX's bytecode interpreter. Off(OUT_A + OUT_C). As a consequence. it looks a lot like a subroutine except with a C-style return type (always void): void wiggle() { OnFwd(OUT_A).0. Second. OnRev(OUT_C). like legOS or pbForth. The RCX imposes three crippling restrictions on subroutines. } The last option. like passing a variable or constant: int power = 6. you might have an inline like this: void forward(const int& power) { SetPower(OUT_A + OUT_C. For example. OnFwd(OUT_A + OUT_C). power). You can basically accomplish the same stuff with int parameters and const int& parameters. } } void increment(int& n) { n++. . Argument Passing for Inlines Type int const int int& const int& By Value or By Reference? by value by value by reference by reference Temporary Variable Used? yes no no no If you pass int by value. Wait(count ∗ 20). while (count <= 5) { PlaySound(SOUND_CLICK). forward(OUT_HALF). you can do normal things. In this code. If you pass by reference.76 Table 4-7. const int passes by value. a count variable is incremented in the body of an inline: task main() { int count = 0. the parameter's value is copied into a temporary variable (from the pool of 31) and used in the inline. } With this inline. for example. const int &. But you can also do trickier stuff. increment(count). forward(power). is used when you want to pass a value that should not be changed. like this: forward(Message()). the variable that is passed in can actually be modified in the inline. The advantage of const int& is that no temporary variables are used. but the value must be a constant at compile time. This is great for things like Sensor() and Timer(). You'll be able to compare the NQC programs to the RCX Code programs from Chapter 3. The second task takes care of things when the light sensor leaves the black line. we can store Trusty's state in a real variable. In NQC. it will be LEFT. this means it's easy to fiddle with their values. . if it was RIGHT. Wait(TIMEOUT). int state. if the robot is still not on the black line. The first task (main) tests the value of the light sensor. it updates the value of state. and our program is easy to read. and vice versa.77 Trusty Revisited You've seen some small examples of NQC code. we used a counter to keep track of Trusty's state. Now I'll show you how Trusty can be programmed using NQC. } The DARK2 and POWER constants are determined using #defines. Whenever the robot leaves the line. The counter value was used to decide if Trusty would turn left or right the next time the light sensor left the black line. we call toggle() again to turn back the other way: task lightWatcher() { while (true) { if (SENSOR_2 > LIGHT2) { toggle(). First. we'll use symbolic constants to represent state values. #define LEFT 0 #define RIGHT 1 Trusty's program has two tasks. toggle() starts the robot turning. it makes Trusty turn. If it is over the black line. based on the value of the state variable. the robot is set to move forward: while (true) { if (SENSOR_2 < DARK2) OnFwd(OUT_A + OUT_C). the toggle() subroutine is called. Second. Then we wait a little while. if (SENSOR_2 > LIGHT2) { toggle(). } } } } The toggle() subroutine performs two important functions. Plus. Wait(TIMEOUT ∗ 2). New Brains For Trusty As you may recall. SENSOR_LIGHT). state = RIGHT. } } } } sub toggle() { if (state == LEFT) { OnRev(OUT_A). SetSensor(SENSOR_2. #define LEFT 0 #define RIGHT 1 #define DARK2 35 #define LIGHT2 40 #define POWER 7 #define TIMEOUT 50 task main() { state = LEFT. state = LEFT.78 Here is the whole program: int state. main initializes the value of the state variable. POWER). } } The main task performs three important initializations which I haven't mentioned yet. OnRev(OUT_C). It just uses LEFT . OnFwd(OUT_C). SetPower(OUT_A + OUT_C. } else { OnFwd(OUT_A). if (SENSOR_2 > LIGHT2) { toggle(). while (true) { if (SENSOR_2 < DARK2) OnFwd(OUT_A + OUT_C). start lightWatcher. Wait(TIMEOUT). } } task lightWatcher() { while (true) { if (SENSOR_2 > LIGHT2) { toggle(). Wait(TIMEOUT ∗ 2). First. Finally. No action is taken for BOTH_OFF and INDETERMINATE: while (true) { if (state == BOTH_ON) OnFwd(OUT_A + OUT_C). Next. programming this robot in RCX Code was cumbersome. Another task examines the state variable and sets the motors appropriately. A fifth value. If it is. It's pretty straightforward to translate Table 3-1 into source code. is used when one or both of the light sensor values is not in the dark or light range: #define #define #define #define #define BOTH_ON 3 LEFT_ON 1 RIGHT_ON 2 BOTH_OFF 0 INDETERMINATE 255 The main task simply tests the value of the state variable and sets the motors accordingly. The four possible states are represented by constant values. Then one task examines the sensors and updates the state variable. // the light sensor is seeing black. INDETERMINATE. OnFwd(OUT_A). I'll present an NQC program that works with the two light sensor version of Trusty. As you may recall. The basic strategy is to use a state variable to represent the four states of the robot. OnFwd(OUT_C). main configures input 2 for a light sensor. } else if (state == RIGHT_ON) { Off(OUT_C). it starts the lightWatcher task.79 arbitrarily. #define BOTH_ON 3 #define LEFT_ON 1 . } } A separate task. Here is the entire source code for the two sensor version of Trusty: int state. else if (state == LEFT_ON) { Off(OUT_A). The programming is a lot cleaner in NQC. // "ON" refers to whether the light // sensor is on the line. watcher. examines the light sensor values and sets the state variable. Using Two Light Sensors In this section. represented by the four lines of Table 3-1. state = BOTH_OFF. . else if (state == LEFT_ON) { Off(OUT_A). SENSOR_LIGHT). } } = BOTH_ON. #define DARK2 35 #define LIGHT2 40 #define DARK3 40 #define LIGHT3 45 #define POWER 4 task main() { initialize(). } } } sub initialize() { SetSensor (SENSOR_2. = RIGHT_ON. OnFwd(OUT_A + OUT_C). SetPower(OUT_A + OUT_C. } else state = INDETERMINATE. } else if (SENSOR_2 > LIGHT2) { if (SENSOR_3 < DARK3) state else if (SENSOR_3 > LIGHT3) else state = INDETERMINATE.80 #define RIGHT_ON 2 #define BOTH_OFF 0 #define INDETERMINATE 255 // Thresholds for light and dark. SetSensor (SENSOR_3. state = LEFT_ON. while (true) { if (state == BOTH_ON) OnFwd(OUT_A + OUT_C). OnFwd(OUT_C). } else if (state == RIGHT_ON) { Off(OUT_C) OnFwd(OUT_A). start watcher. } task watcher() { while (true) { if (SENSOR_2 < DARK2) { if (SENSOR_3 < DARK3) state else if (SENSOR_3 > LIGHT3) else state = INDETERMINATE. POWER). SENSOR_LIGHT). nl/people/markov/lego/ Mark Overmars.) .enteract. Kevin Saddi's NQC Reference Page. utilities for making your RCX play music. developed by Mark Overmars.html This page provides a distilled view of NQC. Word97. or you'd like to see NQC's commands organized by function.com/products/pdf/h33th014d2. Lego Robots: RCX Command Center. (Hitachi's web site is a little flakey. Lego Robot Pages [NQC Tutorial]. This site also includes the definitive NQC documentation. and useful help files.com/h8/ and searching for the H8/3292. You can download the current release. Hitachi Single-Chip Microcomputer H8/3297 Series…. PostScript. It's available off his main web page as PDF. It includes a syntax-colored program editor. The specific model is the H8/3292.uu.gte. If you're having trouble with this URL. or RTF.nl/people/markov/lego/rcxcc/ RCX Command Center (RcxCC). This document is a gentle and thorough introduction to NQC. is built on top of NQC. or browse a FAQ. creator of RcxCC (the previous entry).cs. Dave Baum has packed a lot of useful information into this site. read the documentation. This information is not for casual browsing—you probably won't need to look here unless you start writing your own firmware.cs. which is covered in the manual.uu. real-time control of the RCX.81 Online Resources NQC—Not Quite C. I highly recommend this application.net/ksaddi/mindstorms/nqc-reference.pdf This PDF document has all the crufty details on the Hitachi H8 that forms the heart of the RCX. including such gems as how to create a cable to connect your Macintosh to the IR tower.com/~dbaum/lego/nqc/ This is the official site for NQC. It's a Windows application that provides a friendly graphic interface to the features of NQC.hitachi. has written a detailed introduction to NQC. It's very handy when you can't remember the input type constants. try starting at the URL. Single-line code samples are also included.hitachi. 82 5 Minerva, a Robot with an Arm In this chapter: • Building Instructions • Programming • Directional Transmission • Pulleys • Mechanical Design • Two Sensors, One Input • Where Am I? • Online Resources Minerva is a mechanical marvel. Although she has the same wheel layout as Trusty, Minerva's drivetrain is radically different. In addition, she has a simple arm with a grabber, which allows her to pick up and drop small objects. Best of all, Minerva can be built with the pieces from the RIS alone. The grabber arm is operated by a single motor. The other motor powers the drivetrain, which moves the robot forward or spins it in place. Figure 5-1 shows a picture of this remarkable robot. Figure 5-1. Minerva, a mechanical masterpiece When you run Minerva's program, she drives straight forward. When the light sensor (mounted on the end of the grabber arm) sees something dark, Minerva stops driving. She uses the arm to try to pick up whatever the light sensor saw. 83 Then she turns around and drives back to her starting point. She puts down whatever she's carrying, turns around and is ready to start again. Building Instructions If there's one lesson to be learned from Minerva, it is that mechanical design is hard. I had to build this robot five times to get it right. And I don't mean I moved a few pieces around—I actually disassembled and rebuilt the robot that many times. The drivetrain alone took four tries before I got it right.∗ Directional Transmission and Drivetrain The long gray piece in Step 1 swivels freely on the shaft. ∗ Minerva uses almost all of the gears that come with RIS 1.0. Unfortunately, RIS 1.5 comes with fewer gears (five 12t gears instead of eight). To get the extra gears you'll need for Minerva, you can order the #5229 Gears & Differentials parts pack from the LEGO Shop At Home Service, (800) 453–4652. Cost is $4.50 including shipping. 84 The 8u shaft in Step 2 is loose and may fall out. It will be anchored in the next step. The 6u beam, like the long gray piece from Step 1, swivels freely on its shaft. 85 Make sure the bump on the long pin is up against the 4u beam. Before you put all of Step 7 together, make sure the swiveling parts from Steps 1 and 2 are pointing up, as shown. 86 87 . The swiveling pieces from Steps 1 and 2 are now anchored. adding bushings and gears as you go.88 Step 11 is tricky. . You'll need to slide the 8u shaft into the structure. 89 Step 14 is similar to Step 11. take a deep breath and go slowly. . 90 Grabber Arm In Step 17. the half-bushings go between the center block and the cams (pear-shaped pieces). . 91 . They should mirror each other. .92 Make sure that the two sides are at the same angle. 93 . 94 Structural Support . 95 Idler Wheel . 96 . hold on to the worm gear so it doesn't slip off. .97 Drive Motor While you're putting the motor in. 98 Grabber Arm Motor . 99 . 100 RCX Attach the RCX on both sides as shown. . . attach the left motor. to output A. which powers the arm. Then use a wire brick to attach the right motor (the drive motor) to output C.101 Wiring First. . Next.102 Attach the light sensor to the front of the arm. use a wire brick to attach the touch sensor to the light sensor wire. Then use a longer wire brick to attach both wires to input 3. The wire attaches to Minerva's side as shown. int threshold. } #define NUMBER_OF_SAMPLES 10 int runningTotal. calibrate() . Minerva's program also does some sensor calibration that would also be impossible in RCX Code. i = 0. but you wouldn't be able to implement some key features. i += 1. There's no way to do this in RCX Code. SetSensor(SENSOR_3. SetPower(OUT_A + OUT_C. SENSOR_LIGHT).103 Programming Minerva's basic program is straightforward: find something to pick up bring it back to the starting point The program assumes that the objects to pick up will be dark and that the surface Minerva is driving on is light. You could create a program in RCX Code (the environment that comes with RIS). Here's the whole program: #define TURNAROUND_TIME 425 int i. . To return to the starting point. OUT_FULL). Minerva's ability to drive back just as far as she drove forward is crucial. } OFF(OUT_A + OUT_C). Then it turns around and drives back for the same amount of time. task main() { // Arm limit sensor and grabber light sensor. while (i < 5) { retrieve(). Minerva measures how long it has to drive forward to pick something up. In particular. Here's a slightly exploded version of Minerva's program: drive forward until the light sensor sees something dark pick it up with the grabber turn around drive back to the starting point drop whatever's in the grabber I've written Minerva's program in NQC (see Chapter 4. Not Quite C). ClearTimer(0). . // Back off from the switch. // Drive back. } int returnTime. until (SENSOR_3 < threshold . } void release() { // Run the motor until we hit the limit switch. sub retrieve() { // Drive forward until we see something. ClearTimer(0). OnRev(OUT_A). } void grab() { // Run the motor until we hit the limit switch. } threshold = runningTotal / NUMBER_OF_SAMPLES. Off(OUT_A). // Turn around (roughly). Wait(10). Off(OUT_C).3). OnRev(OUT_C). until (SENSOR_3 == 100). OnFwd(OUT_A). OnFwd(OUT_C). until (Timer(0) >= returnTime). Off(OUT_A). // Back off from the switch. OnFwd(OUT_C). until (SENSOR_3 != 100). // Move up on it a little. Off (OUT_C). until (SENSOR_3 != 100). OnFwd(OUT_A).104 sub calibrate() { // Take an average light reading. returnTime = Timer(0). i = 0. i += 1. runningTotal = 0. while (i < NUMBER_OF_SAMPLES) { runningTotal += SENSOR_3. Wait(20). OnRev(OUT_A). until (SENSOR_3 == 100). grab(). Wait(TURNAROUND_TIME). Wait(TURNAROUND_TIME).105 release(). and the arm to lift again. For now. Finally. Calibrating the sensor in this way frees us from hard-coding a light sensor threshold value into Minerva's program. Specifically.3). You might have noticed that the light sensor and the touch sensor are both attached to the same input. The retrieve() subroutine uses this value to figure out if it's looking at an object that should be picked up. the grabber open.3). OnRev(OUT_C). until (SENSOR_3 < threshold . and the arm lift again. The calibrate() subroutine examines the values coming from Minerva's light sensor. All they do is run the arm motor in one direction until the limit sensor is pressed. // Move up on it a little. timer 0 is ticking away. While it's driving forward. Minerva picks it up: grab(). All we have to do is wait for the arm to lift. which is stored in the variable threshold. It computes an average value. // Turn around. It drives forward (by turning output C on) until it finds something dark to pick up. measuring how long it takes until something is found: OnFwd(OUT_C). Having found something interesting. . I'll talk about how this works later. The retrieve() subroutine is the heart of Minerva's program. just be aware that it's necessary for grab() and release() to move away from the touch sensor to use the light sensor. It also makes Minerva better able to deal with different lighting conditions. Running the motor forward causes the arm to descend. Minerva turns off output C to stop the robot's forward motion: Wait(20). it tests if the light sensor value is a little less than the original average: until (SENSOR_3 < threshold . which presses the switch when it's finished. The grab() and release() inline subroutines take care of the grabber arm. as I'll explain later in the chapter. returnTime = Timer(0). Running the motor in reverse makes the arm descend. She records the forward movement time for the return trip. Minerva moves forward a little farther to position the grabber over the object. The mechanics of the arm take care of everything. Off(OUT_C). ClearTimer(0). the grabber to close. Once a dark object is found. } Let's look at the simple parts first. throwing her off course. There are quite a few things that can go wrong: 1. Put the Test Pad on a hard. using the returnTime value. The grabber doesn't always pick up the block Minerva is aiming for. which stabilizes after the RCX is on for a while. I'll explore some of the things that can confuse Minerva. you may need to adjust the TURNAROUND_TIME constant to make Minerva spin around 180°. she simply reverses the direction of output C for the duration given by TURNAROUND_TIME: OnRev(OUT_C). Finally. . 2. which it probably won't. which was saved earlier: OnFwd(OUT_C). Minerva may not ''see" the dark blocks to pick them up. the retrieve() subroutine drops the object that Minerva's carrying and turns around again: release(). She probably won't bring blocks back to her original starting point. until (Timer(0) >= returnTime). I found that I got better results after the RCX was on for a minute or two—the sensor values depend on the battery power. flat surface. Minerva finds five dark objects and brings them back to her starting point. Minerva's wheels may stumble on the blocks. she'll go pick up some blocks and bring them back to her starting point. In particular.106 Now she wants to turn around and return to her starting point. ClearTimer(0). The main task configures Minerva's inputs and then calls retrieve() five times in a row. Try It Out! To take Minerva out for a spin. Scatter some black blocks on the back of the Test Pad and start Minerva running. To turn around. Different surfaces will give you different results. Off(OUT_C). Instead of driving and returning on a straight line. Wait(TURNAROUND_TIME). It acts as a mostly uniform bright surface. I suggest using the back of the Test Pad that comes with RIS. In the next section. If you're lucky. 3. Wait(TURNAROUND_TIME). Minerva will now be pointing in a different direction. OnRev(OUT_C). If everything works perfectly. Now she drives back to her starting point. Directional Transmission Minerva uses a single motor to drive forward and to turn. The bottom shaft is the input. A directional transmission will drive one of two output shafts If you rotate the input shaft clockwise. . Figure 5-2. but I'll briefly explain the fundamental ideas of both types of directional transmission. the top gear on the beam engages the gear on either the far left or far right. this design would never work. using different combinations of gears. The second design uses a worm gear. but the idea is the same. you can think of it as a box with an input shaft and two output shafts. the other output shaft rotates. Functionally. This design relies on friction to swing the arm in the right direction. A directional transmission does different things depending on whether you run a motor shaft forward or in reverse. I'm going to talk about Minerva's amazing mechanical features. Swing-Arm Design A cutaway view of a swing-arm directional transmission is shown in Figure 5-3.107 Some of the challenges Minerva faces are discussed later in this chapter. as shown in Figure 5-2. These gears are on the output shafts. Depending on which direction the input shaft turns. If you rotate the input shaft counterclockwise. There are at least two ways to build a directional transmission with the parts included in your RIS. This mechanical magic is accomplished with the aid of a directional transmission. frictionless world. The first design uses a pair of gears on a swinging arm. A 24t gear mounted on this shaft drives another gear that is mounted on a beam that rotates on the input shaft. You could create variations on this configuration. In an ideal. Minerva uses the worm gear design. First. the beam swings to the left or right. one of the output shafts will rotate. Cutaway view of a swing-arm directional transmission Worm Gear Design Minerva's drivetrain is based on a worm gear directional transmission. .108 Figure 5-3. it's easier for the worm gear to slide on its shaft than to turn one of the output shafts. In fact. Cutaway view of a worm gear directional transmission The input shaft drives the worm gear. the worm gear slides as far as it can in one direction or the other. which slides freely along the shaft. as shown in Figure 5-5. The basic design of the worm gear directional transmission is quite simple. Depending on which way the input shaft turns. Figure 5-4. the worm gear will turn one of the output shafts. The worm gear engages two outputs at a time. A cutaway view is shown in Figure 5-4. When it can't slide any more (because it's hit a beam). Minerva actually uses a modified version of this design with four outputs. like the grabber arm. you can get the pulleys to move in opposite directions. a twisted band will rub on itself. If you decide directional transmissions are useful for your robot. you can achieve the same power and speed tradeoffs as with gears. The drivetrain alone sucks up all of the 8t gears. This type of linkage is similar to using gears to transmit motion from one shaft to another. while two gears meshed together turn in opposite directions. it's likely to slip if it's used to do heavy work. However. Unless the band that connects two pulleys is very tight.109 Figure 5-5. as you've seen. Pulleys also give you the flexibility to transmit motion between two perpendicular shafts. just as with gears. . and most of the 24t gears that come with RIS. Minerva's directional transmission has four outputs The basic directional transmission designs I've described are quite simple. like moving an entire robot. is a gear hog. like the ones used with outdoor clotheslines. you may want to have some extra gears handy from other sets. which may significantly reduce its life span. they don't work very well for drivetrains. all of the 16t gears. A pulley is simply a slotted wheel. The only difference is that pulleys connected by a band turn in the same direction. By using pulleys of different sizes. One of the early designs of Minerva's drivetrain used pulleys to replace several gears. Figure 5-6 shows three different pulley arrangements. Pulleys Pulleys are an interesting alternative to gears. and things get a little more complicated. however. Although pulleys are useful for lightduty work. Try to use one of these to drive a robot. The RIS comes with a handful of rubber bands that can be used to link pulleys together. Minerva. If you twist the band around once. Linking shafts with pulleys and a band On the other hand. the pulley band will simply slip. In this section. . the grabber grabs. If you run the motor in one direction. You can run the motor for longer than it actually takes to open or close the door—when the door has gone as far as it can go.110 Figure 5-6. Grabber Arm Minerva's grabber arm is operated by a single motor. a pair of pulleys is used to link the arm motor to the arm worm gear shaft. the grabber relaxes. the arm lowers. You can see this arrangement on the top of Minerva—just look for the white band. you can use pulley slippage to your advantage. This mechanical sorcery is based on the FetchBot. and the arm rises again. Run the motor in the opposite direction and the arm lowers. The entire arm is controlled by the main drive shaft. and the arm rises once again. Note that this band does not slip. a pulley can be very useful. like a trap door that opens and closes. If part of your robot should have a limited range of motion. in general. I'll talk about some of Minerva's more interesting mechanical features. Mechanical Design Several thorny mechanical issues complicate the design and construction of Minerva. A cutaway view of the arm is shown in Figure 5-7. In the final design. Its motion is geared down so far that the arm is likely to break apart before the pulley starts to slip. created by Ben Williamson (see the "Online Resources" section for details). A motor linked to a worm gear drives the 40t gear on the main drive shaft. The "fingers" of the gripper need to pick up objects. Minerva uses two of the rubber wheels as fingers. they should be slightly pliable and tacky rather than smooth. the rotation of the main shaft closes the grabber a little bit. the grabber geartrain becomes stationary with respect to the arm. Cutaway view of the grabber arm The key to understanding how the arm works is that it moves up and down for two separate reasons: 1. A single touch sensor can be used to detect when the arm is fully raised. raising the entire arm with the closed grabber. When the main drive shaft starts turning counterclockwise. When the grabber grips something. either with the gripper open or the gripper closed. Releasing an object is just as simple. either on an object or itself. Picking up an object is simply a matter of running the motor in the right direction and waiting for the touch sensor to be pressed. the grabber closes. (At the same time. Ideally.) As the main drive shaft continues turning. Suppose Minerva begins with her arm raised and the grabber open. which work reasonably well.111 Figure 5-7. When it is fully closed. The cams on the lower shaft push the arm up and let it move back down. The cams rotate down. the geartrain that controls the grabber locks up. 2. the lower shaft turns clockwise. When the main drive shaft continues turning. The main drive shaft keeps rotating. . it moves the entire arm up and down. allowing the arm to lower. with which to play. If you have ambitious plans (and parts) for expanding Minerva. Minerva uses a fairly complex system of gears to translate the outputs of the directional transmission into the correct wheel movements. which is stronger and larger than Minerva's. the drive wheels turn in opposite directions. In this section. not just one. mostly) more than compensates for the weight of the grabber arm. as you use Minerva. Balance One of the fundamental issues Minerva faces is balance. See Ben Williamson's FetchBot (in the "Online Resources" section) for the original arm design. Minerva. I'll describe one way to move beyond the three-input barrier: attaching more than one sensor to a single input. the two drive wheels both turn forward. that the pieces of the arm loosen up after time. for example. Without some kind of counterbalance. has a touch sensor and a light sensor attached to a single input. There are two common variations on the theme of attaching multiple sensors to one input. In this case. a press on any one of the attached sensors will produce a value of 1 on the input. Drivetrain Although the directional transmission is relatively simple. The weight of the RCX (the batteries.112 The arm also needs to be strong. Minerva solves the problem of balance by mounting the RCX near the back of the robot. . Only one of the outputs drives a wheel directly. you've got two inputs. as its parts are under a fair amount of stress. When the motor runs the other way. Multiple Touch Sensors The first and easiest possibility is to attach multiple touch sensors to a single input. You may notice. Minerva falls right on her face. both of which are discussed here. One Input You might think that the RCX's three inputs limit you to designing robots with only three sensors. The grabber arm sticks out in front of Minerva. With the input configured for a touch sensor. however. Minerva's drivetrain is a little more complex. One way to fix this is to move the drive wheels closer to the front of Minerva. causing Minerva to spin in place. Two Sensors. When the motor runs one way. the directional transmission and the grabber arm gearing would not have enough space to coexist. but it would also be bulkier. You could make the arm stronger. she can't answer it very well.113 This might be useful. the touch sensor must normally be not pressed. In general. to determine her current position. Then the motor must be run the other way briefly so the touch sensor is no longer pressed. You'll rarely see a real light sensor reading of 100 unless you point some very bright light directly into the sensor. If Minerva drives forward for . Usually the light sensor shows values in the range of 30 to 70. roughly speaking. Then she drives back to her starting point by moving forward for as much time as she moved forward before. or if her wheels slip in any way. is trying to answer the question "Where am I?" Unfortunately. in a robot with a "skirt" touch sensor that runs around the entire robot. she can't find her way back to her starting point. Minerva's program must account for the two sensors being attached to one input. Different parts of the skirt might trigger different touch sensors. the input gives a value of 100. of course. of course. basically. Light and Touch Minerva uses a light sensor and a touch sensor on one input. called timing. but it involves using a soldering iron. the readings depend on the lighting conditions around the sensor. Then she turns around by spinning in place for a length of time defined in TURNAROUND_TIME. anywhere around the robot. Where Am I? You've probably discovered that Minerva gets lost easily. She moves forward for some amount of time until she finds something to pick up. you could easily detect any collision with the skirt. There's a way around this problem. In particular. If she drives over anything. it has no effect on the light sensor reading. When the touch sensor is pressed. I'll explain how it works in Chapter 11. Minerva. the current value of the light sensor becomes irrelevant. is that you don't know which touch sensor is being pressed. In the grab() and release() subroutines. Make Your Own Sensors. This allows Minerva to observe values from the light sensor. The downside. Timing Minerva uses a fairly unreliable technique. The input is configured for a light sensor. for example. By putting all the skirt sensors on one input. for example. it's safe to assume that readings of 100 correspond to the touch sensor being pressed. the grabber arm motor is run forward or in reverse until the touch sensor is triggered. When the touch sensor is not pressed. 2.∗ ∗ An obvious choice might be the Global Positioning System (GPS). Feedback from the compass reading would allow Minerva to turn around with much better accuracy. Navigation Tools There are several generic navigation tools that you might consider attaching to your RCX to answer the question of location: 1. and in what direction. Unless you're the US military. serious electronics. you would know exactly how many times. it's a step up from timing. Wheels do slip. Minerva should have some feedback about how far she's traveled and how far she's turned. and other unpredictable factors will mess things up. the material Minerva is driving on. If you put the rotation sensors on Minerva's two main wheels. Minerva's directional transmission makes things more complicated. By assuming that the wheels didn't slip on the ground. Suppose you mounted three radio transmitters around the area where Minerva was going to drive.114 five seconds. The interface between the compass and Minerva's inputs. this is pretty high-tech. Again. buy some rotation sensors and attach them to inputs 1 and 2. relative to her starting position. you could get a very accurate idea of where Minerva was. Unfortunately. garden variety GPS is only accurate to 100 m or so. sadly. of course. You wouldn't have to worry about the directional transmission any more. Rotation Sensors Ideally. You could. . as the shifting time is also recorded. A magnetic compass would give a good indication of what direction Minerva was pointing. for example. you won't get accurate enough information from GPS to help your robot navigate. each wheel had turned. as well. Triangulation is a commonly used navigation technique. is not very reliable: Minerva almost never heads back precisely the way she came. Timing is not a very accurate technique. in particular. This affects the timing of Minerva's forward motion. because it takes a little time for the transmission to shift from one direction to the other. is entirely up to you and would probably require a bit of electronics hacking. so unexpected terrain like driving over blocks would likely throw this method of navigation off as well. Turning around. Variations in battery power. Still. By listening to the three signals. she assumes she can reach her starting point by turning around and driving forward for five seconds again. or willing to spend some serious money. Minerva could determine her position relative to the radio transmitters. think about what you're trying to do. The whole book is 13 Mb. check them out.net/~rci/transmission. created by Michael Powell. Online Resources Directional Transmission. describes the basic principle of the directional transmission with detailed photographs. It's gotten good reviews from the MINDSTORMS online community. but a free book is a free book.engin. no matter what programming environment you use. .115 Why Should I Care? Before you tear your hair out trying to get a GPS unit to talk to your RCX. build a bumper and back up when you hit something. "Where am I?"—Systems and Methods for Mobile Robot Positioning. If you just want to avoid table legs and walls.edu/~johannb/position. you probably won't be able to build a map of the world in your RCX. Do you really need to know precisely where the robot is? Using precise positioning and having the robot build a map of its world are both techniques of the big-metal artificial intelligence (AI) approach to mobile robotics.com/~benw/lego/ This page contains some fascinating robots created by Ben Williamson.htm This page. These robots are mechanically superlative. After all. A modified version of Ben's FetchBot arm was used as Minerva's grabber arm.umich. Ben's Lego Creations Johann Borenstein's book about mobile robot navigation can be downloaded from this site as an Adobe Acrobat PDF file. The RCX is not very powerful. which is a little hefty for my dial-up Internet connection.pobox.sonic. you can't put your own data on the display. This is the next level of power and complexity beyond NQC. Even NQC. This chapter will get you up and running with pbFORTH by covering the following topics: • An overview of the pbFORTH software architecture • Obtaining and installing pbFORTH • A brief description of Forth • Listings of RCX-specific words defined in pbFORTH • Example programs Replacement Firmware Later. display. the programming environment that comes with RIS.116 6 pbFORTH In this chapter: • Replacement Firmware • pbFORTH Overview • About Forth • pbFORTH Words • An Expensive Thermometer • Minerva Revisited • Debugging • Online Resources In Chapter 4. however. an established language that is suitable for small systems like the RCX. Even though you finally have the use of variables. pbFORTH allows you to program your robots using Forth. Not Quite C. which means they actually replace the software on the RCX. Furthermore. on what you're trying to do and what programming you've already done. In this chapter. . has its limitations. you're limited to 31 of them. Table 6-1 compares pbFORTH and legOS in several important areas. I'll talk about another popular programming environment. of course. which would be very useful for debugging. a piece of software that gives greater access to the memory. If you're considering this move. and other resources in the RCX. legOS and pbFORTH are both replacement firmware. in Chapter 10. which should you choose? It all depends. I described how NQC allows you to get around many of the limitations of RCX Code. legOS. I'll talk about pbFORTH (Programmable Brick Forth). Basically. remember some caution is in order. With pbFORTH. which takes a couple of minutes. pbFORTH is very openended. The software tools you'll need on the PC side are simple and commonly available. Compare this with legOS. you will have to put up with ugly-looking terminal sessions to program your RCX with pbFORTH. You can interact with pbFORTH from a Windows terminal emulator. that are downloaded and interpreted on the RCX itself. a Java application running on Linux. you have to replace the RCX firmware itself. similar to Figure 4-1. pbFORTH excels in two areas: startup cost There's a certain amount of pain. To break through this barrier. pbFORTH and legOS Compared. NQC's limitations are the result of the limitations of the bytecode interpreter on the RCX. just like RCX Code. With legOS. NQC is a replacement for software on the PC only. pbFORTH itself works well. NQC just reflects the limitations of the RCX firmware. that shows how pbFORTH replaces the RCX's firmware. Figure 6-1 shows a block diagram. all you need is a terminal emulator or some other simple software that talks to the RCX's IR port. you need to compile the program on your PC and download the whole thing to the RCX. this sequence of steps is farily short. pbFORTH Overview Although I'm describing pbFORTH as a way around the limitations of NQC. either gcc or egcs As a development environment. it's not NQC that limits your robot programs. you upload or type your program into pbFORTH via a terminal emulator running on your PC. this startup cost is low. the startup cost. or even a custom-developed application on a PalmPilot. before you get all fired up about pbFORTH. However. Briefy pbFORTH Programming language Interactive? Development OS Programming tool Forth Yes Any Terminal emulator legOS C or C++ No Unix. which requires some heavy-duty development tools that can be tricky to install and configure. Linux.117 Table 6-1. development cycle A development cycle is the sequence of steps you need to follow to write and run a program. but there are only a few good tools for working with it. . especially considering it's relatively new software. The program is immediately available to run. or similar C compiler. As of this writing. For pbFORTH. Remember. It generates bytecodes. associated with learning and using a new development environment. You don't have to compile and download programs. you use the -firmware option. and you will be able to talk to it as described in the next section. you simply type them directly to the interpreter. and example scripts.com/lego/pbFORTH/ . It replaces the regular MINDSTORMS firmware entirely. the source code. so you won't be able to program with RCX Code or NQC without reinstalling the regular firmware. The firmware downloader is a piece of software that knows how to transmit firmware over the IR link to the RCX. for example. you'll need a firmware downloader.html .edu/~kekoa/rcx/tools. Two freely available firmware downloaders are nqc (described in Chapter 4) and firmdl. Installing pbFORTH Installing pbFORTH is a simple process: 1. your RCX's screen will go entirely blank. It's available as an archive that contains the pbFORTH replacement firmware. pbFORTH software architecture Forth is an interpreted language. Obtain pbFORTH from. available in C source code at. 2.stanford. To do this. To remove . so be prepared to wait. like this: nqc -firmware pbforth. pbFORTH is running. which means you can type commands to pbFORTH and have the robot respond immediately.hempeldesigngroup.Downloading firmware to the RCX takes a couple of minutes. pbFORTH will remain running on your RCX as long as the batteries are good.118 Figure 6-1. Install pbFORTH on the RCX. To download pbFORTH using nqc. don't be fooled. Although the RCX looks dead.srec When the download is complete. you'll need to remove the batteries to clear the memory. Once you've got your emulator running. and no parity. You'll need to point your emulator at whatever serial port has the IR tower attached. let's turn on one of the outputs. 1 stop bit. First. Linux users can use minicom or something similar. pbFORTH should respond with ''ok" messages: ok ok To get a quick start with pbFORTH. you can turn off the output like this: 7 3 0 MOTOR_SET ok . The MOTOR_SET line turns on output A (represented in the code by 0) in reverse (represented by 2) with full power (represented by 7). you need to use a terminal emulator to exchange data with the RCX over the IR link. use the MOTOR_SET command. like this: 77 22 00 MMOOTTOORR__SSEETT I have removed the extra letters in the examples in this chapter. press Enter on your keyboard a couple of times. The other relevant settings are 2400 Baud.119 pbFORTH from your RCX. for clarity. Windows users can use the HyperTerminal application that comes with Windows. If your RCX is about to drive off your desk. To minimize the repeated characters as you type in the examples. Talking to pbFORTH To interact with pbFORTH. Type the following: 7 2 0 MOTOR_SET ok Remember to press Return after you enter the whole line. 8 data bits. make sure "local echo" is disabled in your terminal emulator. Depending on your terminal settings. you will see the letters you type two or three times in a row. which will be covered later. If you want to reinstall the default firmware. you can use the RIS software. Then you can use nqc or firmdl to download a different set of firmware. you'll need to initialize the RCX like this (the stuff you should type is shown in bold): RCX_INIT Ok To turn on an output. or NT). after I've introduced you to the Forth language itself. The 3 tells pbFORTH to turn the output off. although you have to set it up correctly. pbFORTH will get confused and complain that it can't find a word definition. Motor_Set is not. If you miss a space. as shown in Figure 6-2. Figure 6-2. the terminal emulator needs to know how long to wait after sending each character. 98. Sending Files For serious development. You can do this with many terminal emulators. In HyperTerminal (in Windows 95. You should set the Line delay to 100 milliseconds and the Character delay to 20 milliseconds. .120 This is the same as the previous example. pbFORTH reads different words by assuming that they're all separated by whitespace. While MOTOR_SET is a defined word. choose Transfer → Send Text File from the menu. Make sure you separate everything with spaces. In the window that appears. I'll get to the details of MOTOR_SET later. nor is motor_set or MOTOR_SEt. either spaces or returns. choose the Settings tab and press the ASCII Setup button. Setting character delays for sending files To upload a file to pbFORTH. First. you'll want to create your source code in a text file and send the whole file to pbFORTH when you're ready to test. except the 2 is now a 3. this setting is available in the File > Properties menu option. pbFORTH is also case sensitive. Type a number into your terminal emulator and hit return. Let's begin by pushing a number on the stack. To run it. pbFORTH responds with a friendly "ok": 77 ok Now type a single period and press return. you can pop more than one value off the stack with more than one period.121 There are other options. About Forth In this section. You can add something to the stack or remove the top item. let's see how this works. I'll briefly describe the Forth language itself. The Stack Forth is a simple but powerful language. Then I'll detail pbFORTH's RCX-specific words and present some short examples of robotic programming with pbFORTH. Similarly. Retrieving the top item is a pop. Assuming you've already gotten pbFORTH running on your RCX. like this: 77 12 55 ok . contains source code for a Java-based program downloader. A pop always returns the last item that was pushed. the pbFORTH web site has pbFORTH tools written in Tcl/Tk. A word is a simply a program with a name. 77 ok You can push multiple values on the stack by separating them with spaces. Adding an item to the stack is a push. along with that ubiquitous "ok": . 77 ok If you understand the stack. This is simply a list of words and what they mean. A stack is just what it sounds like. Words and the Dictionary The other important concept in Forth is the dictionary. 55 12 ok . . The period pops a value off the stack and prints it out to the console. Furthermore. Appendix B. you know almost everything there is to know about Forth. A pbFORTH Downloader. like a stack of trays in one of those spring-loaded carts at a cafeteria. . It is based around the idea of a stack. as well. OR. Many programs expect to find input values on the stack and may place their results on the stack when they're done. the top is shown on the right. Built-in words Forth has a number of simple words that are built in to the dictionary. By convention. For example. For example. which operate on the top two items of the stack and leave their result at the top of the stack. . you would type HEX. duplicates the top element of the stack. You can change the number base you're working in using the HEX and DECIMAL words. if you wanted to work in hexidecimal (base 16). 77 77 ok Table 6-2 lists some of the important built-in words in Forth. You can easily see how this works: 77 ok DUP ok . but it makes sense after a while (and it's the convention in Forth documentation). DUP. Base 10 is represented by DECIMAL.122 you just type its name. XOR. . x1 x2 shows a stack with x2 at the top and x1 as the second item. Most of the numbers in this chapter will be base 16. This seems confusing at first. For example. Table 6-2. The table shows the stack before ("Initial Stack") and after ("Ending Stack") the word runs. 42 ok Bitwise operators are also defined: AND. Forth Built-in Words Word DUP OVER PICK SWAP ROT DROP Meaning Duplicates the top item on the stack Copies the second stack item Initial Stack x x1 x2 Ending Stack x x x1 x2 x1 … xn x2 x1 x2 x3 x1 Copies the nth stack item (n is zero-based) … n Switches the top two stack items Moves the third stack item to the top Discards the top item on the stack x1 x2 x1 x2 x3 x Forth also supports mathematical operators. you can divide two numbers like this: 84 2 / ok . for example. Retrieving the current base with BASE @ may seem like a pointless exercise. so it will always be 10. ok The colon tells the Forth interpreter that the words that follow define a new word for the dictionary and should be stored to run later. so there are three copies of it. Here's a simple example: : threeTimes DUP DUP + + . To print out the current number base.123 BASE is a word (a variable. you can use it like any other Forth word: 5 threeTimes . Suppose you're working in base 8. then adds them all together. 15 ok And you can. The pbFORTH interpreter simply ignores the rest of the line after it sees the (. the current base is printed in terms of the current base. ok 5 nineTimes . If you print out the current base. do this: BASE @ . Subsequent words will be executed when the new word is executed. but it's useful if you want to save the current base away to be restored at some later time. (20 in base 16 is 32 in base 10) ok ! 20 DECIMAL . Word definitions begin with a colon and end with a semicolon. 10 ok Interestingly. of course. which is supplied immediately after the colon. it's expressed as 10. The new word needs a name. threeTimes in this example. Now that you've defined a new word. threeTimes duplicates the top item on the stack twice. for example. (20 in base 8 is 16 in base 10) ok The open parenthesis ( is used to indicate a comment. The semicolon tells the interpreter that the new word definition has ended. in base 8. use it in subsequent definitions: : nineTimes threeTimes threeTimes . If you want to work in a number system other than HEX or DECIMAL. Defining words Writing programs in Forth is a matter of defining your own words in the dictionary. The following example shows two ways you can use Forth to convert numbers between different bases: HEX 20 32 8 BASE 16 DECIMAL . 8. 45 ok . you can use BASE ! to store any base number. which I'll talk about soon) that contains the current number base. redefine helloWorld ok Constants and Variables You can define words in Forth that represent numerical values. all you're really doing is assigning an address (determined by the Forth interpreter) to a name. To define a constant. It replaces the address with the value at that address. like this: FULL 2 0 MOTOR_SET ok Variables are even easier to define. world. A variable is really an address in memory. The ! word expects to find an address and a value on the stack. " . " . When you declare a variable with the VARIABLE word." Tag. Then use the word CONSTANT and supply a name. it will be redefined: : helloWorld . . you can use the word anywhere you really mean the number it represents. Welt. push its value on the stack. the @ word expects to find an address on the stack. ok helloWorld Hello. : helloWorld . Similarly. This is really handy for making programs more readable. which are separate from the string. Just use the word VARIABLE and supply a name: VARIABLE z ok Values are stored in variables using the ! word.“ and ” words. it stores the value at the specified address. like this: 7 CONSTANT FULL ok You can the use FULL anywhere you really mean 7. pronounced "store": 12 z ! ok The value of a variable can be retrieved and placed on the stack with the @ word: z @ .124 Here's another simple example that demonstrates how to print messages from within a word. ok If you define a word that already exists. These words are called constants. 12 ok There's some tricky stuff going on here that I'll briefly discuss. Be careful about the spacing: the actual string to be printed is framed by the . world." Hello. a loop index is given the value start.start times. Table 6-3 lists some of the mathematical condition words that are available. up until the ” word. false otherwise > Compares the top two items on the stack. false otherwise 0= Replaces the top item of the stack with true if it is equal to zero. Table 6-3. the index is increased by one. the body between IF and THEN is executed. The . You can put the . Mathematical Condition Words Word Description < Compares the top two items on the stack. There's also a slightly more complicated IF word: condition IF trueBody ELSE falseBody THEN This is the same as before. except words between ELSE and THEN will be executed if the condition is false." less than zero " THEN . false otherwise = Compares the top two items on the stack. The IF word comes in two different varieties: condition IF body THEN The IF word looks at the condition on the stack. Forth also includes some simple loops. ok -2 negative less than zero ok 2 negative ok The 0< word examines the top value on the stack. including: limit start DO words LOOP This loop performs the given words limit . false otherwise The following example prints out a message if the top item on the stack is less than 0: : negative 0< IF . THEN marks the end of the body of the IF. replaces them with true if they are equal.“ word tells pbFORTH to print text to the console. the loop ends. Finally. The result of this comparison is examined by the IF word. Each time through the loop. When it is equal to limit.125 Conditionals and Loops Forth supports a standard IF statement. If the condition is true. false otherwise 0< Replaces the top item of the stack with true if it is less than zero. Internally. replaces them with true if the second item is less than the top item. the body of the IF is executed. replaces them with true if the second item is greater than the top item. If it is true. though the order is switched around from what you might be used to. then the stack would be shown like this: x1 x2 x3. the SWAP word would be listed like this: SWAP (x1 x2 -. for example. the loop ends and WaitForViewButton is done. takes three values off the top of the stack: MOTOR_SET (power mode index --) . ok In the body of this loop we push RCX_BUTTON on the stack and duplicate it. The following example waits for the View button to be pressed (using some stuff we haven't covered just yet): BUTTON_INIT ok : waitForViewButton BEGIN RCX_BUTTON DUP BUTTON_GET @ 2 AND UNTIL . I'll describe them all for you. pbFORTH Words pbFORTH includes 34 words that perform RCX-specific functions. For example. Each word's name is listed along with the starting and ending state of the stack. which corresponds to the View button on the RCX. then x2 and x3. which retrieves the current state of the buttons into the RCX_BUTTON variable. : oneToTen 11 1 DO I . In this section.126 value of the loop index on the stack with the I word. BEGIN body UNTIL This loop performs its body until a false condition is left on the stack.endStack) For example. executing its body each time through the loop. like this: WORD_NAME (startStack -. Then the value of RCX_BUTTON is retrieved (with @) and compared to 2. The MOTOR_SET word. ok oneToTen 1 2 3 4 5 6 7 8 9 10 ok limit start DO words delta +LOOP This variation on the basic DO LOOP adds the given delta value to the loop index instead of always adding one. You can use this type of loop to count backwards by supplying a negative delta. the following shows how to define a word that prints the numbers from 1 to 10. Then we call BUTTON_GET. If you push x1 on the stack. LOOP . BEGIN body AGAIN This variation on BEGIN UNTIL loops forever.x2 x1) The starting stack and ending stack are shown such that the top of the stack is shown on the right side. When this condition is true. The top of the stack is x3. the stack is empty. Output Control One word is devoted to controlling the RCX's outputs: MOTOR_SET (power mode index -. In your code. After you load pbFORTH on the RCX. and performs other important initializations.) This word turns an output on or off. should be 0. The top parameter. The power parameter should be 1 to 7.) This word starts the input and output handlers. system timers. The mode parameter indicates whether the output should be turned on going forward (1) or in reverse (2). B. buttons. 7 is power. or if it should be turned off in "brake" (3) or "float" (4) modes. or 2. For example: 7 CONSTANT OUT_FULL ok 2 CONSTANT FORWARD 4 CONSTANT FLOAT ok 2 CONSTANT OUT_3 ok OUT_FULL FORWARD OUT_3 MOTOR_SET ok OUT_FULL FLOAT OUT_3 MOTOR_SET Ok Front Panel Buttons pbFORTH provides two words that allow you to examine which front panels are pressed. the last thing is index. it comes out in the same order: 7 2 0 MOTOR_SET In this case. in float mode. It pops three parameters off the stack. The first thing you need to push on the stack is power. to turn on output 3 in full reverse. or C. In brake mode. it turns freely. The very first pbFORTH word initializes the RCX: RCX_INIT ( -. call this word before you try to do anything with the inputs. outputs. the motor shaft resists turning. and 0 is index. representing output A.127 After MOTOR_SET runs. respectively. where 7 is full power. 1. index. or other RCX services. . do this: 7 2 2 MOTOR_SET Remember that constants can make this kind of code a lot nicer. For example. 2 is mode. display numbers. Here's a word definition that retrieves the button state and places it on the top of the stack: : buttonState RCX_BUTTON DUP BUTTON_GET @ . you must call LCD_REFRESH: .) This word places the current button state into the variable address. The value placed in the variable tells which buttons are pressed and is a combination (boolean OR) of the values shown in Table 6-4. pbFORTH provides a variable. or clear the entire display. For changes to actually take effect.) This word initializes pbFORTH's button-handling system. BUTTON_GET Return Values Button Name Run View Prgm Value 1 2 4 For example. Figure 6-3 shows the display with most of its segments lit up." the input and output arrows. here's a handy word definition that tests if the Run button is pressed: : isRunButtonPressed buttonState 1 AND . the datalog indicators (which you might never have seen otherwise). Building on this. pbFORTH offers words that show and hide individual segments.128 BUTTON_INIT ( -. you'll need to use the POWER_GET word. Table 6-4. This is exciting news because you can display the results of your programs or even intermediate values. however. BUTTON_GET (address -. this includes the "little man. Remember. To test the state of the On-Off button. LCD Display Words pbFORTH provides direct control of the RCX's display. and the large numbers in the center. Make sure to call it once before you try to call BUTTON_GET. that you can use for this purpose. otherwise is won't work. RCX_BUTTON. if the Run and Prgm buttons are pressed simultaneously. the flags returned from BUTTON_GET will be 5. you have to call BUTTON_INIT before you use this word. Every segment of the LCD display can be controlled individually. described later in this chapter. 129 LCD_REFRESH ( -.) This word shows the number value on the display. The RCX's display pbFORTH can display a number from the stack with the following word: LCD_NUMBER (decimal value signed -. use the following: 3002 -1066 3001 LCD_NUMBER LCD_REFRESH . Values for the decimal Parameter of LCD_NUMBER Value (in hexadecimal) 3002 3003 3004 3005 any value Description No decimal point One digit after the decimal point Two digits after the decimal point Three digits after the decimal point Single digit on the right of the display (use 3017 for signed) Table 6-6. The state of the display will not change until you call LCD_REFRESH. if there is one. while the signed parameter determines whether value is shown as signed or unsigned. The decimal parameter controls the location of the decimal point. Values for the signed Parameter of LCD_NUMBER Value (in hexadecimal) 3001 301F 3017 Description Signed. Figure 6-3. The acceptable values of decimal and signed are shown in Table 6-5 and Table 6-6. no leading zeros Unsigned with leading zeros Single digit on the right of the display (ignores decimal) For example. Table 6-5.) Use this word after making changes to the display. to display the number -4198. 130 Note that we've specified the value in hexadecimal (-1066) but the display always shows decimal (-4198). LCD Segment Numbers Segment Number (Hex) 3006 3007 3008 3009 300A 300B 300C 300D 300E 300F 3010 3011 3012 3013 3014 3015 3016 3018 3019 301A 301B 301C (table continued on next page) Sequence? no no no no no no no no no no no no no no no no no yes (4) yes (5) yes (5) no no Description Standing figure Walking figure Input 1 selected Input 1 active Input 2 selected Input 2 active Input 3 selected Input 3 active Output A selected Output A backward Output A forward Output B selected Output B backward Output B forward Output C selected Output C backward Output C forward Datalog indicator segments Data transfer segments (ascending) Data transfer segments (descending) Low battery indicator Short range download indicator .) These words show or hide the given display segment. For example. you'll see one quarter. Do this three more times. basically everything except the numbers: LCD_SHOW (segment -. Valid values are shown in Table 6-7. Show 3018 again. The values that are flagged as a sequence can be repeatedly called to update the display automatically. and then all the quarters go blank and the sequence begins again. the datalog indicator (3018) consists of four quarters of a circle. and a second quarter lights up.) LCD_HIDE (segment -. The first time you show 3018. Table 6-7. pbFORTH provides two words that show or hide individual display segments. the fourth quarter lights up. and the third quarter lights up. Configuring inputs You probably remember that the RCX's inputs may be powered.) SENSOR_PASSIVE (index -. As before.) These words set the input described by index to be active (powered) or passive. corresponding to input 1. Table 6-8. Input Control Words Before you configure inputs or read values from them. all others are passive. index should be 0. the following words determine whether an input is active or passive: SENSOR_ACTIVE (index -. LCD Segment Numbers (continued) Segment Number (hex) 301D 3020 Sequence? no no Description Long range download indicator All segment (LCD_SHOW only) Conveniently. The light sensor. for example. is powered from an input. or 2. 1.) This word initializes pbFORTH's input system. The values for type are shown in Table 6-8. which describes the electrical characteristics of the sensor you. These types of sensors are called active. 2 or 3. 1.) This word clears the RCX's display so that no segments are lit. The index value should be 0.131 (table continued from previous page) Table 6-7. Call it once before working with inputs. you should initialize pbFORTH's input system with the following word: SENSOR_INIT ( -. you can clear the entire display with a single word: LCD_CLEAR ( -.) This word sets the type of an input. You can configure an input for a particular type and mode. or 2. In pbFORTH. Input Type Values Value 0 1 2 Description Raw Touch senso Temperature sensor (table continued on next page) . plan to attach. just as in NQC: SENSOR_TYPE (type index -. which is described later. A status code is placed on the stack. The modes are shown in Table 6-9.132 (table continued from previous page) Table 6-8.code) This word tells pbFORTH to read the value of the specified input. Input Mode Values Value (hex) 0 20 40 60 80 A0 C0 E0 Description Raw sensor value from 0 to 1023 Boolean. If code is 0. First. . you need to tell pbFORTH to go and read the input values: SENSOR_READ (index -. Values other than 0 indicate that the RCX was busy and could not read the input value. then the read was successful. Table 6-9. either 1 or 0 Counts transitions from 1 to 0 and vice versa (edge counting) Counts transitions from 1 to 0 (pulse counting) Percent from 0 to 100 Celsius temperature Fahrenheit temperature Shaft angle. An input's mode determines how the sensor values will be interpreted. The actual value can be retrieved with a call to SENSOR_GET. 16 counts per full revolution The following example shows how you could configure input 3 for a light sensor: 2 CONSTANT INPUT_3 ok SENSOR_INIT ok INPUT_3 SENSOR_ACTIVE ok 3 INPUT_3 SENSOR_TYPE ok 80 INPUT_3 SENSOR_MODE ok Reading input values Reading input values in pbFORTH is a two-step process. Input Type Values (continued) Value 3 4 Description Light sensor Rotation sensor SENSOR_MODE (mode index -.) This word sets the mode of the given input. you should really check the return code from SENSOR_READ to make sure it was successful. For these modes.133 Having read an input value. Finally. the current count of an input can be reset to 0 using SENSOR_CLEAR. SENSOR_RAW (index--value) Use this word to obtain the raw value of the input described by index. . The timers count up once every tenth of a second and have values from 0 to 7FFF (hexadecimal): TIMER_SET (value index--) This word sets the timer described by index to the supplied value. Four of these timers count in tenth-of-a-second intervals. The raw value will always be in the range from 0 to 1023. For example. There are also 10 timers with a hundredth-second resolution. like the edge counting. you are now ready to retrieve it using one of the following words: SENSOR_VALUE (index--value) This word returns the value of the given input. RCX Timers The RCX has 14 timers that you can use in your programs. Strictly speaking. Each of these timers is identified by an index. SENSOR_BOOL (index--value) This word returns the current value of the given input as a Forth-style boolean. of course. TIMER_GET (index--value) This word places the current value of the timer described by index on the stack. These timers have an index from 0 to 9. timer_GET (index--value) This word places the current value of the timer described by index on the stack. pulse counting. . from 0 to 3. they count down instead of up and stop when they reach 0: timer_SET (value index--) This word sets the timer described by index to the supplied value. The range of the returned value is determined by the mode of the input. you would do this: : read 2 SENSOR_READ 2 SENSOR_VALUE . the current value of an input can be reset with the following word: SENSOR_CLEAR (index--) Some of the input modes count values. and rotation modes. to read the value of the sensor on input 3. say overnight. however. it just goes into a low power consumption mode until you press the On-Off button to turn it on. Note that this does not clear the display. turn off active inputs. Three words in pbFORTH are related to power: POWER_INIT (--) This word initializes pbFORTH's power management. which can have the values shown in Table 6-11. The possibilities are shown in Table 6–10. POWER_GET Code and Value Possibilities Code (hex) 4000 4001 Value On-Off button state: 0 is pressed. Table 6-11. you should probably do this if you're going to stop using pbFORTH for a while. depending on the value of code. It doesn't actually turn off completely. pbFORTH can play the built-in beep sounds of the RCX. It does. This is exactly the same behavior as with the default RCX firmware. POWER_OFF (--) Use this word to turn the RCX off. The result is placed in the variable represented by address. The two words related to sound are: SOUND_PLAY (sound code--) This word plays the sound described by the sound parameter. although it does not offer the possibility of playing arbitrary notes. put the interpreter in a kind of sleep mode. 11E ok Sounds Finally. or turn off running outputs.134 Power Management pbFORTH includes a simple power management scheme that allows you to turn the unit off. Table 6-10. SOUND_PLAY Sounds Sound Number 0 1 Description Short beep Two medium beeps (table continued on next page) . POWER_GET (address code--) This word serves two purposes. pbFORTH provides the RCX_POWER variable for use with this word. 2 is not pressed Current battery level The following example shows how to print out the current battery level: RCX_POWER DUP 4001 POWER_GET @ . A zero indicates that the sound system is not busy. Cooperative multitasking allows multiple tasks to appear to run simultaneously. which you've seen in NQC and will see again in legOS. which is a good demonstration of the use of multiple tasks in pbFORTH.0. on the other hand. waits for the sound system to finish whatever it's doing and then plays. This includes space for user variables and space for a parameter and return stack. interrupting each task to give control to the next task.e. The basic procedure for running a multitasking program has four steps: 1. In reality. Take a look at the tortask. then the unqueued sound will not be played at all. the sound system is already busy). each task must voluntarily yield control to the next task in line. If your robot has a task that is going to do any lengthy processing. Unqueued sounds will be played right away if no sound is currently playing. Here's a sample from tortask.. The pbFORTH web page has more information on cooperative multitasking. the task needs to be structured so that it can yield control frequently. First. SOUND_GET (address --) This word returns the current state of the sound system to the given variable. SOUND_PLAY Sounds (continued) Sound Number 2 3 4 5 Description Descending arpeggio Ascending arpeggio Long low note Quick ascending arpeggio (same as 3 but faster) The sounds can be either unqueued or queued. A queued sound. You can use the pbFORTH-supplied variable RCX_SOUND for this word. If a sound is currently playing (i.5 introduced words that support cooperative multitasking.txt: 0 32 CELLS 32 CELLS ALLOT_TASK MOTOR_TASK . Any other value means that the sound system is busy playing another sound. Cooperative Multitasking pbFORTH version 1.135 (table continued from previous page) Table 6-11. you need to allocate space for each task using the ALLOT_TASK word. the system gives little bits of time to each task. With preemptive multitasking. is called preemptive multitasking. Cooperative multitasking is a little tricky to program because each task needs to explicitly yield control to the other tasks. The value of code determines if a sound is queued (4003) or unqueued (4004). The other kind of multitasking.txt example. for example. EXECUTE 4. EXECUTE The ACTIVATE word associates MOTOR_TASK with the rest of the NONAME definition. 2. we want it to look like this: BEGIN UPDATE_MOTORS PAUSE AGAIN The real work of the task is in UPDATE_MOTORS. To link the code into the task list. which can be used only inside a definition. each task must be built into a list. Basically. Next. (The combination of NONAME and EXECUTE allows you to execute a defined word just one time. almost like a variable definition. When one task voluntarily gives up control (cooperates). use AWAKE.txt example sets up its other three tasks in the same way: :NONAME TIMER_TASK ACTIVATE BEGIN UPDATE_TIMERS PAUSE AGAIN . Consider. we need another special word. To associate this loop with MOTOR_TASK. which is simply the endless BEGIN AGAIN loop. The PAUSE word is the key to cooperative multitasking-it passes control to the next task in the list.txt. three other tasks are allocated in the same way: 0 32 CELLS 32 CELLS ALLOT_TASK TIMER_TASK 0 32 CELLS 32 CELLS ALLOT_TASK SENSOR_TASK 0 32 CELLS 32 CELLS ALLOT_TASK DISPLAY_TASK Notice how the name of the new task is specified after the ALLOT_TASK word. to bytes. a word that examines some other values in the system and sets the state of the motors. This is done with the ACTIVATE word. ACTIVATE: :NONAME MOTOR_TASK ACTIVATE BEGIN UPDATE_MOTORS PAUSE AGAIN . the NONAME definition is executed. like this: DISPLAY_TASK AWAKE SENSOR_TASK AWAKE TIMER_TASK AWAKE MOTOR_TASK AWAKE . the next task in the list will get control. The line above allocates no space for user variables and 32 cells each for the parameter stack and return stack. The BUILD word assembles tasks into a list: MOTOR_TASK BUILD TIMER_TASK BUILD SENSOR_TASK BUILD DISPLAY_TASK BUILD 3. which are the fundamental units of Forth memory. EXECUTE :NONAME SENSOR_TASK ACTIVATE BEGIN UPDATE_SENSORS PAUSE AGAIN . Next.) The tortast. the MOTOR_TASK. The name of the new task is MOTOR_TASK. you can't execute the defined word again later. EXECUTE :NONAME DISPLAY_TASK ACTIVATE BEGIN UPDATE_DISPLAY PAUSE AGAIN .136 The CELLS word simply converts a number on the stack from cells. Because it doesn't have a name. To actually start the tasks running. In tortast. you need to actually define what each task does. To run this program. We'll build a simple Celsius thermometer using a temperature sensor. : showTemperature 3003 SWAP 3001 LCD_NUMBER LCD_REFRESH . : thermometer RCX_INIT SENSOR_INIT BUTTON_INIT 2 1 SENSOR_TYPE A0 1 SENSOR_MODE BEGIN BEGIN 1 SENSOR_READ 0= UNTIL 1 SENSOR_VALUE showTemperature isRunButtonPressed UNTIL clear . : clear LCD_CLEAR LCD_REFRESH . The clear word simply erases the entire display using the LCD_CLEAR word. : isRunButtonPressed buttonState 1 AND . ShowTemperature takes the top item on the stack and shows it on the display with the decimal point placed to show tenths. . The LCD display will show the temperature read by the sensor until you press the Run button. An Expensive Thermometer This section contains an example that will help you get your feet wet with pbFORTH. This is how thermometer knows to stop running. use the thermometer word.137 To dive into this a little more. check out the whole tortask. Hook the sensor up to input 2 and enter the following (I've omitted pbFORTH's ''ok" responses for clarity): HEX : buttonState RCX_BUTTON DUP BUTTON_GET @ . The isRunButtonPressed word simply tests to see if Run has been pressed.txt example at the pbFORTH web site. using the buttonState word. Then the actual input value is read using SENSOR_VALUE. we fall out of the loop.138 The main program. It then configures input 1 for a temperature sensing using the temperature type (2) and the Celsius mode (A0). Make Your Own Sensors. To retrieve the input value we first have to call SENSOR_READ. begins by initializing the RCX and the input and button systems. let's rewrite Minerva's software in pbFORTH. Minerva. : showValue 3002 SWAP 3001 LCD_NUMBER LCD_REFRESH . such that the most sophisticated words are at the end. the challenge with Forth is to break the large problem into pieces that are small enough to be understood easily. see Chapter 5. Each time through the loop we call isRunButtonPressed. A call to clear cleans up the display. HEX : initialize RCX_INIT SENSOR_INIT 2 SENSOR_ACTIVE 3 2 SENSOR_TYPE 80 2 SENSOR_MODE . . and then thermometer is done. If you bought LEGO's temperature sensor. shows how you can build your own temperature sensor. The main part of temperature is a BEGIN UNTIL loop that reads a value from the input and shows it on the display. a Robot with an Arm. They are defined in bottomup fashion. You could use that code to make a digital thermometer for only about $202. you now have yourself a $225 digital thermometer. if the button is pressed. indicating success. A call to showTemperature puts the input value on the display.) As with any other language. (For a full description of this robot. : sleep 0 0 TIMER_SET BEGIN DUP 0 TIMER_GET = UNTIL DROP . Minerva Revisited To really put pbFORTH through its paces. thermometer. Here's a set of words that will run Minerva. This call is inside its own BEGIN UNTIL loop that waits for SENSOR_READ to return 0. Chapter 11. : spin 7 2 2 MOTOR_SET . : forward 7 1 2 MOTOR_SET . : release armRelease BEGIN 2 sensorValue 100 = UNTIL armGrab BEGIN 2 sensorValue 100 < UNTIL armStop . : armStop 7 3 0 MOTOR_SET . : armRelease 7 2 0 MOTOR_SET . : stop 7 3 2 MOTOR_SET . . : turnAround spin TURNAROUND_TIME sleep stop .139 DECIMAL 42 CONSTANT TURNAROUND_TIME 10 CONSTANT NUMBER_OF_SAMPLES VARIABLE threshold VARIABLE returnTime : sensorValue BEGIN DUP SENSOR_READ 0= UNTIL SENSOR_VALUE . : armGrab 7 1 0 MOTOR_SET . : grab armGrab BEGIN 2 sensorValue 100 = UNTIL armRelease BEGIN 2 sensorValue 100 < UNTIL armStop . : calibrate 0 NUMBER_OF_SAMPLES 0 DO 2 sensorValue + 1 sleep LOOP NUMBER_OF_SAMPLES / threshold ! threshold @ showValue . Then grab is called to grab the object. : Minerva initialize calibrate 5 0 DO retrieve LOOP . Finally. and turns around again with turnAround. the more complex words are simply combinations of the earlier ones. Then it calls calibrate to take an average reading of the light sensor. pretty much describes itself. The pbFORTH implementation of Minerva's program closely resembles the NQC version of the program presented in Chapter 5. : return forward returnTime @ sleep stop . The retrieve word is also pretty self-explanatory. Minerva. calling retrieve to go pick up something and bring it back. which includes configuring input 3 as a light sensor input. with release. Minerva turns around and heads back to her starting point with turnAround and return. retrieve is a highly readable piece of programming: : retrieve seek .140 : seek forward 0 1 TIMER_SET BEGIN 2 sensorValue threshold @ 3 . Keep this in mind—I'll describe the words in Minerva's program starting at the end and returning to the beginning. With the simpler words defined correctly. It calls seek to drive forward and look for an object to pick up. Then she drops the object. It initializes the RCX. The main program word. it loops five times.< UNTIL 2 sleep 1 TIMER_GET returnTime ! stop . By the time all the simpler words are defined. : retrieve seek grab turnAround return release turnAround . seek first sets timer 1 to 0 like this: 0 1 TIMER_SET Then Minerva moves forward until she "sees" something to pick up. calculating an average is a simple matter of division: NUMBER_OF_SAMPLES / Then the average value is stored in the threshold variable: threshold ! . we just need to drive back for the stored amount of time: : return forward returnTime @ sleep stop . Timer 1 is used for this purpose. we read the value of input 3 and add it to the running total on the stack. returnTime. The interesting thing about seek is that it uses one of the RCX's timers to figure out how long Minerva moves forward before finding something to pick up. the total is zero: : calibrate 0 Then we just run in a loop from 0 to the constant value NUMBER_OF_SAMPLES. We begin by pushing the current running total on to the stack. in returnTime. I won't describe every word in Minerva's program. by calling 1 sleep: NUMBER_OF_SAMPLES 0 DO 2 sensorValue + 1 sleep LOOP Once this is done.141 grab turnAround return release turnAround . This is done every tenth of a second. To begin with. but I do want to cover the more interesting ones. the sleep word uses timer 0. This value is used to determine if the light sensor "sees" something that can be picked up or not. Each time through the loop. let's take a look at seek and return. like this: 1 TIMER_GET returnTime ! When it's time for Minerva to drive back to her starting point. First. Another interesting word is calibrate. The current timer value is recorded in a variable. which takes ten readings of the light sensor and calculates an average value. If you entered all of the Minerva source code. The interactive nature of the pbFORTH interpreter can really help. In this case. Any word that is defined can be interactively tested.142 Finally. This makes it easy to drill down from the higher layers to the lower layers of your program to identify problems. With legOS (see Chapter 10). is used in the seek word to find a dark object to pick up. With pbFORTH. try this: initialize ok ∗ Interestingly. You should use the MARKER word. they just mask them out. This is powerful medicine indeed.< UNTIL Debugging When you're writing your own programs. you can interactively test every word in your program. you could do this: 5 sleep ok To test out the calibrate word. you will have to use your firmware download utility to reload pbFORTH. you'd have to compile and download a whole new version of your software. for example. the average value is shown on the RCX's display: threshold @ showValue The average value. to show a number on the display. new definitions don't replace the old ones. do something like this: RCX_INIT ok 42 showValue ok To pause for half a second. 2. you need to be very careful about endless loops. make changes in a word by redefining it. seek drives forward until the light sensor returns a reading that is 3 less than the average: BEGIN 2 sensorValue threshold @ 3 . For example. On the other hand.∗ Furthermore. as an added bonus. . threshold. you can interactively test any of its words. by contrast. You can. there are two things you should keep in mind when you are debugging: 1. you can simply make new definitions for the words that aren't working. See the pbFORTH web site for details. If you do get stuck executing an endless loop. there's no way to stop pbFORTH short of removing the batteries. If you want to return to an earlier definition. pdf This is one of the resources available from the Forth Interest Group Home Page (see the previous entry). If you want to learn more about Forth.enteract.html This is the home page for NQC. offers the current version of pbFORTH here.taygeta. Forth Interest Group Home Page. Online Resources Forth for Mindstorms. It's listed here because nqc can be used to download the pbFORTH firmware to the RCX. it's a good general introduction to the language itself (see its chapters 1 through 5). The best way to program with pbFORTH is to put your program in a text file on your PC.txt). The main thing to keep in mind is to break your programs into small pieces that can be easily tested and debugged. creator of pbFORTH.143 calibrate ok By now. Ralph Hempel.forth. You can modify the text source file to make changes or fix bugs and redownload the new word definitions each time you want to test the program.html This page describes some tools created by Ralph Hempel to make it easier to work with pbFORTH. Tim Hendtlass's Real Time Forth Book. When you're ready to give it a try. Although it describes a specific version in some detail.com/lego/pbFORTH/ This is the center of the pbFORTH universe.hempeldesigngroup. You can also get the source code. this is a great place to start. The tools are based on Tcl/Tk.org/ This site is a good jumping-off point for all sorts of interesting information about the Forth language.com/~dbaum/lego/nqc/index. you can't retrieve a word definition from pbFORTH. NQC—Not Quite C. .com/pub/Forth/Literature/rtfv5.hempeldesigngroup.com/lego/pbFORTH/rcxTkGUI. you are probably getting a feel for this software. download the file to pbFORTH and test it out. Interestingly. and helpful advice and pointers. sample Forth programs (including tortask. It is a tutorial introduction to Forth. pbFORTH rcxTk GUI. and extra RCX's. You can also get touch sensors.com/ This online store offers various useful items like the temperature sensor used in this chapter. . the source code is available in C and should compile on most platforms. light sensors. rotation sensors.c Another popular firmware downloader is firmdl.edu/~kekoa/rcx/firmdl.144 firmdl. LEGO World Shop. more motors. Written by Kekoa Proudfoot.stanford. One of Minerva's shortcomings. Minerva also needs a new program that will respond to incoming IR messages. Build leader and follower robots. by itself. She simply drives forward. for about $120US. of course. With two RCXs. One way to improve Minerva's performance is to have a human being control her. This chapter describes the construction and programming of a remote control for Minerva. a Robot with an Arm. Two Heads Are Better Than One If you're a MINDSTORMS enthusiast. you're probably always hoping to get more stuff: more motors. if you can afford it or if you can convince somebody to buy it for you. It is based on a second RCX. Minerva. This is called teleoperation or telerobotics.145 7 A Remote Control for Minerva In this chapter: • Two Heads Are Better Than One • The Allure of Telerobotics • Building Instructions • Programming the Remote Control • Programming Minerva • Online Resources In Chapter 5. you can buy a single RCX. If you're on a tighter budget. The two RCXs can coordinate their actions by communicating over the IR port. you can build a robot with six outputs and six inputs. however. 2. A second RIS set is a great investment. Build a giant robot. If you have a friend with a MINDSTORMS set. you read about a mechanically complex robot that could be built from one RIS kit. more sensors. of course. This chapter illustrates this technique by describing how to build a remote control for Minerva. There are several interesting things you can do with two RCXs: 1. you can always pool your resources. One robot tells the other robot what to do by issuing commands over the IR port. looking with her light sensor for something dark. . is that she isn't very smart about searching out things to pick up. and a better programming environment than RCX Code. which sends IR messages to Minerva. 146 3. Have a robot competition. In Chapter 9, RoboTag, a Game for Two Robots, I'll talk about one possible robot competition. There are many other types of competitions. You and a friend could build robots to accomplish a specific task. Then you could see whose robot performs better. The "Online Resources" section at the end of this chapter lists some existing competitions. You might think that having three or more RCXs would be even better, but it actually complicates things considerably. Although IR communication between two RCXs is fairly straightforward, it gets messy with three or more RCXs. How do you know if an IR message is destined for a specific RCX? A simple solution is to assign a specific range of message values to various message pathways. For example, with three RCXs, named RCX1, RCX2, and RCX3, you might assign the message numbers as shown in Table 7-1. Table 7-1. Sample Message Assignments for Three-way RCX Communication Message Numbers 0 to 9 10 to 19 20 to 29 Message Pathway (Two-way) RCX1 to RCX2 RCX1 to RCX3 RCX2 to RCX3 A more general solution may someday be supplied by the LEGO Network Protocol, a work in progress in the online MINDSTORMS community (see the "Online Resources" for more information). The Allure of Telerobotics Replacing the function of your robot's brain with that of a human brain is appealing in many situations. It's easy to program a robot to do the same task over and over again. However, if the task changes or if the environment changes, the robot may have a hard time adjusting. Humans are much better at adapting to new conditions. On the other hand, telerobotics is a kind of cheating. Part of the point of autonomous mobile robots is that you can set them running and forget about them until they're done with whatever they're doing. If you build a robotic vacuum cleaner, you want to set it running and forget about it until it's done cleaning your floors. If you used a teleoperated robotic vacuum cleaner, you'd spend just as much time cleaning as with a conventional vacuum cleaner. In the simplest form of telerobotics, the human can see the robot and can control it much as you might play with a radio control car. This is basically how the remote control for Minerva works: you can see Minerva and control it by sending IR messages from the remote control. 147 More sophisticated telerobots have a video camera that sends pictures back to a human operator. The operator can see what the robot sees and can send commands to control the robot. Teleoperation does not work well if the human operator and the remote robot are separated by a very large distance, such as the distance between Mars and the Earth. In this case, the video signals from the robot take a long time to reach the operator, and the control signals from the operator take a long time to reach the robot. What the operator sees is really a second or two behind what's actually happening, so it's very hard to control the robot with any precision. Fortunately, you don't have to worry about this with Minerva. Because the remote and the robot communicate with IR light, there must always be a line-of-sight between them. If you can control the robot, you can see it—there's no video connection to add confusion. Building Instructions The controls for the remote are built on the bottom of the RCX. This was a conscious design decision—it orients the IR port of the remote in the best place to broadcast commands to Minerva. 148 Attach the light sensor and wire bricks as shown. The light sensor goes on input 1, while the two wire bricks (which will be attached to the touch sensors) go to input 2 and input 3. If you get these two wires backwards, you'll know when you push the joystick backward and the robot moves forward. You can easily swap the two connectors later. The two touch sensors are triggered by a joystick-like lever contraption. Only one of the sensors will ever be triggered at a time. 149 The next step shows the joystick, which is really a simple lever. 150 Put the joystick, from Step 5, into the assemblies from Step 6. Fasten it together with the two yellow plates. Then put the whole thing on the remote assembly. When you wiggle the joystick back and forth, it pushes one or the other touch sensor. Step 8 might not look like much, but it's important. It's the slider that controls Minerva's arm. It slides past the light sensor, presenting either a yellow or a black brick to the sensor. This is how the RCX knows if you've moved the slider. In Step 9, the slider gets mounted on the remote. Make sure it slides freely, and note that it's upside-down with respect to the rest of the construction. The orientation of the yellow and black bricks in the slider will make a difference in how the arm is controlled. If you don't like how it works when it's all together, you can always switch it around later. If Minerva doesn't hear this message. SENSOR_TOUCH). and the third task sends the heartbeat signal. SetSensor(SENSOR_3. SENSOR_LIGHT). the remote responds to these by telling Minerva to move forward or spin. Here is the code for those tasks: #define #define #define #define #define #define FORWARD_MESSAGE 16 SPIN_MESSAGE 17 STOP_MESSAGE 18 GRAB_MESSAGE 19 RELEASE_MESSAGE 20 HEARTBEAT_MESSAGE 21 #define HEARTBEAT_TIME 20 task main() { SetSensor(SENSOR_1. SENSOR_TOUCH). one task monitors the light sensor. The remote uses three different tasks to get everything done.151 Programming the Remote Control The remote control doesn't really have to do much. One task monitors the touch sensors. . The joystick control triggers the two touch sensors. One final feature is a ''heartbeat"—a special message that the remote periodically sends to Minerva. The slider control is used to move Minerva's arm up or down. SetSensor(SENSOR_2. it knows it has lost contact with the remote. It responds to its sensors by sending commands to Minerva. 10). 10).TOLERANCE) && lastArmMessage != RELEASE_MESSAGE) { PlayTone(494. 10). } . int minimum. until (SENSOR_2 == 0). int midline. SendMessage (STOP_MESSAGE). } task touchWatcher() { while (true) { if (SENSOR_2 == 1) { SendMessage (FORWARD_MESSAGE). while (true) { current = SENSOR_1. Wait(10). SendMessage(GRAB_MESSAGE). if (current > maximum) maximum = current. 10). PlayTone(660.152 start lightWatcher. } } } #define TOLERANCE 3 int current. midline = minimum + (maximum . int maximum. if (SENSOR_1 <= (midline . lastArmMessage = GRAB_MESSAGE. if (current < minimum) minimum = current. start heartbeat. task lightWatcher() { minimum = 100. until (SENSOR_3 == 0). int lastArmMessage. maximum = 0. Wait(10). SendMessage (RELEASE_MESSAGE). start touchWatcher. SendMessage (STOP_MESSAGE).minimum) / 2. PlayTone(494. } if (SENSOR_1 >= (middle + TOLERANCE) && lastArmMessage != GRAB_MESSAGE) { PlayTone(660. } if (SENSOR_3 == 1) { SendMessage (SPIN_MESSAGE). lastArmMessage = RELEASE_MESSAGE. Just what exactly what "light" and "dark" are is a little tricky to define. When one is detected. if (current > maximum) maximum = current.153 } } task heartbeat() { while (true) { SendMessage (HEARTBEAT_MESSAGE). A dark-to-light transition causes the remote to send a grab command to Minerva. . between the steady states of off and on. if (current < minimum) minimum = current. Debouncing is a way of making touch sensors (and buttons in general) work reliably. Then the task waits for the touch sensor to be released and sends a stop command to Minerva. it's an example of a technique called debouncing. the remote uses a scheme to calibrate itself on the fly. The touchWatcher task is fairly straightforward. and it occurs while you're pressing or releasing the switch. Wait (HEARTBEAT_TIME). It listens for a touch on either touch sensor. the remote tells Minerva to release the grabber. } } The main task configures the inputs on the remote control and starts up the other tasks. The basic problem occurs just at the point where you press the touch sensor enough to make its state change from off to on. The call to Wait(10) deserves more mention. This effect is called bounce. If the sensor value changes from light to dark. Bounce can be eliminated with an electronic circuit or by special programming. but then the remote had to be reprogrammed depending on whether I was using it in daylight or at night. The slider on the remote changes the value of the light sensor. lightWatcher also keeps track of the last grabber arm command it sent to avoid unnecessarily sending the same command twice. midline = minimum + (maximum . Then lightWatcher calculates the midpoint of the minimum and maximum values. lightWatcher is the task that monitors the light sensor. This value is used to determine exactly what light and dark values cause the remote to fire commands to Minerva. The call to Wait(10)gives the touch sensor signal a chance to settle down before touchWatcher starts looking for the release of the touch sensor. I had originally hard-coded light values.minimum) / 2. Tiny motions or electrical variations can cause the touch sensor's output to switch back and forth very quickly between on and off. It keeps track of its minimum and maximum light readings in the minimum and maximum variables. as I've done here. the remote sends out an IR command to Minerva to go forward or to spin in place. as shown here: current = SENSOR_1. Instead. If she doesn't hear them. must listen for incoming messages on the IR port and respond to them. lightWatcher plays tones when it sends the grab or release commands. so you can change the direction of the arm as it's moving. heartbeatWatcher assumes it has lost contact with the remote. heartbeatWatcher starts up messageWatcher once again. but it's complicated by two things: 1. The hearbeat task is very simple. The heartbeatWatcher adds one to this count. The human operator should be able to change the direction of the arm as it is moving. When messageWatcher receives a heartbeat. When one arrives. Programming Minerva Minerva's program. kept in the missedBeats variable. They are separate tasks so that messageWatcher can continue to receive commands from the remote while the arm is moving. grab and release The grab and release tasks are kicked off by messageWatcher to control Minerva's arm. When the heartbeat is heard again. 2. Minerva's program is split into four primary tasks: message Watcher The messagewatcher task examines the IR port for incoming messages.154 To provide some feedback to the human operator. Here's the entire program. grab and release have the ability to interrupt each other. however. for example. It then stops the messageWatcher task and shuts down the robot's motors. start driving forward while the arm was grabbing. This feature. It repeatedly sends the heartbeat command to the IR port. if it's ever more than one. it is examined and the appropriate action is taken. she should stop what she's doing until the IR link is established again. it subtracts one from a tally of missing heartbeats. I'll describe more of the details after the listing. You could. heartbeatWatcher This task keeps count of missing heartbeats. then. without waiting for an entire grab or release cycle to be completed. should not interfere with Minerva's ability to stop the arm when it moves up as far as it can go. This is fairly simple. Minerva should listen for the heartbeat commands from the remote. . } else if (message == RELEASE_MESSAGE) { start release. task main() { SetSensor (SENSOR_3. start heartbeatWatcher. ClearMessage(). } else if (message == HEARTBEAT_MESSAGE) { missedBeats = missedBeats . } else if (message == GRAB_MESSAGE) { start grab. ClearMessage(). SENSOR_LIGHT). } else if (message == SPIN_MESSAGE) { OnRev(OUT_C). } } } task grab() { until (armLock == 0). if (message == FORWARD_MESSAGE) { OnFwd(OUT_C). } task messageWatcher() { while (true) { message = Message().1. . } else if (message == STOP_MESSAGE) { Off(OUT_C). ClearMessage(). int armLock. ClearMessage(). missedBeats = 0.155 #define #define #define #define #define #define FORWARD_MESSAGE 16 SPIN_MESSAGE 17 STOP_MESSAGE 18 GRAB_MESSAGE 19 RELEASE_MESSAGE 20 HEARTBEAT_MESSAGE 21 #define HEARTBEAT_TIME 20 int message. start messageWatcher. int missedBeats. ClearMessage(). armLock = 0. ClearMessage(). until (armLock == 0). until (SENSOR_3 != 100). stop grab.156 stop release. Since the arm is already at the top of its travel. } missedBeats = missedBeats + 1. Wait(HEARTBEAT_TIME). OnFwd(OUT_A). OnRev(OUT_A). until (Message () == HEARTBEAT_MESSAGE). armLock = 0. armLock. start messageWatcher. They use a variable. suppose grab starts up. Before the touch sensor is released. stop messageWatcher. until (SENSOR_3 == 100). have the ability to interrupt each other. so grab starts running the motor in reverse. Off(OUT_A). to avoid potentially dangerous situations. armLock = 1. until (SENSOR_3 == 100). missedBeats = 0. It's already pressed. OnFwd(OUT_A). It stops release and runs the motor forward until the touch sensor is pressed. suppose that release is running. until (SENSOR_3 != 100). Off(OUT_A). It drives the arm motor in reverse until the arm is up and the limit touch sensor is pressed. armLock = 1. OnRev(OUT_A). } } Don't Break That Arm The grab and release tasks. Off(OUT_C). running the arm motor in reverse creates pressure on the gears and will either break the arm apart or cause the gears to skip. } task release() { until (armLock == 0). however. For example. waiting for the touch sensor to be released. PlaySound(SOUND_UP). armLock = 0. Off(OUT_A). as I said. . } task heartbeatWatcher () { while (true) { if (missedBeats > 1) { PlaySound (SOUND_DOWN). Then the motor is run forward to release the touch sensor. and starts up messageWatcher again: until (Message() == HEARTBEAT_MESSAGE). This means Minerva should never break her own arm. however. If it is regained. First. missedBeats = 0. a sound is played (the descending arpeggio). resets missedBeats. Off(OUT_A). like this: until (armLock == 0). stop messageWatcher. This lets the human operator know that contact with the remote has been lost. but it respects the armLock variable so the arm is not left in an uncertain state: until (armLock == 0). Both grab and release wait for armLock to be 0 before interrupting the other task. Then heartbeatWatcher shuts down the messageWatcher task and turns off Minerva's drive motor: PlaySound(SOUND_DOWN).157 Using the armLock variable enables grab and release to complete the press-release cycle of the arm limit switch without being interrupted. Now heartbeatWatcher waits to regain the heartbeat signal from the remote. heartbeatWatcher shuts Minerva down. start messageWatcher. the messageWatcher task is subtracting from missedBeats every time it hears the heartbeat message. heartbeatWatcher plays another sound (the ascending arpeggio). Off(OUT_C). . It adds one to the missedBeats variable just as often as it expects the remote to send a heartbeat. Stayin' Alive The heartbeatWatcher task also deserves some mention. heartbeatWatcher also wants to shut down Minerva's arm motor. If missedBeats is ever greater than one. PlaySound(SOUND_UP). Remember that just as heartbeatWatcher is adding to missedBeats. This shutdown is not as straightforward as you might think. The grab and release tasks set armLock to 1 before doing the sensitive press-release cycle. You can register online. which includes a robotic challenge and competition. to participate.net/joel/Challenge.html The Robot Arena is another robot competition in the San Francisco Bay area. Challenges and Competitions Events. you build a robot to accomplish the objective.html The Thames Science Center. FIRST LEGO LEAGUE. RCX Challenge. hosts monthly challenges for robot builders of all ages. Each challenge consists of an objective.legomindstorms.azimuthmedia. in Newport. the challenge is to build a robot that can navigate a room to pick up empty soda cans. If you're considering hosting your own robot competition. Teams can register to be a part of FLL.thamesscience.com/robotics/events/ This is the home page for the robotics events discussion group at LUGNET.com/RobotArena/mainframe.events newsgroup. Lego Mindstorms Robot Arena. you might want to check out Joel's rules. you can view its genesis in the discussion groups at LUGNET. check back here often or subscribe to the lugnet. .robotics.lugnet.lugnet.org/program1. programs. Then bring in your robot and see how it compares to other designs.com/first/ FIRST LEGO LEAGUE (FLL) is an organization for kids from 9 to 14.com/robotics/rcx/legos/?n=180&t=i&v=c Although the LEGO Network Protocol is not yet mature. To keep up on community activity related to challenges and competitions.html Designed by Joel Shafer. Rhode Island.158 Online Resources LEGO Network Protocol legOS: 180[LEGO Network Protocol discussion thread]. This URL points to a lengthy exchange from the middle of 1999. Because VB is so widespread in the Windows world. The programming environment that comes with RIS. including information and examples at Microsoft's site. There are several good online tutorials. Aside from providing better capabilities than RCX Code. The "Learning Edition" is $109US. and Subroutines • Tips • Retrieving the Datalog • Online Resources Part of the appeal of the programming environments described in Chapter 4. In this chapter. If you are running windows. The link between Visual Basic and your robots is a file called Spirit. as I'll describe in the next section. chances are good that you already have Visual Basic somewhere. You May Already Have Visual Basic Visual Basic is a programming language made by Microsoft.ocx Functions • Immediate and Delayed Gratification • Programs. I'll show you how to use Visual Basic and Spirit. A "Professional Edition.) Instead. is that they don't tie you down to using Windows on your development PC. Visual Basic is a language developed by Microsoft and included with many of their other products. this chapter focuses on how you can use VB to write programs for your RCX. pbFORTH. NQC and pbFORTH also allow you to develop RCX software using your operating system of choice. In this chapter. (See the "Online Resources" section at the end of this chapter for references. which is installed as part of the standard RIS software. I'll describe a Windows-only solution— programming your robots using Visual Basic (VB).159 8 Using Spirit. Tasks. and Chapter 6.ocx to control and program your robots." . is a Windows-only solution.ocx • Calling Spirit. I won't attempt to describe the language itself.ocx. which is distressing to people who prefer other operating systems. RCX Code. Not Quite C.ocx with Visual Basic In this chapter: • You May Already Have Visual Basic • About Spirit. You can purchase it as a separate product. Word. Don't be alarmed by the price tags. for example. and Access all include VBA. If you have more money to burn. If you're familiar with VC++. Spirit.ocx is the glue that links Windows applications to the RCX. or create programs on the RCX. is available for $279Us. but you could just as easily use one of the other incarnations of VB or VBA. Several similar packages are available online. The examples in this chapter were developed with VBA in Microsoft Word 97. you can use a very similar environment called BrickCommand. Excel. called Visual Basic for Applications (VBA). Figure 8-1 shows the software architecture.ocx on your computer. Spirit. Even if you don't have VB or VBA. BrickCommand allows you to program the RCX via Spirit.ocx is a collection of functions that send commands to the RCX.ocx Spirit. This chapter describes VB because it is simple and commonly available." for $1299US. If you installed the software from the RIS kit. You may already have Visual Basic without knowing it. Figure 8-1. In Word.ocx can also be used from Visual C++ (VC++). try the "Enterprise Edition. RCX software architecture .ocx. In essence. you already have Spirit. much the same way as you would using VB or VBA.160 with more bells and whistles. you can do this fairly easily. ask the RCX for information. The applications in the Microsoft Office software include a limited version of Visual Basic. which is quite similar to Figure 4-1 in Chapter 4. see the "Online Resources" section for details. About Spirit. there's a Visual Basic Editor menu item in the Macro submenu of the Tools menu. 10 . During this installation. choose Tools > Additional Controls. First Things First To begin with.ocx in the Tool Palette To reference Spirit.161 Like NQC. When you use VB again later. If you have any of the Microsoft Office applications. as shown in Figure 8-2. then click on OK. for example. To add it.ocx is a Windowsspecific piece of software.ocx we first need to put it in a user form. you can use VBA.ocx uses the default firmware that is loaded on the RCX and makes more features of the bytecode interpreter available than RCX Code. The control itself has a default name of Spiritil. Spirit.PlayTone 440. choose Tools > Macro > Visual Basic Editor. You only have to follow this procedure once. Create a new form by choosing Insert > UserForm. Select this item and place it on the form you just created. We won't use the form for anything except as a place to keep the Spirit. A new item with the familiar LEGO logo should now be in your tool palette. you should enter your VB or VBA environment.On "01" All you need to do is let VB know about the Spirit.SetWatch Hour (Now). Change the name to something like DummySpiritForm.∗ Click on the box to its left to select it.ocx control will automatically show up in your tool palette. Unlike NQC. In the window that appears. Spirit. scroll down to find Spirit Control in the list of available controls.ocx is registered with the system in such a way that VB or VBA can find it later. This process is described in the next few sections.ocx functions directly from VB or VBA with code like this: . just start it up.ocx control. A new form appears.ocx Functions The goal of this chapter is to enable you to call Spirit.ocx control. If you have a full version of VB installed. along with a tool palette labeled Toolbox.ocx does not appear in the tool palette. Minute (Now) . . Showing Spirit. In Word. the Spirit. which is just fine for our purposes.InitComm . Spirit. ∗ The Spirit Control item appears in the list only if you have already installed the LEGO MINDSTORMS software. Spirit. Calling Spirit. is DummySpiritForm. let's write some code to use it.Spirit1. It's little cumbersome to always refer to the full name of the Spirit.ocx.PlaySystemSound 0 .ocx control. make sure your RCX is on. Hello. Spirit Now that you've placed a Spirit.CloseComm End With End Sub . Then click on the play button in the toolbar. type the following to create a new subroutine: Sub HelloSpirit To call functions in Spirit. If all goes well. In the window that appears. looks like this: Sub HelloSpiritII () With DummySpiritForm.ocx control on a form.PlaySystemSound 0 DummySpiritForm.ocx in the tool palette You should glance over Spiritl's properties to make sure they're set up properly.Spirit1 .InitComm DummySpiritForm. check the ComPortNo property to be sure you'll be talking to the right serial port.Spiritl.InitComm . you should hear your RCX play a simple beep. It contains a Spirit. A simpler syntax. using With. then. Fill out the body of the HelloSpirit subroutine as follows: Sub HelloSpirit () DummySpiritForm.162 Figure 8-2.ocx control called Spiritl. Choose the Insert > Module menu item to create a new code module.Spiritl. Spirit.Spiritl. you need to reference the control by name.CloseComm End Sub To run this simple subroutine. The dummy form you created is DummySpiritForm. In particular. The full name of the control. 20 . 10 . The following subroutine redefines Program 5 on the RCX to play the same song: Sub ChargeProgram() With DummySpiritForm. delayed.PlayTone 659. For example.InitComm . you can store them for later.PlayTone 392.ocx can be immediate.PlayTone 523. 10 .PlayTone 392.EndOfTask Pause 1 . Onis both an immediate and delayed function. 10 . 10 . 10 .BeginOfTask 0 . The following subroutine plays a little song using the PlayTone function in its immediate mode: Sub Charge() With DummySpiritForm.PlayTone 659.Spirit1 .Spirit1 .PlayTone 784. Delayed functions can be placed inside a program and executed later. 10 . 20 . 10 . or you can call it to add it to a program that will be executed later. 20 .InitComm .PlayTone 659.PlayTone 659.163 Immediate and Delayed Gratification The functions in Spirit. An immediate function executes as soon as you call it. 20 .PlayTone 784. You can call it to turn on some outputs immediately.CloseComm End With End Sub Sub Pause(ByVal duration As Integer) Start = Timer Do While Timer < Start + duration Loop End Sub .PlayTone 784.PlayTone 784.CloseComm End With End Sub Instead of executing things on the RCX immediately.PlayTone 523. 10 .SelectPrgm 4 . or both. I'll explain more about tasks a little later. Without this pause. to give Spirit. Tasks.BeginOfTask 0 .ocx provides StartTask. you'll hear the song. The following example defines three tasks.ocx function in this example is BeginOfTask. and hence is exactly the same structure that I described for NQC in Chapter 4.ocx a chance to download the program to the RCX before calling CloseComm. The same restrictions on subroutines in NQC apply here. using StartTask. SelectPrgm expects a zero-based number. The next unfamiliar Spirit. you can call a subroutine with the GoSub function. just keep in mind that task 0 is run when you press the Run button on the RCX. subroutines cannot call other subroutines or themselves. you won't hear anything. Calling SelectPrgm 4 tells the RCX to switch to Program 5. the program does not get fully downloaded. Pause. Sub MultiTaskingProgram() With DummySpiritForm. Everything between the BeginOfTask and EndOfTask is stored as the task itself. StopTask. and StopAllTasks for controlling the execution of different tasks within a program.StartTask 1 . over and over. task 0 in a program is the task that is run when you press the Run button on the RCX. Task 0 simply runs the other tasks. But when you select Program 5 and press the Run button. from zero to four. Programs. for now. Subroutines are defined much the same way that tasks are defined.Spirit1 . ChargeProgram uses a helper subroutine.InitComm . while task 2 runs the motors forward and reverse ad infinitum. representing the RCX's programs from one through five. It's up to that task to start whatever other tasks you've defined. and Subroutines Each of the RCX's five programs is made up of one to ten tasks and zero to eight subroutines.SelectPrgm 3 . It simply waits for a second before shutting down the communication link to the RCX.164 When you run ChargeProgram. by framing some set of function calls with the BeginOfSub and EndOfSub functions. There's one final tweak I should mention. Spirit. You have just downloaded a program to the RCX from Visual Basic! This example uses SelectPrgm to select the RCX's current program number. As you learned in the last example. This structure is dictated by the RCX firmware. Within a task. Task 1 sings a song. the current status of the RCX's outputs. 0.While 0. Task 1 plays a song over and over.SetFwd "02" . LEGO's official Technical Reference Document (see the ''Online Resources") does a good job describing the syntax of Spirit.Wait 2.PlayTone 659. 2. including input values (in several different forms). this section contains down-toearth information on using Spirit.Wait 2. Although the syntax in Visual Basic is different. and the last value received over the IR port. you may be left wondering how to retrieve the value of an input or timer. Poll can return many values from the RCX. 2. Instead.PlayTone 784. .SetRwd "02" .EndOfTask Pause 5 .BeginOfTask 1 . 50 . I won't attempt to duplicate that work. Retrieving Input and Timer Values Although the Technical Reference Document makes it clear how to reset timer values and how to configure the RCX's inputs. timer values. 0. . . . The answer is a versatile function called Poll.While 0.PlayTone 659. 50 .Wait 2.BeginOfTask 2 . 0.Wait 2. 0.ocx exposed in NQC.EndWhile . while task 2 runs the outputs in forward and reverse. .On "02" . .ocx commands.StartTask 2 . . .PlayTone 392. 80 .PlayTone 784.EndOfTask . Tips You've already seen a lot of the functionality of Spirit.PlayTone 523.ocx.EndWhile .EndOfTask .165 . variable values. . 80 . the basic functions are the same.CloseComm End With End Sub 0 10 10 10 20 10 20 0 Tasks 1 and 2 both use While and EndWhile to loop forever. 2. If compares two Poll values. For example.166 Poll accepts a Source and a Number that. A call to Poll 0. The Technical Reference Document even includes a set of constant definitions. You can incorporate this file as part of your Visual Basic project. Using Constants As you might have guessed. The key to understanding Poll is the Parameter Table in the Technical Reference Document. 11 would return the value of the twelfth variable. 2. SENSOR_2 Result = . Using If and While The Parameter Table is likewise the key to understanding the If and While functions. 1. This table simply lists out the possible values for Source and Number and how they are interpreted. you might add the following definitions (the lines beginning with a single quotation mark are comments): ' Sources Public Const VARIABLE = 0 Public Const SENSOR_VALUE = 9 ' Sensor names Public Const SENSOR_1 = 0 Public Const SENSOR_2 = 1 Public Const SENSOR_3 = 2 Using these constants.Poll(SENSOR_VALUE. RCXDat. symbolic constants in your Visual Basic code can make Source and Number values a lot easier to read. 1 would return the value of input 2. the above Poll functions could be rewritten like this: With DummySpiritForm. a call to Poll 9. each described by a Source and a Number. You can easily define your own constants in the (Declarations) section of your code module.Poll (VARIABLE. taken together.Spirit1 ' … Result = . but the constant names are not very descriptive (SENVAL and VAR.bas (also available online). for example). In essence. describe the value you want to retrieve. you'll really appreciate knowing what's going on. the If statement tests to see if the value of input 3 is less than the constant value 100: If 9. 11) ' … End With It's a lot more readable with the symbolic constants. If you ever have to look at the code at some later date. For example. In the following example. 100 . for example. LESS. The body of the While (until an EndWhile) is executed until the comparison is false. it compares two values using an operator. What's that 1 in the middle? That's the operator that's used for comparison. the While loop is easy. would be executed as long as the value of input 3 was less than 100: While SENSOR_VALUE. The available operators are shown in Table 8-1. As you might have guessed. Table 8-1.If SENSOR_VALUE. 100 ' Do stuff here. LESS.InitComm ' … . Operators for If and While Number 0 1 2 3 Meaning > < = !=(not equal) A good set of constants makes the If statement a lot easier to read: ' Sources Public Const VARIABLE = 0 Public Const CONSTANT = 2 Public Const SENSOR_VALUE = 9 ' Sensor names Public Const SENSOR_1 = 0 Public Const SENSOR_2 = 1 Public Const SENSOR_3 = 2 ' Operators Public Const GREATER = 0 Public Const LESS = 1 Public Const EQUAL = 2 Public Const NOT_EQUAL = 3 Sub UsingConstants( With DummySpiritForm. .CloseComm End With End Sub Once you've mastered If. the constant value 100 is represented by 2 100. CONSTANT. SENSOR_3. The body of the following loop.EndIf ' … . SENSOR_3. Like If. you can define constants to make these easier to understand. 100 ' Loop body EndWhile . 2. CONSTANT.Spirit1 .167 The value of input 3 is represented by the first 9. It's all pretty straightforward.InitComm battery = . The following example shows how you can retrieve and display the current battery power level: Sub ShowBattery() With DummySpiritForm. a special set of data in the RCX that your programs can use.CloseComm MsgBox (battery) End With End Sub Retrieving the Datalog Back in Chapter 4.InitComm . You can modify this program to suit your needs. this function can be executed either immediately or inside a program. It opens up communications with the RCX. it's a pretty silly program.ocx offers some interesting capabilities that go beyond even NQC.Spirit1 .PBBattery() . but how to you get that data back? Although you can retrieve the datalog using a tool like nqc or RCX Command Center. The following Visual Basic code defines an RCX program that turns itself off: Sub TurnOffProgram() With DummySpiritForm. SaveDatalog. except that the RCX will .BeginOfTask 0 . using PBTurnOff. The main part of the program is a subroutine.SelectPrgm 2 .EndOfTask Pause 1 . The PBBattery function returns the current battery voltage in milliVolts (mV). It's easy to create a datalog and add values to it in NQC. and writes them into a file of comma-separated values.CloseComm End With End Sub By itself. For fresh batteries. One of these is the ability to turn off the RCX.168 Other Nuggets Spirit. you should get a reading of 9000. though: shouldn't your robot turn itself off when it's accomplished its mission. to conserve battery power? You can also use Spirit. In this section I'll show you how to write a program in Visual Basic to extract the datalog from the RCX. it may not be in exactly the format you'd like. extracts the datalog values.PBTurnOff .Spirit1 .ocx to query the RCX for the current battery charge. You can imagine how it might be useful. Interestingly. I described the datalog. of course. because the zeroth item is not a data point. of course. 0. On each line. 368 Sensor value. This example interprets the source of each value. the source. it must be uploaded in pieces. 0. on the contents of the datalog): Variable. The example is comprised of three parts. The third number is the actual value stored in the datalog. You can use your robot to gather data. then converts it to a descriptive string before writing it out to the file. 1) length = data(2. number. 2. The first (zero-th) item of the datalog contains the length of the datalog. which takes a starting index and a length. and value for each datalog item out to a text file. It uses the min function to calculate a minimum and the getTypeString function to convert the datalog item source number to a descriptive string: Sub SaveDatalog(filname As String) Dim data As Variant Dim index. stepSize As Integer Dim line As String With DummySpiritForm. The output file will look something like this (depending.169 only upload fifty datalog values at a time. The relevant Spirit. 7 A plain text file of comma-separated values is usually pretty easy to import into a spreadsheet or statistical analysis program. If you have larger datalog. 33 Watch. and then use some other program to analyze or graph the data. 543 Variable. The first two numbers indicate the source and number of the value. The SaveDatalog subroutine does most of the work. 1. use this example program to upload it to your PC. source and number have exactly the same meaning here as they do for Poll. The data returned from UploadDatalog is an array. 8.Spirit1 . 1. length. Some people have built optical scanners based on RIS using these techniques. Each datalog item is represented by three numbers. SaveDatalog writes the source. It's the first thing SaveDatalog reads: data = . 8 Variable.ocx function is UploadDatalog. and value of the item are separated by commas. 0) -1 The actual data length is one less than the reported length.UploadDatalog(0. number. Each line of the text file represents one item from the datalog. 2 Timer. "Program number". _ code = 12. "Constant". _ code = 4. 1) length = data(2. Close #out End With End Sub Function min(n1 As Integer. index = 0 While (index < length) ' Find the smaller of the remaining items or 50. 50) ' Get the data. "Sensor value". "Random". _ code = 10. "Variable". stepSize) ' Write it out to a file. which describes the length of the datalog." + _ Str (data(1. _ code = 2.UploadDatalog(index + 1.index. i)) + ". "Sensor type". data = . _ .CloseComm ' Close the file. "Sensor raw". _ code = 9. out = FreeFile open filename For Output As #out . i)) + ". _ code = 3. i)) Print #out. _ code = 1.UploadDatalog(0. "Timer". line Next I index = index + stepSize Wend . _ code = 11. _ code = 8. For i = o To stepSize -1 line = getTypeString(data(0. n2 As Integer) As Integer If n1 < n2 Then min = n1 Else min = n2 End If End Function Function getTypeString(ByVal code As Integer) As String getTypeString = Switch( _ code = 0.InitComm ' First get item zero. "Sensor mode". 0) .170 ' Open the output file." +_ Str (data(2.1 ' Now upload 50 items at a time. data = . stepSize = min(length . "Motor status". object-arts.com/sdk/ This official document from LEGO describes Spirit. developed by Andy Bower. which is 112 pages of reference material describing every function in Spirit. LEGO on my mind: Roboworld This tutorial. Although LEGO calls it a Software Development Kit (SDK). of course. which is a Smalltalk implementation for Windows. Links are provide on the Bot-Kit web site for obtaining Dolphin . _ code = 14.svc. how to use VB to talk to the RCX. Online Resources LEGO Programmable Bricks Reference Guide. It's available as a PDF file.ocx from Visual Basic.wit. is really just a jumping-off point.ocx.fcj.ocx in detail. To use Bot-Kit. you will need Dolphin Smalltalk. There are also some Visual Basic files that you can download and experiment with. "Watch". and even includes several sets of instructions for building robots that you then program with VB.legomindstorms. provides a gentle introduction to Visual Basic and programming with Spirit. The second resource is "Mind Control" a programming environment that interprets Visual Basic-like programs and can download them to the RCX.nl/brok/legomind/robo/ This is the robotics area of Eric Brok's excellent site. There are actually two relevant resources here. Lego Robotics Course. Bot-Kit. either in one big chunk or in separate pieces. it's not really a big deal. a popular object-oriented programming language. including a file of handy constant definitions. • Modify the output file format to suit your own needs. _ code = 15. The document describes how to work in the Visual Basic environment. created as a course handbook at the Waterford Institute of Technology in Ireland. The first is an outstanding introduction (the "Spirit programming" link) to using Spirit.com/Bower/Bot-Kit/Bot-Kit.hvu.171 code = 13.htm Bot-Kit. "Sensor boolean". You may want to make the following enhancements: • Integrate SaveDatalog into a form to create a user-friendly application. There's a PDF file of the Technical Reference Document. is glue that allows you to program your RCX using Smalltalk. "IR message" _ ) End Function This example. com/Area51/Nebula/8488/lego.netway.com/botcode.html BrickCommand is a programming environment for MINDSTORMS that is similar to Visual Basic.demon. BotCode RCX Development System but doesn't have as many extras as BrickCommand. it's shareware ($20US).umbra.ocx functions interactively.geocities. Bot-Kit itself is free. Furthermore. this would certainly be a fun way to do it. an interactive motion controller.ocx. .html Gordon's Brick Programmer is yet another alternative to VB.ocx for your programming pleasure. Like BrickCommand and BotCode. LEGO MINDSTORMS: GORDON'S BRICK PROGRAMMER. If you are interested in learning Smalltalk. The documentation is excellent.ocx. which is available for free. The BrainStorm Web Page. it's a programming environment built on top of Spirit. Developed by Richard Maynard. and the ability to call single Spirit.com/~rmaynard/ BrainStorm is a version of the Logo programming language adapted to work with MINDSTORMS robots. Richard wrote BrainStorm using Visual C++ to communicate with Spirit. you can write Smalltalk programs that run on your PC and control the RCX.htm BotCode is another alternative to VB.172 Smalltalk. It includes other goodies like a piano keyboard for playing music on the RCX. The source code is available. although you'll need to join a related mailing list in order to install the software.uk/gbp. whereas BrickCommand is entirely free. or you can write Smalltalk programs and download them to the RCX. BrainStorm is a work in progress and currently stands at version 0. As with VB. IGUANO Entertainment Lego Page [BrickCommand]. It opens up the full power of Spirit. It opens up the power of Spirit.desktopmusic. the robot assumes it bumped into the other robot and shouts "Tag!" It waits for an acknowledgement from the other robot (in the form of another IR message).173 9 RoboTag. Then it starts up again. The two robots are identical. When the light sensor "sees" the edge. it is obliged to send an acknowledgement and then sit still for a short time. If the acknowledgment is received. wandering around to tag the other robot. to build and program the first RoboTag contestants. Each robot has a bumper on its front and a downward pointing light sensor. The tagged robot must sit still for a while. When the bumper is triggered. an important paradigm in robotics programming. Paul Stauffer. The light sensor is used to detect the edge of the playing arena. Each has two motor-driven treads. RoboTag is the creation of Matthew Miller. When one of the robots receives the "Tag!" message from the other robot. The robots drive around in a simple arena. who teamed up with a friend. a Game for Two Robots In this chapter: • Building Instructions • Subsumption Architecture • Online Resources RoboTag is a game for two robots. the edge of the arena is marked by a black line. I'll use RoboTag as a way to explain subsumption architecture. it shouts "Tag!" by sending a message out its IR port. the robot backs up and turns to stay inside the arena. the robot adds one to its current score. In this chapter. When one robot bumps into the other robot. . and then the game continues. 174 Building Instructions . .175 The 16t gears are nestled inside the tread wheels. 176 . 177 Attach the motors to output A and output C as shown. . is attached to input 2. which is mounted on the bumper. The touch sensor goes on input 1.178 The light sensor. . First. It will completely take . subsuming (replacing) lower-level behaviors. Overview Subsumption architecture is a radically different paradigm for robot programming developed by Rodney Brooks at MIT in the late 1980s. This behavior will become active when it detects a bump on the touch sensor. it requires heavy-duty processing power and may not work properly anyway. Then it decides how to act. Based on the sensor data. including the RCX. the robot will use two behaviors. the robot constructs or updates a model of the world. it should back up and turn around. When the robot bumps into something. higher-level behaviors completely take over control of the robot. Imagine a robot that has a bumper (a touch sensor) on its front. This deliberative approach is very complicated. Input from sensors is used to determine which behavior controls the robot at any given time. In this reactive approach. the robot processes its sensor data. To avoid obstacles. Figure 9-1 shows a diagram of this behavior. subsumption architecture is simple enough to be implemented on inexpensive hardware.179 Subsumption Architecture The traditional approach to robot programming has been to emulate human thought processes. several robot behaviors run at the same time. A basic example will clarify the concept. Depending on the sensor values. the robot needs another behavior. With subsumption architecture. avoid. It controls the motors to make the robot move forward. The first behavior is cruise and simply moves the robot forward. As you'll see. trying to control the robot according to their own rules. Cruise. One additional task decides which behavior is in charge and then sends its commands to the motors. If one robot collides with the other robot. a single input might trigger multiple behaviors. Finally. the bumper is pressed. The behaviors all run simultaneously. It's entirely possible that one behavior will be triggered by some combination of inputs. Our implementation of subsumption architecture is written in NQC. The circle with an ''S" indicates that the avoid behavior can take control of the motors from the cruise behavior. The avoid behavior takes control of the robot when the bumper is pressed There won't always be a one-to-one relationship between inputs and behaviors. the reading from the light sensor causes the avoid behavior to assert itself.180 Figure 9-1. This causes the tag behavior to take control of the robot. RoboTag behaviors The robots in RoboTag actually need four different behaviors. The basic idea is that each behavior is a separate task. . shown in Figure 9-3. As you'll recall. the RCX's default firmware supports this feature. Figure 9-2. Implementation It's fairly easy to implement subsumption architecture on a system that includes preemptive multitasking. Figure 9-2 shows a diagram with both the cruise and avoid behaviors. the top level behavior is tagged. This behavior is triggered if the robot has been tagged by the other robot. The basic cruise behavior is the same as before—it moves the robot forward. a simple robot behavior over control of the robot. depending on the input's value. Likewise. If the robot drives over the edge of the playing field. Wait(20). // Coast to a stop. cruise always wants the robot to move forward. while (true) Wait(100). The cruise behavior is simple: int cruiseCommand. if (Message() == MESSAGE_ACKNOWLEDGE) { ∗ The endless loop isn't strictly necessary. I'll show you how this variable is used to determine what actually happens to the robot. tagCommand = COMMAND_FLOAT. Then I'll talk about how a behavior is selected and how the motors are controlled. Later on. . In the next section.∗ Each behavior (task) has an associated command variable that holds the desired motor output. for example. RoboTag behaviors I'll start by examining the NQC code for each behavior. The next behavior is tag. } cruise sets the cruiseCommand variable to the value COMMAND_FORWARD and then loops forever. but it makes cruise look more like the other behaviors.181 Figure 9-3. Like cruise. I'll present the entire source code for RoboTag. // Check to see if we got an acknowledgement. cruise. In this simple case. task tag() { while(true) { if (BUMP_SENSOR == 1) { // Say tag! SendMessage(MESSAGE_TAG). task cruise() { cruiseCommand = COMMAND_FORWARD. tagCommand: int tagCommand. uses the cruiseCommand variable to hold the desired motor output. tag has its own motor output variable. Wait(50). // Turn left or right for a random duration. On(OUT_B). it adds one to its score. } else tagCommand = COMMAND_NONE. When the bumper is pressed. to the other robot. There's a bit of a hack here to keep score. SetPower(OUT_B. the counter runs from only 1 to 7. tag sends out an IR message. The lack of a reply can mean two things: either the other robot did not receive the IR tag message. so the maximum score is 7. hoping to get in range of the other robot's IR port. This movement is accomplished by setting the tagCommand variable. or the robot bumped into an obstacle. tagCommand = COMMAND_REVERSE.182 PlaySound(3). Otherwise. it doesn't do anything. score). so it was safe to assume that the other robot didn't "hear" the tag message. In the original RoboTag by Matthew Miller. not the other robot. . ClearMessage(). The tagging robot would then spin in place shouting "Tag!" repeatedly. if (Random(1) == 0) tagCommand = COMMAND_LEFT. which indicates that tag is not interested in controlling the robot. On(OUT_B). COMMAND_NONE. The initialization code for RoboTag (presented later) tells the RCX to view the output B setting: SelectDisplay(5). Then it waits for a reply by repeatedly calling Message(). The robot also backs up and turns to the left or right to move around the robot it has just tagged. If tag sends out a tag message but doesn't receive a reply. tagCommand = COMMAND_NONE. using SendMessage(). // Back up. it sets tagCommand to a special value. Wait(Random(200)). If tag receives an acknowledgement from the other robot. All tag does is set the power of output B to show the current score on the display: SetPower(OUT_B. if (score < 7) score = score + 1. } else PlaySound(2). if (score < 7) score = score + 1. The power setting of output B is used to contain the robot's current score. } } tag acts only if the bumper is pressed. Of course. score). the arena contained no obstacles. else tagCommand = COMMAND_RIGHT. PlaySound(4). Wait(20). .183 In our design.3) { // Back away from the border. Wait(50). In this implementation. If the robot bounces into something that doesn't respond to the tag message. This opens up the possibility of adding physical obstacles to the arena. a task called arbitrate examines the output command variable of each behavior. much like tag. avoidCommand = COMMAND_FLOAT. and sit still for eight seconds. Wait(Random(200)). else avoidCommand = COMMAND_RIGHT. int taggedCommand. Wait(800). it must be an obstacle. taggedCommand = COMMAND_NONE. play a sad sound. // Turn left or right for a random duration. if (Random(1) == 0) avoidCommand = COMMAND_LEFT. This behavior backs up and turns to move away from the edge. which is triggered when the IR port receives notification that the robot has been tagged. avoidCommand = COMMAND_REVERSE. tag doesn't do anything if a reply is not received. } } } Arbitration As mentioned earlier. task tagged() { while(true) { if (Message() == MESSAGE_TAG) { taggedCommand = COMMAND_STOP. which helps the robot to avoid the edge of the playing arena. The next behavior is avoid. avoidCommand = COMMAND_NONE. it is used to set the current motor command. int avoidCommand. If it is not COMMAND_NONE. ClearMessage(). SendMessage(MESSAGE_ACKNOWLEDGE). It is triggered by the light sensor. This behavior tells the robot to send an IR acknowledgement. } } } The highest-level behavior is tagged. an additional task is needed to link the robot's behaviors to its motors. task avoid() { while(true) { if (LIGHT_SENSOR < averageLight . and the robot will just continue doing whatever it did before. } else if (motorCommand == COMMAND_RIGHT) { OnFwd(OUT_A). } The relationship between arbitrate and motorControl is important. For example. All motorControl() has to do is examine the value of motorCommand and set the motors accordingly. OnFwd(OUT_C). motorControl(). else if (motorCommand == COMMAND_FLOAT) Float(OUT_A + OUT_C). in a different program. Here it is: sub motorControl() { if (motorCommand == COMMAND_FORWARD) OnFwd(OUT_A + OUT_C). } else if (motorCommand == COMMAND_STOP) Off(OUT_A + OUT_C). cruise. if (avoidCommand != COMMAND_NONE) motorCommand = avoidCommand. since cruiseCommand is always COMMAND_FORWARD. This isn't an issue. At first glance. if both the cruise and tagged behaviors are attempting to control the robot. the tagged behavior takes precedence by subsuming the lower-level behavior. if (tagCommand != COMMAND_NONE) motorCommand = tagCommand. In this implementation. task arbitrate() { while(true) { if (cruiseCommand != COMMAND_NONE) motorCommand = cruiseCommand. else if (motorCommand == COMMAND_REVERSE) OnRev(OUT_A + OUT_C).184 int motorCommand. OnRev(OUT_C). Where the rubber meets the road The arbitrate task hands off the actual dirty work of controlling the motors to a subroutine called motorControl(). you might think it makes sense to implement motorControl as a separate . if (taggedCommand != COMMAND_NONE) motorCommand = taggedCommand. else if (motorCommand == COMMAND_LEFT) { OnRev(OUT_A). } } Note that the order is important. then motorCommand will be unchanged. if no behavior asserts control. The commands in the end of the list will overwrite the value of motorCommand and are thus higher-level behaviors. you might want to set motorCommand to a default action at the beginning of the while loop in arbitrate(). However. #define MESSAGE_TAG 33 #define MESSAGE_ACKNOWLEDGE 6 #define BUMP_SENSOR SENSOR_1 #define LIGHT_SENSOR SENSOR_2 int score. task tag() { . if you do this. a Robot with an Arm) to calculate a baseline value for the light sensor. The problem is that arbitrate changes the value of motorCommand several times each time it loops. int averageLight. arbitrate. int cruiseCommand. The RoboTag Program Once you get through the details of implementing subsumption architecture. motorControl is implemented as a subroutine and is called once each time at the end of the arbitrate loop. the robot "jiggles" badly. We're really interested only in the value of motorCommand at the end of each loop in arbitrate. task cruise() { cruiseCommand = COMMAND_FORWARD. } int tagCommand. Therefore. motorControl responds by changing the motors' directions. The RoboTag program uses its main task to start up all the behavior tasks and.185 task. When the light sensor reads lower than the average. the rest of the programming is pretty simple. As the value changes. Minerva. #define COMMAND_NONE -1 #define COMMAND_FORWARD 1 #define COMMAND_REVERSE 2 #define COMMAND_LEFT 3 #define COMMAND_RIGHT 4 #define COMMAND_STOP 5 #define COMMAND_FLOAT 6 // IR messages. // Motor commands. Here is the entire code for RoboTag. the RoboTag robot can assume it's reached the edge of the arena. It also uses the light sensor initialization code from Minerva (see Chapter 5. of course. However. while (true) Wait(100). You should download this program to both of the robots that will be playing. Wait(20).186 while(true) { if (BUMP_SENSOR == 1) { // Say tag! SendMessage(MESSAGE_TAG). // Check to see if we got an acknowledgement. tagCommand = COMMAND_FLOAT. Wait(Random(200)). task avoid() { while(true) { if (LIGHT_SENSOR < averageLight . // Back up. if (Random(1) == 0) tagCommand = COMMAND_LEFT. } else PlaySound(2). tagCommand = COMMAND_NONE. // Turn left or right for a random duration. ClearMessage(). On(OUT_B). SetPower(OUT_B. } } int avoidCommand. Wait(20). if (score < 7) score = score + 1. } else tagCommand = COMMAND_NONE. // Turn left or right for a random duration. tagCommand = COMMAND_REVERSE. // Coast to a stop.3) { // Back away from the border. if (Random(1) == 0) avoidCommand = COMMAND_LEFT. if (Message() == MESSAGE_ACKNOWLEDGE) { PlaySound(3). task tagged() { while(true) { if (Message() == MESSAGE_TAG) { taggedCommand = COMMAND_STOP. else avoidCommand = COMMAND_RIGHT. } } } int taggedCommand. Wait(50). avoidCommand = COMMAND_NONE. Wait(50). avoidCommand = COMMAND_REVERSE. avoidCommand = COMMAND_FLOAT. Wait(Random(200)). . score). else tagCommand = COMMAND_RIGHT. } } sub motorControl() { if (motorCommand == COMMAND_FORWARD) OnFwd(OUT_A + OUT_C). avoidCommand = COMMAND_NONE. } else if (motorCommand == COMMAND_STOP) Off(OUT_A + OUT_C). tagCommand = COMMAND_NONE.187 SendMessage(MESSAGE_ACKNOWLEDGE). tag. if (tagCommand != COMMAND_NONE) motorCommand = tagCommand. taggedCommand = COMMAND_NONE. } task main() { initialize(). tagged. OnFwd(OUT_C). else if (motorCommand == COMMAND_REVERSE) OnRev(OUT_A + OUT_C). Wait(800). start arbitrate. start start start start cruise. cruiseCommand = COMMAND_NONE. task arbitrate() { while(true) { if (cruiseCommand != COMMAND_NONE) motorCommand = cruiseCommand. OnRev(OUT_C). taggedCommand = COMMAND_NONE. ClearMessage(). else if (motorCommand == COMMAND_FLOAT) Float(OUT_A + OUT_C). } } } int motorCommand. if (taggedCommand != COMMAND_NONE) motorCommand = taggedCommand. motorControl(). else if (motorCommand == COMMAND_LEFT) { OnRev(OUT_A). PlaySound(4). } else if (motorCommand == COMMAND_RIGHT) { OnFwd(OUT_A). } . if (avoidCommand != COMMAND_NONE) motorCommand = avoidCommand. avoid. } averageLight = runningTotal / NUMBER_OF_SAMPLES. If you really want to learn more.umich. they're an excellent read. } #define NUMBER_OF_SAMPLES 10 int i. you should look up Brooks' papers.edu/cogarch3/Brooks/Brooks. . int runningTotal. runningTotal = 0. Fwd(OUT_B). calibrateLightSensor().html This page has some background on subsumption architecture.eecs. while (i < NUMBER_OF_SAMPLES) { runningTotal += LIGHT_SENSOR. void calibrateLightSensor() { // Take an average light reading. i = 0. SENSOR_LIGHT). Brooks' Subsumption Architecture. SetSensor(LIGHT_SENSOR. It contains the original source code and a couple of movies of RoboTag in action. score = 0. SelectDisplay(5). however. } Online Resources mattdm's Mindstorms stuff sub initialize() { SetSensor(BUMP_SENSOR. i += 1. created by Matthew Miller.org/mindstorms/ This is the original RoboTag web page. ClearMessage().mattdm. SENSOR_TOUCH). Wait(10). it offers full control of the RCX. smoke-snorting monster truck with a roaring engine and no muffler. here's your chance. legOS • Function Reference • New Brains For Hank • Online Resources legOS is the most powerful development tool available for the RCX. I'll describe the legOS services and present some sample code. you have direct control of the inputs and outputs. With legOS. and memory of the RCX. which is well-documented in other publications. and pbFORTH would probably be an ecoconscious alcohol-burning car with a Grateful Dead bumper sticker. or C++. legOS offers you the ability to program your RCX in assembly language.189 10 legOS In this chapter: • About legOS • Development Tools • Hello.oreilly. legOS would be a fire-breathing. RCX Code would be a plastic tricycle. If you don't already know C. please see. ∗ For updated information on legOS. Unless you're already running Linux and using GNU development tools. of course. Like pbFORTH. There's a lot of power here. NQC would be a comfortable sport/utility vehicle.∗ If programming environments were cars. C. I won't attempt to describe C. you may be more comfortable running legOS than pbFORTH. I'll talk about what software you need to develop legOS programs and what alternatives are available. The flip side. is that legOS is harder to use than any of the other programming environments. you'll have to spend some time configuring your system to support legOS development. you might want to work your way through a tutorial before reading this chapter. . In this chapter. display.com/catalog/Imstorms/ . About legOS legOS is replacement firmware that completely replaces the default RCX firmware that LEGO gives you. If you're already familiar with C. IR port. If you've been wanting to implement a neural network on your RCX. you need to recompile with legOS and download the whole firmware each time. no such facility exists. (There is another possibility. In this case. pbFORTH. To run your program you need to download the whole thing to the RCX. some kind of cross compiler compiles your code with the legOS code to produce a firmware. like nqc or firmdl. This makes for a clumsy development cycle: even though you're only changing your own code.190 legOS is more of a library than an OS. Figure 10-1. you want a cross compiler that runs on your PC and produces firmware for the RCX. someone will probably write a rudimentary set of tools so that you can leave legOS on the RCX and download new user programs to it. you can program it using a terminal emulator. . as described in the sidebar. in some ways. On the PC side. ''An Innovative Alternative. The basic tool you need is a cross compiler. To get your program on the RCX. legOS software architecture Development Tools You'll need some heavy-duty tools to work with legOS. Figure 10-1 shows the architecture of legOS. The programs you write are compiled with the legOS source code to produce a firmware. a tool that runs on one platform but produces executable files for another. For now. though. is an interpreter. you need to use a firmware downloader tool. As time passes. by contrast. after that. running whatever program you have created. the firmware lives in the RAM of the RCX. Once downloaded.") The good news is that the tools are free. You only have to download it once to the RCX. Downloading Firmware Once you have successfully compiled something in legOS. if you can find somebody who's created the cross compiler for your particular platform. If you're a Linux enthusiast trapped in a Microsoft world. You can download someone else's binary version of the egcs cross compiler. you will need to download it to your RCX to run it. the open-source successor to the GNU gcc compiler. (The "Online Resources" section has more information on obtaining Cygwin. A full download is about 13 MB. The "Online Resources" section at the end of this chapter lists web sites that contain instructions for recompiling egcs as well as the locations of popular binaries of the cross compiler. To build legOS. You can recompile egcs itself to make it into a cross compiler. There are two ways to do this: 1. To do this. If you're not running Linux. you'll need to go get Perl. there is a way to make Windows act like Linux. You'll need to have Perl installed on your computer to make legOS programs. As before. Linux users probably have Perl lying around already. Oh. On a Unix-like operating system. you're going to need to configure egcs as a cross compiler for the RCX.191 legOS is built using egcs. Obviously. I'll explain this process soon. and Perl Too Part of compiling legOS involves running some Perl. you can probably build egcs and binutils yourself. you need a small utility that's called a . Like lots of GNU stuff. compressed. the second option is a lot easier. If you've installed Cygwin on your Windows machine. These tools are present on most Linux systems. 98. and NT. 2. See "Online Resources" for more information. don't despair. though. it's a little bulky.) Setting Up egcs To compile legOS. you'll also need GNU's binutils package. or find someone who has binaries for your platform. Cygwin What if you're not running Linux or a Unix-like operating system? If you have Windows instead. but they must be reconfigured to support crosscompilation for the RCX. See the "Online Resources" section later in this chapter for information on obtaining egcs and binutils. you'll definitely want to check this out. The Cygwin package from Cygnus Solutions is a port of many GNU tools to Windows 95. a machine compiles the code and sends you the result. An Innovative Alternative If the complexity of setting up tools for legOS is making you sad. This piece of software uses the IR tower to transfer firmware to your RCX. This completely sidesteps the whole problem of obtaining a cross compiler. Another option is Kekoa Proudfoot's firmdl. you can compile legOS programs.h" int main(void) { cputs("Hello") . using the -firmware option. Across the Internet. legOS Let's begin with something simple. 3. You have to depend on someone else to keep the compiler running. Two kind individuals have set up web-based legOS compilers.com/web-legOS. return 0. described in Chapter 4. The following program displays "Hello" on the RCX's display briefly: #include "conio. You have to fit your program into a single source file. This solution is useful even for platforms that don't support the GNU tools. The web-based cross compilers are here: There are some downsides to this approach. delay(1000) . which you can then download to your RCX. All you do is submit your source code.mersenne. Not Quite C. Two firmware downloaders are readily available. Hello. first compile it.com/~dbm/compile-legOS.192 firmware downloader.dwarfrune. If you have the cross compiler installed locally. 2. there's a creative solution. Dave Baum's nqc. } To run this example. lcd_refresh() . you just need to edit the legOS Makefile so that the TARGET line points to .html. As long as you have a web browser. as well: 1. This will allow you to verify that your tools are working and give you a first taste of programming with legOS. is capable of downloading firmware files to the RCX. You can't apply patches and tweak other things yourself. which is available as a C source file. If you've been reading through this book in order. If everything is installed correctly. press the Run button.common. your RCX will display the string "legOS" to indicate that legOS is running.lugnet. take a deep breath. The TOOLPREFIX and LEGOS_ROOT lines should point to the appropriate directories on your system. When the download is complete. and you're starting to curse at your computer.193 your source code. If you're using one of the online compilers.cyou would edit the Makefile's TARGET like this: TARGET=/projects/HellolegOS Then type make at the command line. at least. If there are no errors. The "Online Resources" section of this chapter has pointers to helpful sites. you can press Run again to see the "Hello'' message again.com/. Likewise.c. legOS has a set of functions that looks a lot like pbFORTH and ∗ Make sure you've edited Makefile. you will then need to download the . The display will show "Hello" for a second or so. they will be awed and inspired.srec file in the same directory as the source file. Trouble with Make If you can't make HellolegOS. Control has now returned to legOS. To actually run the program you just wrote. you'll end up with a HellolegOS. legOS has a strong online community. you will get back an . Make sure you put a trailing slash on the LEGOS_ROOT directory. The left number shows the result returned from our main() function. you've seen them all—to some degree. you've probably noticed that NQC and pbFORTH have similar commands but different syntax. There are at least as many messages about configuring the legOS development tools as there are about actually programming in legOS. if you saved the source code above in a file called /projects/HellolegOS. using either nqc or firmdl.just copy the source into the web page and press the compile button. Show your friends and family. When the RCX is on. as described in the comments. Function Reference Once you've seen one RCX development environment.. One of the best things you can do is look at LUGNET. and search through the discussion group archives for the particular problem you're having. . Regardless of how the source file is compiled.∗ For example. you can use the OnOff button to switch the RCX off and on.srec file representing your compiled legOS program.srec file to the RCX. then show two zeros. people will help if you ask. as we did in the HellolegOS. debug it. you can read it. e_1. meaning the functions you can call without knowing much about what's inside legOS.h) Most of the useful display functions are defined in rom/lcd.c example. you can ask legOS to approximate a text string using the display. lcd_unsigned(u) This macro displays an unsigned value. the full source code of legOS is freely available.h includes definitions for four macros that simplify the process of displaying numbers: lcd_int(i) Use this macro to display a signed integer. ∗ The source code is subject to the Mozilla Public License (MPL). e_2 or e_3. but the syntax and usage is slightly different. which is fully described at the following URL:. 123 is shown 0123. To display a number. unsign or digit. you won't need to call lcd_number () directly. Numbers and symbols (rom/lcd. After you call any other display function. i. different levels at which you can use legOS. .h. In this section.org/MPL/ . The first function you should learn is lcd_refresh(): void lcd_refresh(void) This is the function that makes it all happen. or reprogram it as much as you'd like. Signed and unsigned numbers are shown in the main display area. I'll describe the "user-level" functions. Leading digits are padded with zero if necessary—for example. lcd_comma_style c) Use this function to show a number.mozilla. rom/lcd. I'll describe the important functions of legOS and demonstrate how they are used. you must call lcd_refresh(): to actually update the display.194 NQC. Aside from just displaying numbers. on the display. The comma style is digit_comma (for use with the digit number style). In many cases. There are. use lcd_number(): void lcd_number(int i. lcd_number_style n. If you're looking for even more power. The number style is one of sign. of course. indicating the number of digits to the right of the decimal point. e0. Values over 9999 are shown as 9999. while digitshows a single digit on the right side of the display.∗ Using the Display legOS is surprisingly capable when it comes to managing the display on the RCX. you would do this: lcd_show(battery_x). download status. The lcd_segment enumeration is defined inrom/lcd. To show the low battery indicator. to clean up when you're done playing. (You still have to call lcd_refresh() afterwards. and others. Each display segment can be controlled individually: void lcd_show(lcd_segment segment) Show a single display segment with this function. Valid positions are 0 through 4. as well— indicators for the outputs.195 lcd_clock(t) This macro simulates showing a digital clock on the display. void cputw(unsigned word) This function displays the supplied value as four hexadecimal digits. . for example. void lcd_hide(lcd_segment segment) This function hides a specific display segment. void cputc(char c. the comments in that file describe each segment type.h) The conio. Keep this in mind as it may modify your display unexpectedly.h file defines several functions that are handy for displaying text on the RCX: void cputs(char ∗s) This function displays the supplied string. where 0 is the right-most position (the single digit at the right of the display) and 4 is the left-most position. use lcd_clear(): void lcd_clear(void) This function clears the entire display.) As your program is running. The supplied number is shown as a time. The RCX's display contains many symbols. datalog. kind of (conio. int pos) Use this method to display a character at the given position. as nearly as possible. lcd_digit(d) Use this macro to display a single digit on the right side of the display. battery level. Letters like "w" and "m" don't come out very well. Finally. lcd_refresh(). inputs. legOS will try to animate the running man. with the decimal point between the first two and last two digits. Text. but overall this is a great function for debugging. Only the first five characters of the string are shown.h. and off. don't get confused here: off in legOS is the same as Float() in NQC. brake. The rule of thumb for testing touch sensors is to test if the value falls below 0xF000. void motor_a_dir(MotorDirection dir) void motor_b_dir(MotorDirection dir) void motor_c_dir(MotorDirection dir) These functions set the direction of the RCX's outputs.h) Controlling the outputs with legOS is very easy. Don't expect sensors to use the full range of raw input values. but the actual values are not as extreme. the speed only really matters when the output direction is fwd or rev. Values range from 0 to 255. All you need to do is give the output a direction and a speed. Working with Inputs (direct-sensor. motor_c_speed(MAX_SPEED). do this: motor_a_dir(fwd). motor_c_dir(fwd). you have to deal with the raw input values. like this: ∗ If you're accustomed to working with NQC. . You can use the handy constants MIN_SPEED and MAX_SPEED if you wish. support for inputs is rudimentary. The raw values are in the range from 0x0000 to 0xffff. while brake in legOS is the same as Off() in NQC. except for light and rotation sensors. To set outputs A and C running forward at top speed. motor_a_speed(MAX_SPEED).196 Controlling Outputs (direct-motor. The dir value can be fwd.h) In legOS.∗ void motor_a_speed(unsigned char speed) void motor_b_speed(unsigned char speed) void motor_c_speed(unsigned char speed) These functions set the speed for the outputs. The following macros return the raw value of the inputs: SENSOR_1 SENSOR_2 SENSOR_3 BATTERY Use these macros to retrieve the raw value of the corresponding input. Remember all that nice input value processing in NQC and pbFORTH? In legOS. You might think a touch sensor would produce a value of 0x0000 when it's pressed and 0xffff when it's not pressed. rev. BATTERY returns an indication of the battery level. The off mode is the same as Float() in NQC. Of course. then. legOS also supports rotation sensors with the following functions: void ds_rotation_on(unsigned∗ const sensor) void ds_rotation_off(unsigned∗ const sensor) These functions turn on or off rotation counting for the specified input. To actually read the rotation value. The light and rotation sensors are active sensors. you would just use the ROTATION_3 macro. Once you get the input set up for rotation. Processed light sensor values can be retrieved with the following macros: LIGHT_1 LIGHT_2 LIGHT_3 These macros process raw input values to produce a light sensor reading in the range from 0 to approximately LIGHT_MAX. Setting up input 3 for a rotation sensor. you would do this: ds_active(&SENSOR_2). void ds_rotation_set(unsigned∗ const sensor. int pos) This function sets the current rotation count of the given input. you can set inputs to be active or passive: void ds_active(unsigned∗ const sensor) void ds_passive(unsigned∗ const sensor) Use these functions to set the specified sensor to active or passive mode. you can retrieve the rotation value with one of the following macros: ROTATION_1 ROTATION_2 ROTATION_3 These macros return the rotation count for each of the inputs. to set input 2 to be active. For example. the touch and temperature sensors are passive. ds_rotation_on(&SENSOR_3). . The argument to these functions is the address of one of the sensor values. legOS does offer some help. } If you're working with light or rotation sensors. looks something like this: ds_active(&SENSOR_3).197 if (SENSOR_1 < 0xf000) { // Touch sensor is pressed. First. 0). ds_rotation_set(&SENSOR_3. h) legOS provides one function and some other handy definitions to describe the state of the front panel buttons: int button_state(void) This function returns a value that indicates the state of the RCX's four buttons. it makes sense to store the result of button_state(). . if (PRESSED (state. BUTTON_PROGRAM) ) { // Program button is pressed. and BUTTON_PROGRAM. } To test the state of more than one button. pass the result of button_state() as the state parameter and the name of a button for button. BUTTON_RUN. To use these macros. Buttons names are BUTTON_ONOFF. } if (PRESSED(state.198 The rotation sensor code does not work in the March 30.7 Using the Buttons (direct-button. button) RELEASED(state. For example.1. button) These macros return a boolean value indicating if the specified button was pressed or not. just use the dir_write() function: size_t dir_write(void∗ const buf. Use the following macros to interpret the returned value. BUTTON_VIEW)) { // View button is pressed. } The Infrared Port (direct-ir. size_t len) This function writes len bytes of data from the supplied buffer out the IR port. 1999 build of legOS 0. It returns the number of bytes written or -1 if there is an error. BUTTON_VIEW)) { // View button is pressed. BUTTON_VIEW. the following code tests the state of the View button: if (PRESSED(button_state(). PRESSED(state. state = button_state(). like this: int state.h) To send data out the IR port. You can stop a task. 1999 build of legOS 0. It returns the number of bytes read or -1 if there is an error. The new task has the given priority and stack size. as you'll see later. size_t stack_size) This function starts the task described by code_start. Lower priorities take precedence over higher priorities. first call dir_fflush(). This program listens for incoming IR data and shows it on the RCX's display. which means incoming data is placed in a buffer. Remember. or many automatic variables. void dir_fflush(void) The IR input is buffered. it is made available to dir_read(). . int argc. This function returns a process identification number (PID). all sorts of weird behavior results. When it fills up.1.h) Multiple tasks are supported in legOS through a reduced version of the standard Unix libraries. If the stack size you pass to execi() is too small. this is one of the first things you should check.199 The dir_write() function does not work in the March 30. a function's return addresses and automatic variables (declared in the scope of the function) are stored on the stack.c. char ∗∗argv. char∗∗).h and sys/tm. Don't worry about the nasty-looking syntax above. you can pass 0 for the priority and DEFAULT_STACK_SIZE as the stack size.priority_tpriority. If your program crashes. In general. size_t len) This method reads len bytes of data into the supplied buffer. If you have many levels of function calls. To force the contents of the input buffer to be available to dir_read(). or large arrays as automatic variables. Then the task manager itself must be started with a call to tm_start(). One of the legOS demos is tm-and-ir. You can type into a terminal emulator on your PC and see the data show up on the display.7 . you may overrun your stack. The basic idea is to set up some number of tasks using the execi() function. You can pass information to the task using the argc and argv parameters. Two functions are provided for reading data from the IR port: size_t dir_read(void∗ buf. all you have to do is pass the name of a function. using this number. Multitasking in legOS (unistd. pid_t execi(int (∗code_start)(int. } int stop_task(int argc. 0. 0. When it is pressed. . char ∗∗argv) { msleep(200). 0.h" "unistd. new tasks can be started (with execi()). DEFAULT_STACK_SIZE). cputs("nurse"). int display_task(int argc. lcd_refresh().h" pid-t pid. the first task is stopped. The first task shows "Hello" and "nurse" on the display. Here is a simple example that uses two tasks. char ∗∗argv) { while(1) { cputs("Hello"). the second task ends. Once the task manager is running. DEFAULT_STACK_SIZE).h" "sys/tm. } return 0. lcd_refresh(). execi(&stop_task.200 void tm_start(void) Use this function to start up the task manager. } int main() { pid = execi(&display_task. 0. and running tasks can be stopped with this function: void kill(pid_t pid) Use this function to stop the task represented by pid. kill(pid). NULL. while (!PRESSED (button_state(). return 0.h" "direct-button. #include #include #include #include "conio. sleep(1). You can suspend tasks for a given amount of time with the following two functions: unsigned int sleep(unsigned int sec) This function suspends execution for the given number of seconds. BUTTON_RUN)). and control returns to legOS. unsigned int msleep(unsigned int msec) This function suspends execution for the given number of milliseconds (ms). sleep(1). The second task just waits for the Run button to be pressed. NULL. When the button is pressed. int display_task(int argc. until it returns a non-zero result. . sleep(1). wait_event() will return.h" "sys/tm.h" "direct-button. The stop_task() waits for the Run button to be pressed. What's that call to msleep() at the beginning of stop_task()? When legOS first boots on the RCX. char ∗∗argv) { while(1) { cputs("Hello").h" "unistd. it's waiting for the Run button to be pressed. The following is a rewrite of the previous example that uses wait_event() instead of a while loop: #include #include #include #include "conio. } Let's start at the bottom and work our way up. It alternates between displaying "Hello" and "nurse" on the display. which actually handles running the tasks. The process ID of the display task is saved away in the pid variable so that it can be stopped later. with data as a parameter. stop_task() calls kill() to stop the display process. The call to msleep() simply delays a little while to give you a chance to release the Run button. cputs("nurse").201 tm_start(). It helps to look at some of the examples that come with legOS. return 0. The display_task() is straightforward. but it's certainly not obvious. The last thing main() does is call tm_start() to start the task manager.h) For a cleaner way to wait for specific events. The main() method uses execi() to start the two tasks: display_task() and stop_task(). lcd_refresh(). At this point. It's very possible that stop_task() will already be running before you have a chance to take your finger off the Run button. lcd_refresh(). The function pointed at by wakeup is called. your program is started. wakeup_t data) Use this function to wait for a specific event. As soon as it is.h" pid_t pid. looping forever until it is killed by stop_task(). Waiting (unistd. consider wait_event(): wakeup_t wait_event(wakeup_t (∗wakeup)(wakeup_t). It's not hard to use wait_event(). wait_event(&button_press_wakeup. kill(pid). DEFAULT_STACK_SIZE). return 0. does the dirty work of checking the state of the button. takes up about 5K or 6K of the RCX's 32K of RAM. NULL. each size bytes long. } wakeup_t button_press_wakeup(wakeup_t data) { return PRESSED(button_state(). you should free it using this function. NULL is returned. tm_start(). Like malloc(). 0. A pointer to the memory is returned. DEFAULT_STACK_SIZE). size_t size) This function allocates enough memory for nmemb chunks of memory. it returns NULL if something goes wrong. You should have about 26K left for your program and its data. LegOS. 0.202 sleep(1). 0. return 0. char ∗∗argv) { msleep(200). If the memory cannot be allocated. } int stop_task(int argc. . It also sets each byte of the allocated memory to zero. NULL.h) You can request chunks of memory in the RCX using the familiar malloc() and calloc() functions. } int main() { pid = execi(&display_task.data). void ∗malloc(size_t size) This function allocates a chunk of memory of the given size (in bytes). BUTTON_RUN). The given function. button_press_wakeup(). void ∗calloc(size_t nmemb. void free(void ∗ptr) When you are done with memory you've allocated. Memory (stdlib. } return 0. 0. } All that happened in this code was that the while loop from the previous example was replaced with a call to wait_event. execi(&stop_task. by itself. void srandom(unsigned int seed) Use this function to provide a new seed for the pseudorandom number generator.h and direct-sound.h) You can play one of the RCX's built-in ''system" sounds with the following function: void sound_system(unsigned nr) This function plays one of the system sounds of the RCX. 8 kHz data. unsigned length) This function plays the sound data described by sample.h legOS supports a simple random number generator with the following two functions: long int random(void) This function returns a pseudorandom number. using length bytes of data. neither sound_system() nor ds_play() works in the March 30. you can play any sound you want using this function: void ds_play(unsigned char ∗sample. Table 10-1. In this section. 1999 build of legOS 0. sound_system() Sound Numbers Sound Number 0 1 2 3 4 5 Description Short beep Two medium beeps Descending arpeggio Ascending arpeggio Long low note Quick ascending arpeggio (same as 3 but faster) Furthermore. . Unfortunately. The sample data should be 1 bit. it can be any of the values shown in Table 10-1.7 .1. Other Goodies legOS has a grab-bag of other interesting features. The nr parameter describes the sound.203 Sound (rom/sound. In stdlib. these functions are organized by the header file in which they are defined. h Your programs have tremendous power in legOS. This is really only useful if you want to load some new firmware on the RCX. void rom_reset(void) This functions resets the RCX to its out-of-the-box state. although the syntax is somewhat different. this behavior attempts to turn Hank back toward the light. length. the count resets once every 49. constantly tries to move forward. a Game for Two Robots. while the bumpers allow him to avoid obstacles. the robot from Chapter 2. and compare functions. the Bumper Tank. RoboTag. In time. as in the RoboTag program. Hank's light-seeking proclivity is produced by the interaction of three behaviors: • cruise.h You can retrieve the number of milliseconds since the RCX was powered up using the sys_time variable.h There are also functions for working with text strings: char∗ strcpy(char ∗dest. const char ∗src) int strlen(const char ∗s) int strcmp(const char ∗s1. Use with care! New Brains for Hank In this section I'll present a longer example program. generally speaking.204 In string. newly fitted with the light sensor. using these functions: void power_off(void) This function puts the RCX into its low power consumption "off" mode. All you need to do is mount the light sensor on the front of Hank and attach it to input 2. Hank. Hank's new legOS program will be implemented using subsumption architecture. essentially blowing away legOS and your program. This light sensor will allow Hank to search for light. You can turn the RCX off or even obliterate legOS and your program from memory. Figure 10-2 shows a picture of Hank. The basic structure of the program is similar to the subsumption architecture example presented in Chapter 9. If the values are decreasing.7 days. const char ∗s2) These are the standard string copy. In rom/system. • seek_enlightenment() examines the values of the light sensor. It's a program for a slightly modified version of Hank. . It's got a limited range. int task_index. Hank. here's the entire program. It's a neat feature of subsumption architecture that you can concentrate solely on light-seeking behavior in seek_enlightenment(). Convincing Hank to seek light is surprisingly hard.205 Figure 10-2. implement your own algorithm in seek_enlightenment(). LightSeeker. of course. It is triggered by the bumpers and does the standard back-up-and-turn. You can. retrofitted with a light sensor • avoid() is the highest-level behavior.h" "direct-button.h" #define MAX_TASKS 32 pid_t pid[MAX_TASKS]. #define BACK_TIME 500 #define TURN_TIME 800 // Motor commands.c: #include #include #include #include #include #include "conio.h" "unistd. #define COMMAND_NONE -1 #define COMMAND_FORWARD 1 . The obstacle avoidance behavior is already programmed in a different behavior and will subsume the light-seeking behavior as necessary.h" "direct-sensor.h" "direct-motor. Without further ado.h" "sys/tm. while(1) { if (SENSOR_1 <0xf000) { avoid_command = COMMAND_REVERSE. unsigned long milliseconds) { int current. } if (SENSOR_3 < 0xf000) { avoid_command = COMMAND_REVERSE. char ∗∗argv) { avoid_command = COMMAND_NONE. // Timed out. int avoid(int argc. avoid_command = COMMAND_NONE. } . } while (sys_time < (saved_time + milliseconds) && current < (baseline + FUDGE)). #define FUDGE 5 int wait_for_better(int baseline. msleep(BACK_TIME) avoid_command = COMMAND_LEFT.(int)percent. } int seek_command. } #define RAW_DARK 0x7c00 #define RAW_LIGHT 0x6000 int process_light(int raw) { long big = 100 ∗ (long)raw . do { msleep(50). } } return 0. current = process_light(SENSOR_2). lcd_refresh().RAW_LIGHT). msleep(BACK_TIME).RAW_LIGHT).206 #define #define #define #define COMMAND_REVERSE 2 COMMAND_LEFT 3 COMMAND_RIGHT 4 COMMAND_STOP 5 int avoid_command. int saved_time = sys_time. lcd_int(current ∗ 100 + baseline). return -1. avoid_command = COMMAND_RIGHT. long percent = big / (RAW_DARK . msleep(TURN_TIME). avoid_command = COMMAND_NONE. if (current >= (baseline + FUDGE)) return current. return 100 . msleep(TURN_TIME). } return 0. if (sys_time % 2 == 0) seek_command = COMMAND_LEFT. if (result == -1) { // If that timed out. loop_count = 0. result = wait_for_better(baseline. loop_count. baseline = current.FUDGE)) { // Set the baseline from the current value. lcd_int(current ∗ 100 + baseline). return 0. lcd_refresh(). char ∗∗argv) { cruise_command = COMMAND_FORWARD. } current = process_light(SENSOR_2). else seek_command = COMMAND_RIGHT. } int cruise_command. result = wait_for_better(baseline. // Every so often. else baseline = result. if (seek_command == COMMAND_LEFT) seek_command = COMMAND_RIGHT. if (result != -1) baseline = result. 1000). } . // Slow things down a little. increase the baseline. baseline = process_light(SENSOR_2). 2000). else if (seek_command == COMMAND_RIGHT) seek_command = COMMAND_LEFT. seek_command = COMMAND_NONE. } // Relinquish control. while(1) { msleep(50). current. while (1) sleep(1). // If there's nothing better.207 int seek_enlightenment(int argc. bail. loop_count = 0. // Get a baseline. // Search for something better. search back the other direction. char ∗∗argv) { int baseline. // If the current value is somewhat less than the baseline… if (current < (baseline . } // Set the new baseline. seek_command = COMMAND_NONE. result. int cruise(int argc. if (++loop_count == 5) { if (baseline < 100) baseline++. case COMMAND_STOP: motor_a_dir(brake). case COMMAND_REVERSE: motor_a_dir(rev). else if (seek_command != COMMAND_NONE) cputc('s'. while (!PRESSED(button_state(). 0). i < task_index. case COMMAND_LEFT: motor_a_dir(rev). motor_c_dir(fwd). motor_c_dir(fwd). break. break. motor_c_dir(rev). default: break. else cputc(' '. if (cruise_command != COMMAND_NONE) motor_command = cruise_command. else if (cruise_command != COMMAND_NONE) cputc('c'. break. i++) . msleep(200). 0). case COMMAND_RIGHT: motor_a_dir(fwd). motor_control(). char ∗∗argv) { while(1) { if (avoid_command != COMMAND_NONE) cputc('a'. char ∗∗argv) { int i. for (i = 0. switch (motor_command) { case COMMAND_FORWARD: motor_a_dir(fwd). } } int stop_task(int argc. } } int arbitrate(int argc. lcd_refresh(). break. if (seek_command != COMMAND_NONE) motor_command = seek_command. break. BUTTON_RUN)). 0). motor_c_dir(brake). void motor_control() { motor_a_speed(MAX_SPEED). motor_c_dir(rev). motor_c_speed(MAX_SPEED).208 int motor_command. if (avoid_command != COMMAND_NONE) motor_command = avoid_command. 0). return 0. and an "a" shows that the avoid() behavior is controlling the robot. avoid(). 0. To make it clearer what's going on while the robot is running. return 0. NULL. is used to start the three behavior tasks. 0. Back in main(). exec_helper(&seek_enlightenment). will overwrite the motor command. } LightSeeker. When the Run button is pressed. exec_helper(). exec_helper(&cruise). } void exec_helper(int (∗code_start) (int. If the command is not COMMAND_NONE. Seek_enlightenment() and cruise() have nothing to say about it. exec_helper() is also used to start the arbitrate() task. and cruise(). A "c" on the right side of the display indicates that cruise() has control. stop_task() is also started. seek_enlightenment (). DEFAULT_STACK_SIZE). is at the highest level. exec_helper(&arbitrate). arbitrate() writes a character to the display that indicates which behavior is currently active. but it consists of easily understandable pieces. If it chooses to control the robot. The main() function simply serves to start the other tasks in the program. The last behavior. stop_task() simply goes through the process ID array that exec_helper() built and kills each process. the current motor command is set from the behavior. } int main() { task_index = 0. . As before. which examines the output of the three behaviors and sends the appropriate command to the motors. of course. The exec_helper() function simply starts each task using execi() and stores the returned process ID in an array. 0.char∗∗)) { pid[task_index++] = execi(code_start. tm_start(). arbitrate() examines the output commands of each behavior. DEFAULT_STACK_SIZE). NULL. I'll start at the bottom and work backwards through the source code. exec_helper(&avoid).c is a relatively large program. The later behaviors. A helper function. an "s" stands for seek_enlightenment(). 0. execi(&stop_task.209 kill(pid[i]). avoid(). 210 When arbitrate() has determined the motor command, it uses motor_control() to interpret the command and to actually set the direction and speed of the outputs. This design is very similar to the design of the NQC RoboTag program, from Chapter 9. The cruise() behavior is simple; it just sets its command variable to COMMAND_FORWARD ad infinitum. The next behavior, seek_enlightenment(), is not so simple. The basic idea, however, goes like this: if I'm seeing darker stuff than I've just been seeing look to either side for something brighter seek_enlightenment() implements this with the idea of a baseline. The initial baseline is taken straight from the light sensor reading: baseline = process_light(SENSOR_2); The behavior then enters an endless loop, examining the value of the light sensor. If it falls too far below the baseline, seek_enlightenment() asserts control and searches for brighter light: current = process_light(SENSOR_2); if (current < (baseline - FUDGE)) { To search for brighter light, seek_enlightenment() first sets a new baseline from the current light value: baseline = current; Then the robot turns left or right, more or less randomly using the system clock: if (sys_time % 2 == 0) seek_command = COMMAND_LEFT; else seek_command = COMMAND_RIGHT; A helper function, wait_for_better(), is used to wait for a brighter light than the new baseline: result = wait_for_better(baseline, 1000); It's entirely possible that the robot will not find any brighter light. In this case, it times out (after 1000 milliseconds) and returns -1. In this case, the robot will turn back in the opposite direction and search for brighter light: if (result == -1) { if (seek_command == COMMAND_LEFT) seek_command = COMMAND_RIGHT; else if (seek_command == COMMAND_RIGHT) seek_command = COMMAND_LEFT; The wait_for_better() helper function is again used with a longer timeout: result = wait_for_better(baseline, 2000); 211 In either search, if a better value is found, it is used as the new baseline: if (result != -1) baseline = result; } else baseline = result; } That's the basic algorithm. There is one extra feature that makes everything run a little smoother: every so often the baseline value is incremented. This means that if the robot is stuck in a dark corner, it will eventually get dissatisfied (because of the increasing baseline) and look for something better. To communicate with the outside world about what's going on, seek_enlightenment() shows the current light value as well as the current baseline on the display. The current value is shown in the first and second digits of the display, while the baseline is shown in the third and fourth digits. (Remember that the letter on the right side of the display tells you which behavior is currently active.) You can actually see the baseline increasing slowly as the program runs. I've implemented my own light sensor processing in process_light(). I didn't use legOS's LIGHT_2 macro because the values I was getting from it were not in the range from 0 to 100. Perhaps this is a bug that will be fixed in an upcoming release. At any rate, I implemented my own sensor data processing to produce a value from 0 to 100. You may need to adjust the RAW_DARK and RAW_LIGHT constants for your particular light sensor. The avoid() behavior is very simple. It just checks the touch sensors on inputs 1 and 3. If one of the touch sensors is pressed, avoid() backs the robot up and turns it a little. Development Tips legOS has serious programming power, but it has its rough spots, too. This section contains some helpful advice based on my own experience developing with legOS. Development Cycle legOS's development cycle is a little clumsy. You write a program, compile it with the legOS source code, then download the whole thing to the RCX. It's the downloading that takes a long time. Here are some tips to make things go smoother: 1. Always include code that terminates your own program. If your program can stop itself, control returns to legOS. When legOS has control, you can turn the RCX on and off and even reinitialize the firmware, as described next. 212 2. When legOS has control of the RCX, you can press and hold the Prgm button, then press the On-Off button. This blows away legOS (and your program) and returns control of the RCX to the ROM. You'll need to do this before you can download a new set of firmware to the RCX. 3. If your program doesn't stop itself and give control back to legOS, you'll need to erase the firmware by removing a battery. If your program has a bug and does not terminate, you'll need to remove a battery to reset the RCX. 4. Sometimes, through a bug in legOS or in your program, the RCX cannot be initialized by removing the batteries for just a few seconds. You will need to remove the batteries from your RCX and wait for a minute or so before the firmware is erased. Some circuitry keeps the RCX's memory alive; in some cases, you need to wait for the circuitry to drain completely before the firmware will be erased. If the endless code-compile-download-reset cycle is getting you down, you might consider using an emulator. An emulator is a special program that runs on your development PC but acts like an RCX. You can test your programs on the emulator much faster than you can test them on an actual RCX. Currently one legOS emulator exists; see the "Online Resources" section for details. Debugging The display is your best friend when it comes to debugging. legOS offers an impressive array of display functions. You can show words that indicate which part of your program is executing or display the contents of variables. Of course, there's not a lot of space to work with, but you could easily display a series of values for a short time. You could even write debugging code that lets you cycle through data by pressing a button. Unexpectedly Static Variables One of the craziest things about legOS development is that global variables retain their value from one time you run your program to the next. This is very important—it means that variables you initialize at declaration time are initialized only once, when your program is first loaded on the RCX. Use the following program to convince yourself: #include "conio.h" int x = 44; int main(void) { lcd_int(x); lcd_refresh(); 213 x++; delay(1000); return 0; } The value shown on the display will be 44 the first time the program is run, but it goes up by one each subsequent time, even when you turn the RCX off and on again. This interesting property was the source of several bugs in the original LightSeeker.c program. If you really want to initialize a variable each time your program is run, you should do it explicitly in the code somewhere, like this: #include "conio.h" int x; int main(void) { x = 44; lcd_int(x); lcd_refresh(); x++; delay(1000); return 0; } If you look back at LightSeeker.c, you'll see that all the variable initialization is done explicitly. In general, it should ring a warning bell in your head when you see variables that are initialized at declaration time. Online Resources legOS legOS This is the official home page of legOS, written by Markus Noga. You can download files, browse the documentation, see installation instructions, and browse related web pages. LegOS HOWTO Luis Villa has created a comprehensive set of information about legOS at this site. It covers the tools you'll need, where to get them, and how to install them. It also talks about programming in legOS and includes useful links to the online MINDSTORMS community. 214 Another Low-level Tool RCX Tools This page contains a link to librcx, a C library for interacting with the RCX's ROM routines. It was developed by Kekoa Proudfoot, who did most of the original reverse engineering work on the RCX. Development Tools egcs project home page This is the home page for egcs, the compiler you'll need for legOS. The full package is 11 MB (compressed!). Binutils—GNU Project—Free Software Foundation (FSF) This is the home page for binutils, which you'll also need to compile legOS. Compressed, it's about 5 MB; uncompressed, it's around 25 MB. Cygwin If you want to make Windows look like Linux, try the Cygwin package from Cygnus Solutions. Like egcs and binutils, it's free. Perl.com—Acquiring Perl Software This is the place to visit if you need Perl for your system. It has links to versions of Perl for most platforms. emulegOS Originally developed by Mario Ferrari, this legOS emulator has been enhanced by Mark Falco and Marco Beri. It comes in two versions. The Windows version requires Borland's C++ Builder 3.0. The Linux version uses Tcl/Tk. Like legOS, this is not for the faint of heart, but it looks like it could be very useful. Installation Help for Windows Users Lego Knees Gavin Smyth wrote this helpful page about installing the legOS development tools under Windows 95, 98, or NT. It includes links to various files you'll need. The resulting.html This page. unofficial Lego RCX firmware. compiles your source code.215 Installing legOS—the unauth. It includes useful links to the relevant software.com/web-legOS. Written by Kekoa Proudfoot.com/~dhm/compile-legOS. maintained by Shawn Menninga.html This is Dave Madden's web-based legOS compiler.srec file can be displayed as HTML or emailed to you. NQC—Not Quite C This is the home page for NQC.c One popular firmware downloader is firmdl.com/~dbaum/lego/nqc/index.edu/~kekoa/rcx/firmdl.dwarfrune.enteract.1. the source code is available in C and should compile on most platforms.mersenne.com/lego/legOS. It's listed here because nqc can be used to download legOS programs. . Web-Based Cross Compilers Web-LegOS 0.stormyprods.stanford. created by Brain Stormont.c. Firmware Downloaders firmdl.html This page. also details the steps you'll need to follow to install a legOS development environment under Windows 95. Compile legOS RCX code. they are expensive—$10US for the touch sensor. This chapter describes different ways of fitting sensors into LEGO bricks.216 11 Make Your Own Sensors In this chapter: • Mounting • Passive Sensors • Powered Sensors • Touch Multiplexer • Other Neat Ideas • What About Actuators? • Online Resources If you're not afraid of a soldering iron. The sensor needs to connect electrically to the RCX. The sensors that come with RIS exhibit this property: the touch sensors and the light sensor are simply specialized bricks. Mounting The first thing you should think about is how you are going to attach your new sensors to the LEGO world. should be a LEGO brick itself so you can easily attach it to your robots. Somehow the electrical connections from the sensor circuit will need to mate with the RCX's input connections. ideally. Building your own sensors is a great way to expand your robot's capabilities without spending a lot of money. Finding Parts and Programming Environments). There are four basic approaches—cut wire. provides discussions of various types of sensors you can build. and a conductor plate—which are described in the following sections. and $25US for the temperature sensor. you can create your own robot sensors. and considers some innovative possibilities for putting multiple sensors on one RCX input. machine screws. There are two goals to consider here: 1. copper tubing. . there's not a very wide selection. $20US for a light sensor. The sensor. 2. Although you can buy the ''official" sensors from the LEGO online store or LEGO DACTA (see the Appendix A. Furthermore. $15US for the rotation sensor. You can use 3/16" copper tubing. The sensor or sensor circuit can be soldered to the part of the tubing that's inside the brick. Copper Tubing The studs (or "bumps") on LEGO bricks are exactly 3/16 inch in diameter. this ensures that an electrical connection is made no matter which way the sensor is attached to the RCX. the tubing acts as an electrically conductive LEGO stud. Machine Screws Using machine screws is a variation on the copper tubing method. Michael Gasperi's excellent web site describes this technique clearly. you replace them with 4/40 machine screws. you can order additional wires from Pitsco LEGO DACTA (800-362-4308). If you don't want to ruin your perfect set. which . you can build a sensor into a brick and use the regular "wire bricks" that come with RIS to attach the sensor to the RCX. You should place the tubing in diagonally opposite studs. Each wire brick therefore yields two connectors that you can use to make your sensors compatible with the RCX. Figure 11-1. Figure 11-1 shows half of one of these wire bricks. Using the tubing. In essence. A wire brick yields two connectors like the one shown here You can wire the cut end directly to your sensor. although you'll pay dearly for them. see the "Online Resources" section at the end of this chapter. to replace studs in a regular LEGO brick. The n you push the tubing through the holes up as far as a regular stud. Instead of replacing studs with tubing.217 Cut Wire The simplest approach to attaching a new sensor is to cut one of the wire bricks that comes with RIS. available at hobby stores. For details. The basic procedure is to drill out two of the studs in a regular brick. These plates are available as an accessory pack. A hobby tool like a Dremel™ rotary tool or Black and Decker Wizard™ works well for this purpose if you have cutting disks for it. It takes a lot of heat to solder on to the screws. With round head machine screws. Now you're ready to mount your sensor in the brick and solder its leads to the screw wire from Step 3. .htm . comes with several plates to which you can attach your sensor electronics. 5.218 have a head that is 3/16" in diameter. 4. Conductor Plate Another technique for attaching sensors to the RCX's inputs is based on special conductive plates. or burn out the sensor you're mounting by soldering it directly to the screws. so you don't want to either melt the plastic around the screws by soldering them in-place. but the pan head is shaped more like a LEGO stud. You should only have to push it a little bit to get it to fit. Turn on the drill and use a file to reduce the diameter of the head. This technique is fully described at:. here are some construction tips: 1. You can use pan head or round head machine screws. so that it's level with the surface of the brick.html . you should replace diagonally opposite studs so that the sensor will be connected to the RCX.ca/tfm/lego_temp. In the meantime. 2. You'll see an example of this technique later. #5037. you may also need to flatten the top of the head. You can test your modifications by trying to place the head of the screw in the bottom of a wire brick. Instead of drilling out the stud. An example of this technique is shown at. Again. 3. Then you can drill a hole and thread the screw down into the brick.bc. Make sure to use heat sinks so you don't undo your previous work or damage the sensor. Some 4/40 machine screws have heads that are larger than a LEGO stud. Solder a short wire to the tip of each screw before you put the screws in the brick.akasa. just shave off the top of it. There are two very good reasons for this.75US.kabai. Now turn the screws into the brick— they should thread nicely into the holes. which is $6. regardless of the orientation of the wire brick. The kit. from the LEGO Shop-at-Home service (800-453-4652). Now make sure the screw heads are the right size.com/lego/lego. Begin by shaving off two diagonally opposite studs on the brick. You can adjust the diameter of the screw by mounting it in a drill (with the head facing out). Thread the wires you just soldered to the screws into the holes in the top of the brick. All you need to do is attach the switch leads to the input somehow. Figure 11-2 shows a photograph of a mercury switch. Touch Sensors Touch sensors are the easiest kind of sensors to make. The A/D converter itself has a resistance. you may have seen ones with clear bulbs in your thermostat. it's helpful to see a diagram of one input of the RCX in passive mode: In passive mode. The LEGO brick is shown for scale. the sensor connected to the input is essentially a resistance. These are the simplest do-it-yourself sensors because you don't need any interface circuitry to make their output comprehensible to the RCX. The A/D converter in the RCX converts the analog voltage to a digital raw input value from 0 to 1023. When the switch is oriented the right way. the mercury drop connects the two switch leads together. A mercury switch has a sealed bulb that contains a drop of mercury. . Browse the pages of a catalog from Jameco (800-831-4242) or Digi-Key (800-344-4539) and you'll find a dizzying array of contact switches. Another interesting possibility is using a mercury switch as a touch sensor.219 Passive Sensors There are several simple passive sensors that attach directly to the inputs of the RCX. It forms a voltage divider with Rinput. Rad. and no special circuit is necessary. Any kind of contact switch is appropriate. A Peaceful Demonstration To really understand passive sensors. The two diodes limit the voltage that can be seen by the A/D converter. but it's so small you probably don't have to worry about it. this makes it hard to damage the RCX by hooking something up incorrectly. Figure 11-3 shows a photograph of one such photoresistor mounted in a brick using the machine screw mounting method. To do this. The extra wire can be pushed up inside the brick. . Figure 11-3.220 Figure 11-2. Then the leads were threaded through to the inside of the brick and soldered to the wires that were already there. Basically all you have to do is hook up the leads of the photoresistor to one of the RCX inputs. the two leads are shorted together. the mercury switch is used to indicate two states: either it's less than the desired angle or greater than the desired angle. The desired angle in a thermostat corresponds to the temperature setting you've chosen. two holes were made for the leads of the photoresistor. it emits light using an LED. for example. It's basically a primitive angle sensor. All that remained was to mount the photoresistor itself in the brick. but it must be powered. When the switch is correctly oriented. and senses light with a phototransistor. These wires were previously attached to the screws. In a thermostat. can be used to build a passive light sensor. A CdS photoresistor mounted in a brick The machine screws were mounted on the brick as described previously. The phototransistor responds to changes in light. A slightly simpler device. A mercury switch The mercury switch works just like a contact switch. Light Sensors The light sensor that comes with RIS is a powered device. a photoresistor. This is a perfect candidate for an RCX sensor. The photoresistor responds to changes in light by changing its resistance. Figure 11-4 shows a photograph of the bottom of the same photoresistor sensor. Radio Shack sells Cadmium Sulfide (CdS) photoresistors that work well as robot sensors. Powered Sensors It's a little harder to attach a powered circuit to the RCX. SENSOR_TYPE_TOUCH). SetSensorMode (SENSOR_1. the CdS photoresistor is a passive device. you can figure out the temperature. By measuring the resistance of the thermistor. these wires alternately power the sensor and read its value. Thus. your temperature readings will be off slightly. rather than just sensing increases and decreases in temperature. Chances are. you can configure the input as follows: SetSensorType (SENSOR_1. Remember. If you are concerned about correct temperature readings. Darker lighting will produce higher sensor readings. make sure the sensor is not powered and read the raw input values. SENSOR_MODE_RAW). Thermistors are widely available and cost only a couple of dollars each. Although LEGO's light sensor is a powered device. creating a small hole. however. there are only two wires connecting the RCX to each of its sensors. In NQC. Temperature Sensors A simple device called a thermistor can be used to make a temperature sensor. while bright lighting produces lower sensor readings. If you don't have one of these.221 Figure 11-4. . you may want to convert raw sensors readings into temperature values yourself. You'll have to experiment to find out what kind of values you get for different lighting conditions. you can heat a wire with a soldering iron and push it through the side of the brick. For powered sensors. A bottom view of the CdS photoresistor sensor You can make holes for the sensor leads using a small drill. for example. instead. The thermistor has a resistance that changes according to the temperature. You should. that your device won't have the same electrical characteristics as the official temperature sensor. This means that you can't blindly configure the photoresistor input as a light sensor input. except for the 8V power supply. Remember how the direction of the motors depended on how they were attached to the RCX? The same problem applies to sensors and sensor circuits. the polarity of the signals may be reversed.1 millisecond. Diodes are used to steer the electrons the correct way . Furthermore.5V to 8. so this may not be an issue for you. The following figure shows a diagram of an RCX input in active mode: The active mode circuit looks a lot like the passive mode circuit. Many electronic circuits are happy with 5V or more. The 8V that is supplied to the active sensor is an approximate number. depending on how the sensor is attached to the RCX. The circuit makes sure that all the electrons go in the right directions so your sensor circuit gets power and the RCX gets a sensor reading. These six diodes make up a circuit called a signal splitter. at least. At the end of every power intervals. but a special circuit makes it irrelevant which way the sensor is hooked up. and the RCX takes a reading from the input. But it's something you should be aware of. Six diodes are sufficient to separate out the power and signal on an input. The difference between fresh and used batteries can produce any voltage in the range from about 6. Signal Splitter The input wires carry power and sensor signals at the same time.5V. the switch opens for 0. the actual value depends on the juice in your batteries.222 Active Sensor Magic The designers of the RCX pulled some magic out of their electrical engineering bag to enable active sensors. there's a switch S that closes for three milliseconds at a time to supply power to the sensor. Conceptually. A Hall effect sensor ∗The signal splitter is really a combination of two circuits. A signal splitter Remember. The current router ensures that the sensor signal is supplied with the correct polarity to the input on the RCX. . Figure 11-6 shows a photograph of a Hall effect sensor. The sensor itself is very small and looks like a transistor. Figure 11-6.∗ Figure 11-5.1 ms sensor readings. The Touchless Touch Sensor This section describes how to build an interface circuit for a Hall effect sensor. If you place a small magnet near the sensor in the proper orientation. punctuated by . A Hall effect sensor is triggered by the presence of a magnetic field.223 so that it doesn't matter which way the active sensor is attached to the input on the RCX. You will need to smooth out the power supply with a capacitor. it consists of the left four diodes in Figure 11-5. power is only applied for 3 ms at a time. Figure 11-5 shows how to set up the diodes. a bridge rectifier and a current router. it will trigger. as shown in Figure 11-5. The right two diodes in Figure 11-5 make up the current router. The bridge rectifier ensures that power is correctly supplied to the active sensor. You could build the Hall effect sensor and the signal splitter circuit into a large LEGO brick. SENSOR_TYPE_LIGHT). SENSOR_MODE_BOOL). some respond to both. Read the fine print closely when you buy a Hall effect sensor. it looks like this: SetSensorType(SENSOR_3. Figure 11-7. what can you do if you want to use . as shown in Figure 11-7. One polarity turns the sensor on. How you use this sensor is. counters. you need to configure the input for a powered sensor. up to you. SetSensorMode(SENSOR_3. Remember. of course. the RCX still has only three inputs and three outputs. Then you could build small permanent magnets into other LEGO bricks. This sensor responds to both magnetic polarities. you can read boolean values from the appropriate input. Some have on-board circuitry that processes the sensor's signal and converts it to a boolean electrical signal. The processing circuitry is all built into the sensor. This would give you a flexible system. In NQC. though. The on or off setting "sticks" until the opposite magnetic field is applied. and the other turns it off. or anything you can imagine. The circuit presented in this section is built around a "sticky" Hall effect sensor (Digi-Key part number DN6847SE-ND). Short of using another RCX. Touch Multiplexer No matter what software you're running. Hooking up the sensor to the RCX is a matter of applying the signal splitter circuit from the previous section. A Hall effect sensor circuit Once the sensor is hooked up.224 Not all Hall effect sensors are created equal. Some respond to one polarity of magnetic field. suitable for building limit switches. You can convert the raw value to a resistance with the following equation. which results in a unique raw input value. which is better suited to our touch multiplexer. a Robot with an Arm. Note that the resistors roughly double in value as you move from left to right. Each combination of switches produces a unique resistance. Chapter 5. Minerva. but you can't tell which of them was pressed when a touch occurs. you can figure out which touch sensors were pressed. there are some tricks. A garden variety switch is much more of a binary device. The touch multiplexer circuit Pressing a single switch shorts out the corresponding resistance. The touch sensors that come with RIS provide a varying resistance as they are pressed. describes some ways of putting more than one sensor on a single input.∗ The basic circuit is shown in Figure 11-8. not the LEGO touch sensors. Michael Gasperi's design combines resistors in parallel. This circuit is called a touch multiplexer. This idea was originally suggested by Paul Haas. at least. which reduces the raw input value. where raw is the raw input value: ∗John Tamplin deserves the credit for this idea. A simple circuit allows you to hook up four switches to a single input and detect them individually. the touch sensors each reduce the raw input readings by recognizable amounts. It's possible to put multiple switches on a single input. The touch multiplexer is based on a fundamental concept in electronics: the combination of different resistances. one implementation is documented nicely at Michael Gasperi's web site. This makes it easier to interpret the results of the touch multiplexer. By examining the raw input values in your robot's program. Figure 11-8. The touch multiplexer I'll describe here combines resistors in series. Note that this method uses regular switches. Because each touch sensor has a different resistance.225 more than three inputs or outputs? On the input side. . which simplifies the math. because it mashes three input signals into one. Each bit is 0 when the switch is closed (pressed) and 1 otherwise.226 Once you've got the resistance. The raw input value depends on the battery voltage. What About Actuators? I've talked a lot about building sensors. although it's possible you could use them to signal other robots. Adding 1/2 in the previous equation (and rounding to an integer) helps compensate for this and allows the touch multiplexer to work until the batteries are about half-drained. this circuit uses an op amp to amplify the signal from a microphone. and assuming you have a binary progression of resistors. why not build actuators too? LEGO only offers two actuators: motors and lights. which means that the calculated value of R becomes lower. you can convert the input resistance to a bitmask of switch presses with this equation: The bitMask will contain four bits of information. Once you've built the signal splitter (Figure 11-5). . Other Neat Ideas This chapter has presented some simple sensors you can build yourself. Michael Gasperi has built several interesting sensors based around the use of operational amplifiers (op amps). This process allows you to easily build a robot that seeks light. but there are many other possibilities. you can attach any old electronic circuit to the RCX's inputs. you can program your robot to respond to sound. The lights aren't very practical and usually serve only a decorative purpose. the raw reading will become lower. Michael has also built a differential light sensor. one for each switch. The circuitry interprets the signals from the two photoresistors and sends a signal to the RCX that indicates the balance of light between the two photoresistors. This sensor actually contains two photoresistors and some circuitry. The first of these is sound sensor. This sensor can detect sounds like hand claps. Michael Gasperi's web site (listed in the ''Online Resources") has several outstanding ideas. Basically. As the batteries drain. While a servo has only a limited range of angular motion. They are actually an assembly of a motor. you can heat SMA wires by passing current through them. and links to other people's RCX sensor web pages. It contains a wealth of information about the inputs themselves. the LEGO-only solution is more flexible. and some electronics. Conveniently. You'll probably also need a power supply for the servo. they rotate an output shaft to a certain angle. The bottom line. It's full of schematic diagrams. You can buy wires that contract when they are heated. and Shape Memory Alloy (SMA) wire: servo motors Servo motors are special motors that are used in radio controlled cars and airplanes. graphs. robots have all sorts of different actuators. Online Resource General Information Mindstorms Sensor Input. solenoids. Three good possibilities for do-it-yourself actuators are servo motors. or buy them new from a supplier like Jameco. and sensors you can build yourself. that heated SMA wire can melt LEGO bricks—mounting the SMA wire may be a challenge. SMA wire should be simple to interface to the RCX's outputs. SMA wire Shape Memory Alloy is a special kind of metal that changes shape dramatically when it's heated. however. In response to an electronic signal. As a matter of fact.plazaearth. . some gearing.htm This is the definitive online resource on the inputs of the RCX. solenoids A solenoid converts electrical power into a small linear motion. explanations. Interfacing a servo motor to the RCX is a matter of making the RCX produce the right signal.227 Outside the tidy world of LEGO MINDSTORMS. is that you can get just as much done with a LEGO motor and a LEGO rotation sensor. You can harvest solenoids from discarded fax machines and cassette players. however. The whole point of a servo is that it rotates to a precise angular position.com/usr/gasperi/lego. the official LEGO sensors. Note. the motor and rotation sensor have no such constraints. however. but that's just as easy to do with a motor coupled to a rotation sensor. TFM's Lego Page .com/powertools. However. and the wire bricks. the sensors.ibm. This page has a clear description of the technique.patents. It demonstrates the machine screw mounting method.com/usr/gasperi/temp.com/lego/lego. the screws are not mounted on diagonally opposite studs. Mounting Methods Homebrew Temperature Sensor Dremel makes hand tools that are good for working with small things like LEGO bricks. Tools Black and Decker. .228 Toy building block with electrical contacting portions (US4552541). which would make them more useful.ca/tfm/lego_temp.Lego Mindstorms Compatible Temperature Sensor. the motors. LEGO Black and Decker makes a tool called the Wizard.plazaearth.html This page describes the construction of a temperature sensor using the conductor plate mounting method. the basic technique is very well illustrated. Welcome to Dremel International This page has brief instructions for building a sound sensor for the RCX. Did you ever wonder why you can attach wires and sensors in any orientation and still make a connection? This patent explains the system. Putting the tubing on diagonally opposite studs would make this sensor more generally useful. However. it's useful for shaving the studs off LEGO bricks.com/details?pn=US04552541 This is the patent that describes the clever scheme used by the input and output connectors on the RCX.htm Michael Gasperi's temperature sensor uses the copper tubing method of sensor mounting. With a cutting disk. Digi-Key Corporation Home Page. . and other great stuff. try Digi-Key instead.com/ If there's something you can't find at Jameco (thermistors.mouser. Mouser Electronics. diodes. resistors. They have a huge selection and good service. for example). where you'll find goodies like switches. bend sensors.229 Electronics Parts Suppliers Jameco Electronics: Home. their web site is a little easier to use than Digi-Key's. Distributor of Electronic Components Here's another good supplier. Hall effect sensors.digikey.jameco.com/ This is the web site of Jameco. and Pitsco is Pitsco LEGO DACTA. S@H is LEGO Shop-at-Home Service. and other robot parts from several sources. Table A-1. This information is current as of mid-1999. including RIS.com/. Sources for LEGO Parts Name LEGO World Shop LEGO Shop-at-Home Pitsco LEGO DACTA Telephone Service (800) 453 – 4652 (800) 362 . .com/ Pitsco LEGO DACTA sells LEGO's educational products.230 A Finding Parts and Programming Environments You can order sensors.) Note that the Shop-at-Home Service does not charge extra for shipping.legoworldshop.pitsco-legodacta. classroom packages. and a fine assortment of spare parts. you'll hardly ever see extra motors and sensors. a programming environment called ROBOLAB. Although you can probably find the Robotics Invention System (RIS) at a local toy store. LEGO Sources Table A-1 lists three places where you can get RIS accessories. (LWS is LEGO World Shop. motors. Parts Table A-2 lists the parts you may wish to buy along with their prices at the three sources shown in Table A-1. so the list is not exactly comparing apples to apples.4308 Web Site. 75 $10.00 $27.75 $27. .99 $18. 128 cm Wire brick set Large turntables Other Suppliers Table A-3 lists suppliers for electronics parts.00 $24.00 $17.99 $129.50 $9. Make Your Own Sensors.75 $11.com/ $54.50 $11.25 $19.50 $27.00 $12.99 $9.50 $19.com/ $54.50 $17.mouser. Table A-3.99 $49.00 $16. Parts and Prices.00 $15.00 $15 $27.digikey. These are useful sources for the electronics described in Chapter 11.00 $49. in US Dollars Part Robotics Invention System RoboSports expansion set Extreme creatures expansion set RCX IR cable for Macintosh Light sensor Touch sensor Touch sensor (two wire bricks) Temperature sensor Rotation sensor Geared motor Micro motor Standard motor Train motor Remote control Electric plates Wire brick.75 $4.75 Programming Environments Table A-4 summarizes the development environments that are available for the RCX.75 $6.com/ Item 9719 9730 9732 9709 9758 9757 9755 9756 5225 5119 5114 5300 9738 5037 5111 Pitsco Item N979719 N979709 4119830 N979890 N779911 N979889 N979891 N775225 N775119 N775114 N779886 N779897 N779876 LWS $219.00 $19.99 $14.99 $19.99 $24. Sources for LEGO Parts Name Jameco Digi-Key Mouser Telephone (800) 831 – 4242 (800) 344 – 4539 (800) 346 – 6873 Web Site Table A-2.00 $129.jameco.75 $11.50 Pitsco $219.75 $6.99 S@H $219.00 $120.75 $15. .htm VB-like no free Win32 - BotCode no $20 Win32 - a.html MindControl. Most of the Win32 packages work with Spirit.umbra. which is installed with the RIS software.co. RCX Development Environments (continued) Replacement Language Firmware? Price Host OS Tools Neededa VB-like VB-like no no Free free Win32 Win32 - Name URL Gordon´s Brick. c.nl/brok/ legomind/robo/mindcontrol.fcj.psy.ca/~cousined/ VB-like lego/robot/rcx/rcx_command/l Table A-4. Win32 means Windows 95. This column assumes you've installed the RIS software.uk/gbp.svc. VB-like means similar to Visual Basic.demon. Function names are modeled on Spirit.hvu. or NT. 98. b.html PRO-RCX. netway.ceeo.netway. Function names are modeled on Spirit. 98.com/lego/ pbFORTH/. or NT. Linux. which is installed with the RIS software.C++ yes free Linux.tufts. Linux.com/dacta/robolab (visual) /defaultjava. Most of the Win32 packages work with Spirit.com/~dbaum/lego/nqc/ Language Firmware? Price Host OS Tools Neededa (visual) NQC no no free Win32b - MacOS. Unix Win32 Win32 - BrickCommand VB-likec no free a. . This column assumes you've installed the RIS software. Unix Win32 Win32 BrainStorm Bot-Kit. Win32 means Windows 95.object-arts.enteract.com/~dbaum/lego/nqc /macnqc/ NQC no free ROBOLAB UCBLogo Smaltalk no no free free UCBLogo Dolphin Small-talk TclRCX. RCX Development Environments Replacement Name RCX Code Not Quite C (NQC) URL. Win32 MacOS MacNQC. Win32 pbFORTH yes free Any Terminal emulator GNU egcs and legOS C.com/Area51/Nebula/ 8488/lego.com/~rmaynard/ Table A-4.ocx.ocx.demailly.lego. VB-like means similar to Visual Basic.com/tcl/rcx/ Tcl no free MacOS. c.com/~rmaynard/ Forth no $50 MacOS. b. ocx. b. which is installed with the RIS software. Function names are modeled on Spirit. c.234 Table A-4. Win32 means Windows 95. Most of the Win32 packages work with Spirit. RCX Development Environments Name URL Language a. This column assumes you've installed the RIS software. 98. or NT.ocx. . VB-like means similar to Visual Basic. If pbFORTH complains about something. It's very simple to use—you just need to supply the name of the Forth source code file. but there are not many tools available for it.....sun....com/products/javacomm/).com/products/jdk/1. This appendix contains source code for a program downloader..sun... it analyzes the responses from pbFORTH to see if any errors occur as the download is progressing...1 or later (see B A pbForth Downloader pbFORTH is a interesting. c:\> . A program downloader enables you to develop your pbFORTH programs in a text editor and download them all at once to the RCX. For example. You'll also need the Communications API....... the downloader tells you about it. funky programming environment...f .2/ for the latest version).... Usage The program downloader is called Download. System Requirements To compile and run this program. The program downloader presented here is a "smart" one... a standard extension API that enables Java programs to use the serial and parallel ports of a computer (see.. written in Java. you'll need the Java Development Kit (JDK) version 1. you can download a file like this: c:\>java Download thermometer.. This means you have a saved copy of your program that is easy to browse and modify. println("Sorry.out. public class Download { public static void main (String[] args) { String filename = args[args.. Writer mOut.f . I don't know about the " + portName + " port.equals("-port")) portName = args[i + 1].out.println("An IOException occurred: " + ioe). Download uses the COM1 port..."). } } private private private private SerialPort mPort.∗.util.println(ucoe). portName).io. import java.2.length . } catch (UnsupportedCommOperationException ucoe) { System. you can tell Download to use a different port like this: C:\>java Download -port COM3 thermometer. somebody else is using " + portName + ". } catch (IOException ioe) { System.comm. } try { new Download (filename. Line 5: Error: redefine isRunButtonPressed RbuttonState ? undefined word c:\> By default.∗. PortListener mPortListener.1]. for (int i = 0. Reader mFileIn.out. } catch (PortInUseException piue) { System.println("Sorry. } catch (NoSuchPortException nspe) { System.236 Download prints a period for each line of the file it downloads to the RCX. . i < args. import javax.∗. private static final int kCharSleep = 20. String portName = "COM1". or if you have your IR tower attached to a different port. "). If you are not running Windows.length . you'll hear about it like this: c:\>java Download thermometer. If there's an error.f Source Code import java. i++) { if (args[i].out. } } sendReturn(). UnsupportedCommOperationException. String portName) throws NoSuchPortException.DATABITS_8.print(".setSerialPortParams( 2400. try { sendReturn(). if (mPortListener. } System.out.isComplete() == false) { throw new DownloadException("Timed out waiting " + "for a response from the RCX.write(c). mOut = new OutputStreamWriter(mPort.isError() == true) { throw new DownloadException("Error: " + mPortListener.PARITY_NONE ). mOut. sendReturn(). } public void run() { int c. mPortListener = new PortListener (in). UnsupportedCommOperationException.reset(). n++. PortInUseException.").getOutputStream()).flush(). SerialPort. IOException { CommPortIdentifier id = CommPortIdentifier. mPort.open("Download". Thread. while ((c = mFileIn. . mOut.getLastLine()).getInputStream()). SerialPort.237 private static final int kTimeOut = 800.read()) != -1) { if (c == '\r') { sendReturn().sleep(kCharSleep). IOException { initialize(portName). run(). } else if (mPortListener. Reader in = new InputStreamReader(mPort. public Download(String filename.STOPBITS_1. mPort = (SerialPort)id.getPortIdentifier(portName). PortInUseException. } protected void initialize(String portName) throws NoSuchPortException."). mFileIn = new FileReader (filename). 1000). SerialPort. } else if (c != '\n') { mPortListener. n = 1. } catch (DownloadException de) { System.sleep(20).out.flush(). } public void run() { String line.println("Line " + n + ":"). Thread.out.savedTime > kTimeOut) trucking = false. boolean trucking = true.close(). } // Regardless of what happened. try to clean up. long savedTime = System. System.out. private boolean mError = false. mPort.close(). mOut. // Wait for response. mFileIn.println(ioe).close().println(" " + de.out. long currentTime = System. mOut. private BufferedReader mIn.exit(0). private String mLastLine. if (currentTime .out.currentTimeMillis().isComplete()) trucking = false.println(ie) .start().currentTimeMillis().sleep(kCharSleep). public PortListener (Reader in) { mIn = new BufferedReader(in). or time out.println(). } protected void sendReturn() throws IOException. } } public class PortListener implements Runnable { private Thread mThread.stop(). } catch (InterruptedException ie) { System. mThread = new Thread(this).getMessage()).238 sendReturn(). while (trucking) { if (mPortListener. try { while((line = mIn. System. try { mPortListener. Thread. } catch (IOException ioe) { System.readLine()) != null) { . InterruptedException { mOut. private boolean mComplete = false. } catch (IOException ioe) {} System.write('\r'). mThread. } } public class DownloadException extends IOException { public DownloadException (String message) { super (message). } } } .indexOf("undefined") != -1) mComplete = mError = true.length() == 0) mComplete = true.indexOf("redefine") != -1) mComplete = true. if (line.trim(). } public boolean isComplete() { return mComplete.out. } public boolean isError() { return mError. if (line. mLastLine = line.println("PortListener: ioe " + ioe). } public void reset() { mComplete = false. if (line. mError = false. } } catch (IOException ioe) { System.239 line = line. if (line. } } public void stop() throws IOException { mThread. } public String getLastLine() { return mLastLine.indexOf("ok") != -1) mComplete = true.interrupt(). It's supposed to be released in the Fall of 1999. These are things either that weren't quite fully complete as the book went to press or that aren't entirely relevant to a general book on LEGO robots. Smalltalk. but what actually comprises RIS 1. The basic premise of JINI is that devices should be able to connect and disconnect from networks seam- .5 The first thing to look for. Java for the RCX You can program your RCX in C. the Motorola 68HC11.5 is anybody's guess. of course. is RIS 1. keep your eyes peeled for real announcements. why not Java? The RCXJVM project aims to build a small Java Virtual Machine (JVM) and supporting classes for the RCX. As of this writing (August 1999).5. RIS 1. not a change to the RCX. (That JVM reportedly was only 6k. At this point. an off-hand mention in the discussion forums at the official LEGO MINDSTORMS web site. It's based on a JVM developed for a different 8-bit microcontroller. which would certainly fit fine in the RCX's 32K of RAM. and Visual Basic.) LEGO Robots as JINI Devices JINI™ is a Java™-based standard from Sun Microsystems™. it's all rumors and speculation. Tcl. though.240 C Future Directions This appendix mentions several interesting technologies related to LEGO robots that didn't make it into the rest of the book. there's been only a whisper of it. One person at LEGO technical support did say it is a softwareonly upgrade. C++. Jan Newmarch has written a JINI tutorial that includes examples with LEGO robots. LEGO robots. but it's still a work in progress.edu. Personal Digital Assistants. be able to plug your laptop computer into a hotel network jack somewhere and be able to use the printer. and. You should. However. of course. The network vision extends beyond these traditional devices. Here's a discussion from mid-1999:. see the discussion lists at LUGNET. pagers.au/java/jini/tutorial/jini. it still makes for an interesting technology blend. You can read it for yourself here: At one of the keynote speeches for the 1999 JavaOne conference. without going through a lot of network configuration gobbledygook.com/developer/technicalArticles/ConsumerProducts/JavaTanks/Javatanks.com/robotics/rcx/legos/?n=180&t=i&v=c .xml LEGO Network Protocol LEGO Network Protocol (LNP) would allow two or more RCXs to communicate via their IR ports without prior configuration. A detailed article on this demonstration (including source code) is here:. it's not a generalized solution. to things like mobile telephones. communicates with the robot over the IR link.Independent of the JavaOne demonstration.javasoft. LNP is a more general approach. a demonstration of JINI included LEGO robots as JINI devices. in fact. Unfortunately. While it is possible to exchange messages between multiple RCXs by reserving blocks of message numbers for specific RCXto-RCX conduits.lugnet. A proxy system is used instead. For more information.canberra. JINI doesn't actually run on the RCX. however.241 lessly. in turn. which. for example. such that a JINI proxy runs on a PC. 233 web site. 184 architecture. 171 bouncing. 191 web site. 234 Bot-Kit web site. 233 BrickCommand. 172 building projects (see projects) bumpers. robotics and. 32 binutils package. 188 arms grabber. 112 batteries. 214 BotCode web site. 8 building. 31 . 33 arbitration. 49 angular velocity. robotics and. 4 ambient light. retrieving current charge. 153 BrainStorm web site. 107 Artificial Intelligence (AI).242 Index A actuators. 15 bevel gears. 4 autonomous robots. 3 B balancing robots. 227 AI (Artificial Intelligence). subsumption. 105 swing. 204 web site. 156 mechanical. 168 beams. attaching sensors with. 70 pbFORTH. 13 cross-compiling. 27 synchro. 30 web site. 218 constants. 107 web site. 115 display configuring NQC. 163 differential. 214 D datalog. 27 differential light sensor. 226 directional transmission. 38 .243 bushings. 15-16 buttons. legOS functions for. 168-171 debouncing. 128 functions (legOS). 29-30 conductor plate. 194-195 drives differential. 217 Crickets web site. 191 web site. 166 copper tubing. 153 delayed functions. attaching sensors with. 71 retrieving. 30 differential drives. 198 C cars. 215 Cygwin package. 191 web sites. 214 Epistemology and Learning Group (E&L Group) web site. 10 Extreme Creatures. 13 expansion sets. 144 firmware. xiii functions legOS. 34 gearing down. 13 emulegOS web site. 37 examples in this book. 214 E&L Group (Epistemology and Learning Group) web site. 215 Forth programming language. 163 G gear reduction. 116 downloader. 191 web site. 34 geared motors. 10 F feelers (see touch sensors) firmdl. 108 . 112 Droid Developer Kit. 34 gears.244 tri-star. 31-35 worm.ocx. 10 E egcs compiler. 37 drivetrains. 10 Exploration Mars. 121-126 FTP sites. 192-193 web sites. 194-204 Spirit. 13 Eureka web site. the Bumper Tank. 50 If function (Spirit. 227 instructions for building Hank. 165-166 legOS. 40-44 internal gearing. 81 I idler wheels. 166-167 immediate functions. 174-179 thermometer.245 grabber arms. 16-25 programming. 115 H Hall effect sensor. 16-25 Minerva. 163 infra-red data link.ocx). 27-38 instructions for building. 119 . 7 legOS. retrieving. 204-211 Hitachi web site. 147-150 RoboTag. 156 web sites. the Bumper Tank. 137-138 Trusty. 196-197 web site. 7 communications NQC. 83-102 remote control. 198-199 inlines. 75 inputs input values. 70 pbFORTH. a Line Follower. 223-224 Hank. 34 IR (infra-red) link. 240 K Killough platform web sites. 158 legOS. web site for. 233 locomotion. 214 functions. 39 Linux. 213 light sensors. 226 legOS. 194-204 static variables. 211 emulator. 157 LEGO Shop at Home. 205-211 line following. 212 development cycle. 38 -L Large Turntable piece.c program. 51 in NQC. 50 building. 27-35 LUGNET (LEGO Users Group Network) web site. 30 LEGO Group web site. robots as. 197 programming. 79-80 LightSeeker. 35 LEGO Users Group Network (LUGNET) web site. 212 web sites.246 J Java for RCX. 11 LEGO Network Protocol web site. 220-221 differential. 158 . 113 adding a second. 233 debugging. 240 JINI devices. 13 mobile robots. 27-35 motors. 233 magnetic compasses. 38 mounting sensors. 11 Minerva instructions for building. requesting (legOS). 37 wheels. 233 . 83-102 programming. 34 MindControl web site. 114 memory. 202 micro motors. 114 web site. xi web sites. 227 web sites. 234 MINDSTORMS. 199-203 NQC. 2-6 web sites. 103-107 pbFORTH. 68-70 N navigation. 72-74 music. 36-37 in legOS. 6 history of. 154-157 MIT Programmable Brick web site. attaching sensors with. 217 Macintosh platform.247 M machine screws. 115 Not Quite C (NQC). 34-35 servo. 138-142 remote control. 217-218 multitasking. 54 web sites. 51 . 38 plates. 191 web site. 167 outputs. ordering. 126-137 PBTurnOff function (Spirit. pbFORTH. web sites) operators for If and While functions. 9 Programmable Brick FORTH (see pbFORTH) programming debugging.248 downloading. 221-224 program downloader. 168 Perl. controlling in legOS. 142-143 program downloader. 143 O online resources (see FTP sites. 143 words. 232 (see also web sites) passive sensors. 233 debugging. the Bumper Tank. 204-211 legOS (see legOS) light sensors. 15 Poll function (Spirit. 214 Pitsco LEGO DACTA web sites. 134 powered sensors. 196 P parts. 165-166 power management.ocx). 235-239 web sites.ocx). 142-143 Hank. 219-221 pbFORTH (Programmable Brick FORTH). 214 . a Line Follower. 138-142 remote control. 135-137 in legOS. 72-74 cooperative multitasking. 82-115 projects (continued) remote control. 147-154 RoboTag. the Bumper Tank. 103-107 pbFORTH. 154-157 multitasking. 53 RCX Command Center (RcxCC). 109 R random numbers. 81 RCX (Robotic Command Explorer). limitations of. a Line Follower. 64 remote control. 199-203 NQC (see NQC) pbFORTH (see pbFORTH) random numbers.249 Minerva. 64 legOS. 168 web sites. 39-51 pulleys. 145-146 programming environment. 180-188 Trusty. 55-57 turning off. 151-154 RoboTag. 203 RCX Code. 58 web site. 174-188 Trusty. 9 software architecture. 204-211 Minerva. 77-80 projects Hank. 168 sensor watchers. 151-154 RIS (Robotics Invention System). 6-7 history of. 173-188 instructions for building.250 RCXJVM. 240 remote control instructions for building. 180-188 web site. 11 Robotics Discovery Set. xi software. 188 Robotic Command Explorer (see RCX) robotics Artificial Intelligence (AI) and. 5 web sites. 197 S SaveDatalog function (RCX). 2-6 balancing. 10 Robotics Invention System (see RIS) robots. 114 legOS. 10 RoboTag. 180 small approach. 112 rotation sensors. 9 version 240 web sites. 38 Robosports. 174-179 programming. 4 behaviors. 147-150 programming. 12 Robolab software. 36 . web site. 164-165 behaviors. 197 mounting.251 sensors. 171 standard motors. 30 web site. 188 symbolic constants. 217-218 passive. 38 T tasks. 171 solenoids. 164 subsumption architecture. 134 playing. 227 sounds legOS. 227 signal splitter. touch sensors) servo motors. 219-221 powered. 203 pbFORTH. 221-224 web site. 222 SMA (Shape Memory Alloy) wire. 227 shafts. 52 (see also light sensors. 166 synchro drives. 227 Smalltalk web site. 68-70 sensors. 159-171 web sites.ocx. 228 Spirit. 180 . 15 Shape Memory Alloy (SMA) wire. 204 web site. 34 subroutines. 226 building. 216 legOS. 221 thermometer. 112 building. 29-30 (see also zero turning radius) U Unix. 137-138 timing. 77-80 turning radius. 114 tri-star wheels. 27 triangulation. 40-44 programming. 224-226 touch sensors. 48 tethered robots. 169 V View button (RCX). 159-171 . 223-224 train motors. building instructions. 35 treads. retrieving. 44-47 in NQC. 30 web sites. 145-147 (see also remote control) temperature sensors building. 233 UploadDatalog function (Spirit. 37 Trusty. 33 touch multiplexer.ocx). 165-166 torque. 221 web site. 228 Test Panel. 113 timer values. 48 Visual Basic. a Line Follower instructions for building. 3 thermistor.252 telerobotics. 188 Spirit. 11 legOS.ocx). 233 legOS and. 171 Windows platform.253 Visual C++. 11 NQC. 214-215 wire brick. 115 electronic. 143 Pitsco LEGO DACTA. 160 W web sites challenges and competitions. 81 Killough platform. 214 RcxCC. 108 worms. 32 . 229 sensors.ocx. 16 attaching sensors. 11 MINDSTORMS. 213 LUGNET. web site for. 166-167 Windows platform. 50 While function (Spirit. 38 LEGO Group. 12 RoboTag. 81 RIS. 217 worm gears. 214-215 wheels. 38 RCX. bevel. 158 Hitachi H8. 143 parts. 228 pbFORTH. 27-35 idler wheels. 254 Z zero turning radius. 27 (see also turning radius) . our books use RepKover™. fears. and hopes of inventors and spectators for many centuries. The text and heading fonts are ITC Garamond Light and Garamond Book. Melanie Wang and Jane Ellin provided quality control reviews. or androids. in the process raising philosophical questions about the nature of life and humanity and the many implications of creating lifelike toys. If the pagecount exceeds RepKover's limit. and literature.255 About the Author ''Java" Jonathan B. European automata and their mechanics or creators were viewed as mystical and magical—conjuring lifelike beings through suspect means. are imitations of living beings. The image on the cover of The Unofficial Guide to LEGO® MINDSTORMS™ Robots is a mechanical toy rabbit or automaton. perfect binding is used. and the second and third editions of Exploring Java™. Machinery progressed from wateroperated to weight-operated to clockwork structures. Colophon Our look is the result of reader comments. The book was implemented in FrameMaker by Mike Sierra. . The illustrations that appear in the book were produced by Robert Romano using Macromedia FreeHand 8 and Adobe Photoshop 5.3 using Adobe's ITC Garamond font. 1823) and the bejeweled. a durable and flexible lay-flat binding. During the Renaissance. Luke. incorporating such well-known specimens as dolls who can say "Mama" and "Papa" (c. breathing personality and life into potentially dry subjects. Knudsen is a staff writer for O'Reilly & Associates. Jonathan works at home with his wife." This book represents one of Jonathan's lifelong goals: getting paid to play with LEGO® bricks. magic. Whenever possible. Distinctive covers complement our distinctive approach to technical topics. Edie Freedman designed the cover of this book. from Prometheus to Asimov. Alicia Cech designed the interior layout based on a series design by Nancy Priest. Daphne. enameled eggs created by Russian Court Jeweler Carl Fabergé Mechanical toys have affected the progress of industry and been intertwined with myth. Especially notable in the long history of automata are the Chinese and Greek cultures. and has contributed to Java™ Swing. Nicole Arigo was the production editor and proofreader for The Unofficial Guide to LEGO® MINDSTORMS™ Robots. and have captured the imagination. animal or human. This colophon was written by Nancy Kotary. using a 19th-century engraving from the Dover Pictorial Archive. Kristen. and Andrew. He hopes this is the start of something big. and feedback from distribution channels. Java™ AWT Reference. He also writes a monthly online column called "Bite-Size Java. Nancy Crumpton wrote the index. our own experimentation. He is the author of Java™ 2D Graphics and Java™ Cryptography. All photos were taken by Jonathan and Kristen Knudsen. Kathleen Wilson produced the cover layout with QuarkXPress 3. an automated machine. and their children. Biological automata. This action might not be possible to undo. Are you sure you want to continue? We've moved you to where you read on your other device. Get the full title to continue reading from where you left off, or restart the preview.
https://www.scribd.com/document/117880151/The-Unofficial-Guide-To-Lego-Mindstorm-Robots-size-A4-pdf
CC-MAIN-2016-50
refinedweb
59,478
69.79
Pluggable dependency resolverKabir Khan Jan 15, 2010 8:15 AM I have made a start on the pluggable dependency resolvers and am committing stuff to. So far I am just playing to get a rough idea of what is needed. I have extracted the contents of AbstractController.resolveContexts(boolean) and what it calls with AbstractDependencyResolver and DefaultDependencyResolver. AbstractDependencyResolver contains a reference to the controller and utility methods to do work on the controller. DefaultDependencyResolver contains the "work" done by resolveContexts and the methods it called. At the moment DefaultDependencyResolver contains too much controller specific stuff, which I want to move out, but I just wanted to get something in for further discussion. 1. Re: Pluggable dependency resolverThomas Diesler Jan 18, 2010 6:45 AM (in response to Kabir Khan) Hi Kabir, here is a quick describtion of how OSGi bundle resolution works. For details see Module Layer When a bundle is INSTALLED, only its constistency in terms of osgi metadata in the manifest is verified. There is no connection to other Bundles established. From now on, the Framework is free to resolve the Bundle at any time. When a Bundle gets started (explicitly) it first becomes RESOLVED and then ACTIVE. For a Bundle to become RESOLVED all its required Package-Imports and other mandatory requirements must get sattisfied. If a Bundle fails to get RESOLVED it remains in the INSTALLED state and may get RESOLVED at a later time (when more requirements become available). In the transition from RESOLVED to ACTIVE the optionally associated BundleActivator.start() method is called. If that fails, the Bundle remains in state RESOLVED and the user may retry to start the Bundle again at some later time. There are various operations that implicitly (try to) resolve a Bundle. These are and it variants. Note, that Bundle.getEntry(String path) does NOT trigger bundle resolution. A Bundle can also get explicitly resolved through the PackageAdmin.resolveBundles(Bundle[] bundles) method. During bundle resolution, so called 'wires' are established between the exporter of a package and its importers. The resolver may have multiple exporters for a given package name/version to choose from and the most common case is that a Bundle contains a certain package that it may also import from another Bundle. In this case the wire may get established to the Bundle itself. It is a 'self wire'. The resolver is encouraged to find the best possible solution that leads to a consistent class space. A consistent class space is one that satisfies the requirements of all importers and a given package is only exported by one and only one exporter. This can become quite complicated, especially when exported packages define a 'uses' directive. The uses directive means that all Bundles in a class space must get wired (i.e. use) the same exporter for a given package. In the face of multiple possible wiring outcomes, the uses directive helps to make more deterministic choices. Generally the resolver should aim to resolve as many as possible Bundles by walking the tree of possible wirings. In case of many unresolved (i.e. hundreds of) Bundles this can become a very expensive operation. Equinox, disregards possible wirings beyond a certain level of complexity and may not find a good solution. Felix considers more possible solution but may take ages to finally return with "sorry can't do it". Currently, both Equinox and Felix work together on a standalone resolver that may be used by both frameworks (and hopefully) ours in the future. Once a wiring is established, is is never changed unless the Framework is restarted or a set of Bundles is explicitly refreshed through the PackageAdmin.refreshBundles(Bundle[] bundles). It is important to understand that Bundle.uninstall() does NOT remove the wiring. Even after a Bundle is uninstalled it is still possible to load classes from that Bundle. This is true, unless the uninstalled Bundle was never choosen as an exporter and there is no wiring to it. In this case it can be removed from the Framework straight away. Here are a few requirements that I would have on the resolver API - It must be possible to resolve multiple Modules at the same time - Resolution must be based on mandatory/optional requirements and capabilities - Environmental capablities (i.e. OS, JDK, NativeLibraries) may influence the resolver outcome - It must be possible to 'try run' resolution and examine the potential outcome without affecting the running system - The MC resolver should be adaptable to the Felix standalone resolver (details still unknown) - The resolver must have an interface to a repository (i.e. OBR) to be able to pull in unstatisfied dependencies on demand - perhaps others that I may need to add in the future ... hope that helps 2. Re: Pluggable dependency resolverKabir Khan Jan 20, 2010 9:05 AM (in response to Kabir Khan) After a false start with I now have something working with . Most tests in the dependency project pass with this, apart from - BadDependencyTestCase - probably since the calls it checks for now happen differently - OnDemandDependencyTestCase.testChangeDependencyReinstall() - since the ordering is now slightly different What I have so far is quite simple. I am still playing around at the moment, and it needs a lot of tidying up, but here is the basic idea: When calling Controller.install(ControllerContext) the context's dependencies are indexed in the resolver. I put it in a map where the key is the dependency name, the value is a map where the key is the dependent state, and the value is list of controller contexts. Controller.uninstall() removes the context's dependencies from the mentioned map. AbstractController.resolveContexts(boolean) has been modified to AbstractController.resolveContexts(ControllerContext, boolean) where the context being installed via Controller.install() or Controller.change() is the parameter. This delegates on to the IDR2.resolvePlugins will try to install the context in question as far as it can until it no longer can resolve the dependencies for entering a particular state. Once it cannot go to another state, it simply returns. I have added a DependencyResolver.stateIncremented(ControllerContext, boolean) callback that is called by the controller once a context has successfully entered the new state. So for example when a context enters the INSTALLED state, this callback is called, and the dependency map is checked for any entries for the context's name and aliases. Then the dependency map is checked for the contexts waiting for that dependency to enter that state. If there were some contexts waiting, we call resolveContexts() on those dependencies. In addition there is a bit of extra housekeeping for OnDemand contexts. So far I have not yet looked at scoping, and need to come up with a way to handle implicit dependencies such as supply/demand, contextual injection with qualifiers and so on. Running the kernel project I get 47 failures and 47 errors out of 1575 tests with the new DependencyResolver, which should be fixed once I implement what I have just mentioned. I'll make which resolver is used configurable via a system property. Once this is more stable we want to run all the tests for any DependencyResolver. For the dependency project I can just create additional sub classes for the different resolvers, but for kernel that will be a big job since there are so many classes, so I'll look at doing profiles instead. For the dependency project I can just create additional sub classes for test for the different resolvers, but for kernel that will be a big job since there are so many test classes, so I'll look at using maven profiles instead. 3. Re: Pluggable dependency resolverKabir Khan Jan 20, 2010 3:58 PM (in response to Kabir Khan) I've moved things around a bit. The new stuff now lives in. I have added scaffolding to support different types of dependency lookups. So far, I have only implemeted the name/alias based one, which is just what I had before in a different place. The basic idea is that for each kind of dependency item there is an implementation of ResolverMatcher / ResolverMatcherFactory. When indexing a context's dependencies, if the dependency is of type AbstractDependencyItem, the name/alias based one I mentioned is used. I'll implement matchers for when the dependency is a demand or a contextual injection dependency. I'm not 100% happy with needing to implement ResolverMatcher(Factory) for each kind of dependency item, but it is the only idea I have at the moment. 4. Re: Pluggable dependency resolverThomas Diesler Jan 21, 2010 4:00 AM (in response to Kabir Khan) Am I right to understand that - Each deployment bundle mapps to a ControllerContext. - Each ControllerContext may have >0 dependencies. - You call ResolverMatcher for each installed bundle - You get multiple sets potential matches How do you consolidate the sets of potential matches such that you end up with a consistent solution? A1 can get wired to B1 and X1 B1 can get wired to X1 or X2 only when B1 gets wired to X1 can A1 get wired at all Conceptually the MC resolver should support the semantics of PackageAdmin.resolveBundles(Bundle[]) also, there needs to be a notion of 'refresh', which may drop existing wirings and establish new ones to potentially updated bundles PackageAdmin.refreshPackages(Bundle[]) There is also a requirement to do a 'try run' of bundle resolution. This would allow to answer a question like: If I install these bundles will I end up with a consistent result where everything can get resolved? To answer this question the running system must not be affected - remember, you cannot "unresolve" a bundle. In real life, you would give a provisioning system a small set of top level bundles and a pointer to a repository. The provisioning system needs to figure out if and how the complete set of transitive dependencies can be sattisfied before it installs anything (i.e. modifies) in the running system. 5. Re: Pluggable dependency resolverKabir Khan Jan 21, 2010 5:06 AM (in response to Thomas Diesler) Thomas, For now I am working on making the main dependency resolution algorithm pluggable and supplying an optimized version. Once that is done, I will look into your requirements 6. Re: Pluggable dependency resolverKabir Khan Jan 21, 2010 7:50 AM (in response to Kabir Khan) I noticed that some test where dependency items come from annotations were failing, so I have fixed that by adding a dependency item DependencyInfo decorator that tracks when dependency items are added/removed and pushes those to the index. KernelAllTestSuite now has 45 errors and 37 failures. Next I'll look at the indexing other types of dependency such as Supply/Demand and contextual injection 7. Re: Pluggable dependency resolverKabir Khan Jan 21, 2010 9:01 AM (in response to Kabir Khan) Looking at supporting contextual injection in the indexing dependency resolver, I've stumbled upon an issue. The basic idea is simple, record which contexts depend on a given Class. When installing a context, check which contexts depend on it (and its superclasses + interfaces) and increment those. The problem is how to know the class of the context being installed? - KernelControllerContext.getBeanInfo() - do we want to require it to be a KCC? - ControllerContext.getTarget() - will not be valid until INSTANTIATED, but then again it probably does not make sense to have contextual injection with a lesser state, although I am not sure this is checked anywhere. 8. Re: Pluggable dependency resolverKabir Khan Jan 22, 2010 5:23 AM (in response to Kabir Khan) I have got contextual injection and basic supply/demand working, so KernelAllTestSuite is down to 18 errors and 32 failures, most of which are related to scoping. The supply/demand implementation is pretty simple so far. When registered, if a context has demand dependency items, they get recorded. When a context has supplies and its state is incremented, we try to resolve the contexts with demand di's waiting for that state. I hope that will suffice, since I don't want to get involved with the matchers, I might be wrong but I don't think they lend themselves to hash lookups - I would have to iterate over all of them anyway. Similarly, the contextual injection mechanism is also quite light, we only index the wanted class on registring, and on incrementing the state we check for the classes. I don't do anything about the qualifiers. One thing I think we're lacking is "wrong order" tests for contextual injection, at least with qualifiers, so I need to add some. The same might be the case for supply/demand, which I need to check. I've been using concurrent collections in my DependencyResolver and Matchers, which might not be necessary. I thing al the access to the DependencyResolver + Matchers happens with the controller lock taken, but again I need to check that. 9. Re: Pluggable dependency resolverAles Justin Jan 22, 2010 7:55 AM (in response to Kabir Khan) I had something simpler in mind, not "indexing" per DependencyItem type. Something in the lines of: (a) install/move context (b) find it's dependencies (c) for each dependency do (a) This way we wouldn't always check all contexts, just the ones that actually can be moved. 10. Re: Pluggable dependency resolverKabir Khan Jan 22, 2010 8:12 AM (in response to Ales Justin) alesj wrote: I had something simpler in mind, not "indexing" per DependencyItem type. Something in the lines of: (a) install/move context (b) find it's dependencies Here, I think you mean the dependsOnMe dependencies, I'll look into that alesj wrote: This way we wouldn't always check all contexts, just the ones that actually can be moved. Just to be clear, we don't check all the contexts the way I have set it up either 11. Re: Pluggable dependency resolverKabir Khan Jan 22, 2010 8:21 AM (in response to Kabir Khan) I don't think dependsOnMe will work.. Have I got the wrong idea/am I missing something? 12. Re: Pluggable dependency resolverAles Justin Jan 22, 2010 8:46 AM (in response to Kabir Khan). Ah, yes, you're right. DependsOnMe is not set until you resolve it from the "other" side. So, I guess what you're doing is OK, as there is no other way as to go per dependency type, and try to figure out what is "dependsOnMe" from the dependency item. 13. Re: Pluggable dependency resolverKabir Khan Jan 22, 2010 10:50 AM (in response to Ales Justin) I have added some simple scoping handling, which brings KernelAllTestSuite down to 11 errors and 24 failures. Adding simple callback item handling further brings this down to 11 errors and 17 failures. 14. Re: Pluggable dependency resolverKabir Khan Jan 25, 2010 6:56 AM (in response to Kabir Khan) I've further extracted how the on demand dependencies are handled in the legacy and new model, which brings the total errors in KernelAllTestSuite down to 10. These are in: - ScopingAliasTestCase - ScopingAliasAPITestCase - ScopingOverrideTestCase - ScopingDependencyTestCase By the way, if anybody wants to try this out, you switch the dependency resolvers in DependencyResolverAbstractFactory.java. Currently it looks like this: public class DependencyResolverAbstractFactory { private static final DependencyResolverAbstractFactory INSTANCE = new DependencyResolverAbstractFactory(); private static final DependencyResolverFactory factory; static { //TODO configure with system properties // String name = "org.jboss.dependency.plugins.resolver.standard.StandardDependencyResolverFactory"; //1 // String name = "org.jboss.dependency.plugins.resolver.indexing.IndexingDependencyResolverFactory"; //2 String name = "org.jboss.kernel.plugins.resolver.indexing.IndexingKernelDependencyResolverFactory"; //3 - 1 is the legacy resolver and all tests pass with that - 2 is the new resolver used for the dependency project - 3 is the new resolver used for the kernel project
https://community.jboss.org/thread/146838
CC-MAIN-2015-22
refinedweb
2,614
52.7
Label text not displayed until end of Button action With the UI Designer's help, I have a simple button and also a label (Record_label). In the button's Action code: ... view["Record_label"].text = "START" # write to the label time.sleep (2) # delay for a bit view["Record_label"].text = "END" # write to the label ... The problem that I'm having is that I only ever see the text "END" in the label. However, if I put in a line of code between "START" and "END" that causes an error, the script halts and then I do see the "START" text. So, I know that the "START" text is getting into the label, but the label's text field is only displaying the last modification (i.e., when the button's action terminates). Does anyone know what I can do to have the label's text field immediately show what has been written to it? Thanks much, Bob The issue here is that by default all UI action functions and delegate methods are called in the main UI thread. This means that when you say time.sleep(2)in an action function, that gets called in the main UI thread, which makes the entire app hang for two seconds. To fix this, you can add the ui.in_backgrounddecorator to your action function, like this: import ui @ui.in_background def myaction(sender): sender.text = "Hello!" time.sleep(2) sender.text = "Bye!" ui.load_view().present() The in_backgrounddecorator makes the function run on the Python thread instead of the main UI thread, which means that Python waits for two seconds while the UI thread is still running and can update the label text. When I add the decorator in front of any button's 'def' then that button becomes inactive. I must be doing something wrong. Also, you used thread.sleep() in your code. I can't find any documentation on that. Thanks for your help on this. Bob Use ui.delay. import ui from functools import partial def delay_action(sender): sender.title = 'bye' def button_tapped(sender): sender.title = 'Hello' ui.delay(partial(delay_action, sender), 3) view = ui.View(frame=(0,0,200,200)) # [1] view.name = 'Demo' # [2] view.background_color = 'white' # [3] button = ui.Button(title='Tap me!') # [4] button.center = (view.width * 0.5, view.height * 0.5) # [5] button.flex = 'LRTB' # [6] button.action = button_tapped # [7] view.add_subview(button) # [8] view.present('sheet') # [9] Likely @dgelessus meant time.sleep, not thread.sleep. Either that, or ui.delay are good methods, either approach will work, although the @ui.in_background method only works if you have one in_background method running at a time, since these are placed in a queue. So if you had two buttons using this approach, and pressed them at the same time, the first would run, then the second would not start until the first completes. A third approach is to define a threaded and decorate your action thusly @run_async def myaction(sender): your code here Yes, I meant time.sleepof course. In Java it's called Thread.sleepand I was talking about threads so much, so I got confused. Yeah... And maybe you did not get enough sleep. ;-) We should probably stop derailing this thread now... :P I really appreciate all of the tips. I'm a hardware engineer and am learning a lot about programming thanks to people like y'all. What I ended up doing was just to have the Button action routine set a semaphore that the main routine acts on. This works perfectly and is probably the right thing to do anyway so that main is not bogged down by delays in any of the background tasks. Bob My approach would follow @dgelessus advise... import time, ui @ui.in_background def myaction(sender): sender.superview["Record_label"].text = "START" # write to the label time.sleep(2) # delay for a bit sender.superview["Record_label"].text = "END" # write to the label def make_button(title='Click me'): button = ui.Button(name=title, title=title) button.action = myaction return button def make_label(text='Who cuts your hair?'): label = ui.Label(name='Record_label', frame=(50, 50, 200, 32)) label.text = text label.text_color = 'blue' return label if __name__ == '__main__': view = ui.View() view.add_subview(makes_button()) view.add_subview(make_label()) view.present() view['Click me'].center = view.center Although it does not solve the two button problem that @JonB raises, ui.in_backgrounddoes run myaction in a way that does not degrade the responsiveness of your UI. See:
https://forum.omz-software.com/topic/3495/label-text-not-displayed-until-end-of-button-action
CC-MAIN-2017-17
refinedweb
744
69.79
ncl_ardbpa - Man Page Produces a plot showing all of the edge segments in an area map that have a specified group identifier IGRP; if IGRP is less than or equal to zero, all groups are included. Such plots allow one to debug problems with an area map. Synopsis CALL ARDBPA (MAP,IGRP,LABEL) C-Binding Synopsis #include <ncarg/ncargC.h> void c_ardbpa (int *map, int igrp, char *label) Description - MAP (an input/output array of type INTEGER) - An array containing an area map that has at least been initialized by a call to ARINAM and to which edges will probably have been added by calls to AREDAM. Note: As part of initializing the area map, ARINAM stores the dimension of MAP in MAP(1); therefore, the dimension does not have to be given as an argument in calls to ARDBPA.) - IGRP (an input expression of type INTEGER) - The group identifier of the group that you want to examine. If IGRP is less than or equal to zero, edges from all groups will be shown. - LABEL (an input constant or variable of type CHARACTER) - The label you want put on the plot. C-Binding Description The C-binding argument descriptions are the same as the FORTRAN argument descriptions. Usage When ARDBPA is called, it draws the requested picture and then calls FRAME to advance to a new frame. By default, each edge segment in the plot appears in one of four different colors, depending on whether the area identifiers to the left and right are less than or equal to zero or greater than zero, as follows: In some cases you may notice gray lines in your plot. This means that the same edge occurs in more than one group. In all but one of those groups, Areas negates the group identifier for the edge in the area map. This allows Areas to include the edge when it is looking at a particular group (as in ARPRAM), but omit it when it is looking at the union of all the groups (as in ARSCAM). Color indices DC+1 through DC+5 are used for the required colors. The default value of DC is 100, so, by default, ARDBPA redefines color indices 101 through 105. If this would result in colors that you have defined being redefined, you should change the value of DC to something else. Nominally, each edge segment is shown with an arrowhead, indicating the order in which the points defining the edge segment occur in the area map and therefore which side of the edge segment is to the left and which side is to the right. In regions where putting an arrowhead on each edge segment would result in too much clutter, some of them may be omitted. The left and right area identifiers for each edge segment are written in the appropriate positions relative to the edge segment. Also, if IGRP is less than or equal to zero, the group identifier for each edge segment is written on the segment itself. These identifiers are intentionally written using very small characters; the idea is that you can look at the whole plot to get some idea of possible problem regions; when such a region is found, you can enlarge it, using the "zoom" capability of "idt", for a closer look; at that point, the area identifiers become readable. If ARDBPA is used for a complicated area map, the amount of output can be very large. Examples Use the ncargex command to see the following relevant examples: arex01, cardb2. Access To use ARDBPA or c_ardbpa, load the NCAR Graphics libraries ncarg, ncarg_gks, and ncarg_c, preferably in that order. See Also Online: areas, areas_params, ardrln, aredam,.
https://www.mankier.com/3/ncl_ardbpa
CC-MAIN-2021-21
refinedweb
617
64.75
Outline - Introduction - Assignment and underscore - Variable name gotchas - Vectors - Sequences - Types - Boolean operators - Lists - Matrices - Missing values and NaNs - Functions - Scope - Misc. - Other resources Introduction I have written software professionally in perhaps a dozen programming languages, and the hardest language for me to learn has been R. The language is actually fairly simple, but it is unconventional. These notes are intended to make the language easier to learn for someone used to more commonly used languages such as C++, Java, Perl, etc. R is more than a programming language. It is an interactive environment for doing statistics. I find it more helpful to think of R as having a programming language than being a programming language. The R language is the scripting language for the R environment, just as VBA is the scripting language for Microsoft Excel. Some of the more unusual features of the R language begin to make sense when viewed from this perspective. Assignment and underscore The assignment operator in R is <- as in e <- m*c^2. It is also possible, though uncommon, to reverse the arrow and put the receiving variable on the right, as in m*c^2 -> e. It is sometimes possible to use = for assignment, though I don’t understand when this is and is not allowed. Most people avoid the issue by always using the arrow. However, when supplying default function arguments or calling functions with named arguments, you must use the = operator and cannot use the arrow. At some time in the past R, or its ancestor S, used underscore as assignment. This meant that the C convention of using underscores as separators in multi-word variable names was not only disallowed but produced strange side effects. For example, first_name would not be a single variable but rather the instruction to assign the value of name to the variable first! S-PLUS still follows this use of the underscore. However, R allows underscore as a variable character and not as an assignment operator. Variable name gotchas Because the underscore was not allowed as a variable character, the convention arose to use dot as a name separator. Unlike its use in many object oriented languages, the dot character in R has no special significance, with two exceptions. First, the ls() function in R lists active variables much as the ls Unix shell command lists directory contents. As the ls shell command does not list files that begin with a dot, neither does the ls() function in R function show variables that begin with dot by default. Second, ... is used to indicate a variable number of function arguments. R uses $ in a manner analogous to the way other languages use dot. R has several one-letter reserved words: c, q, s, t, C, D, F, I, and T. (Actually, these are not reserved, but it’s best to think of them as reserved. For example, c is a built-in function for creating vectors, though you could also create a variable named c. Worse, T and F are not synonyms for TRUE and FALSE but variables that have the expected values by default. So someone could include the code T <- FALSE; F <- TRUE and reverse their meanings!) Vectors The primary data type in R is the vector. Before describing how vectors work in R, it is helpful to distinguish two ideas of vectors in order to set the correct expectations. The first idea of a vector is what I will call a container vector. This is an ordered collection of numbers with no other structure, such as the vector<> container in C++. The length of a vector is the number of elements in the container. Operations are applied componentwise. For example, given two vectors x and y of equal length, x*y would be the vector whose nth component is the product of the nth components of x and y. Also, log(x) would be the vector whose nth component is the logarithm of the nth component of x. The other idea of a vector is a mathematical vector, an element of a vector space. In this context “length” means geometrical length determined by an inner product; the number of components is called “dimension.” In general, operations are not applied componentwise. The expression x*y is a single number, the inner product of the vectors. The expression log(x) is meaningless. A vector in R is a container vector, a statistician’s collection of data, not a mathematical vector. The R language is designed around the assumption that a vector is an ordered set of measurements rather than a geometrical position or a physical state. (R supports mathematical vector operations, but they are secondary in the design of the language.) This helps explain, for example, R’s otherwise inexplicable vector recycling feature. Adding a vector of length 22 and a vector of length 45 in most languages would raise an exception; the language designers would assume the programmer has made an error and the program is now in an undefined state. However, R allows adding two vectors regardless of their relative lengths. The elements of the shorter summand are recycled as often as necessary to create a vector the length of the longer summand. This is not attempting to add physical vectors that are incompatible for addition, but rather a syntactic convenience for manipulating sets of data. (R does issue a warning when adding vectors of different lengths and the length of the longer vector is not an integer multiple of the length of the shorter vector. So, for example, adding vectors of lengths 3 and 7 would cause a warning, but adding vectors of length 3 and 6 would not.) The R language has no provision for scalars, nothing like a double in C-family languages. The only way to represent a single number in a variable is to use a vector of length one. And while it is possible to iterate through vectors as one might do in a for loop in C, it is usually clearer and more efficient in R to operate on vectors as a whole. Vectors are created using the c function. For example, p <- c(2,3,5,7) sets p to the vector containing the first four prime numbers. Vectors in R are indexed starting with 1 and matrices in are stored in column-major order. In both of these ways R resembles FORTRAN. Elements of a vector can be accessed using []. So in the above example, p[3] is 5. Vectors automatically expand when assigning to an index past the end of the vector, as in Perl. Negative indices are legal, but they have a very different meaning than in some other languages. If x is an array in Python or Perl, x[-n] returns the nth element from the end of the vector. In R, x[-n] returns a copy of x with the nth element removed. Boolean values can also be used as indices, and they behave differently than integers. See Five kinds of subscripts in R. Sequences The expression seq(a, b, n) creates a closed interval from a to b in steps of size n. For example, seq(1, 10, 3) returns the vector containing 1, 4, 7, and 10. This is similar to range(a, b, n) in Python, except Python uses half-open intervals and so the 10 would not be included in this example. The step size argument n defaults to 1 in both R and Python. The notation a:b is an abbreviation for seq(a, b, 1). The notation seq(a, b, length=n) is a variation that will set the step size to (b-a)/(n-1) so that the sequence has n points. Types The type of a vector is the type of the elements it contains and must be one of the following: logical, integer, double, complex, character, or raw. All elements of a vector must have the same underlying type. This restriction does not apply to lists. Type conversion functions have the naming convention as.xxx for the function converts its argument to type xxx. For example, as.integer(3.2) returns the integer 3, and as.character(3.2) returns the string “3.2”. Boolean operators You can input T or TRUE for true values and F or FALSE for false values. The operators & and | apply element-wise on vectors. The operators && and || are often used in conditional statements and use lazy evaluation as in C: the operators will not evaluate their second argument if the return value is determined by the first argument. Lists Lists are like vectors, except elements need not all have the same type. For example, the first element of a list could be an integer and the second element be a string or a vector of Boolean values. Lists are created using the list function. Elements can be access by position using [[]]. Named elements may be accessed either by position or by name. Named elements of lists act like C structs, except a dollar sign rather than a dot is used to access elements. For example, consider, a <- list(name="Joe", 4, foo=c(3,8,9)) Now a[[1]] and a$name both equal the string “Joe”. If you attempt to access a non-existent element of a list, say a[[4]] above, you will get an error. However, you can assign to a non-existent element of a list, thus extending the list. If the index you assign to is more than one past the end of the list, intermediate elements are created and assigned NULL values. You can also assign to non-existent named fields, such as saying a$baz = TRUE. Matrices In a sense, R does not support matrices, only vectors. But you can change the dimension of a vector, essentially making it a matrix. For example, m <- array( c(1,2,3,4,5,6), dim=c(2,3) ) creates a matrix m. However, it may come as a surprise that the first row of m has elements 1, 3, and 5. This is because by default, R fills matrices by column, like FORTRAN. To fill m by row, add the argument by.row = TRUE to the call to the array function. Missing values and NaNs As in other programming languages, the result of an operation on numbers may return NaN, the symbol for “not a number.” For example, an operation might overflow the finite range of a machine number, or a program might request an undefined operation, such as dividing by zero. R also has a different type of non-number, NA for “not applicable.” NA is used to indicate missing data, and is unfortunately fairly common in data sets. NA in R is similar to NULL in SQL or nullable types in C#. However, one must be more careful about NA values in R than about nulls in SQL or C#. The designer of database or the author of a piece of C# code specifies which values are nullable and can avoid the issue by simply not allowing such values. The author of an R function, however, has no control over the data his function will receive because NA is a legal value inside an R vector. There is no way to specify that a function takes only vectors with non-null components. You must handle NA values, even if you handle them by returning an error. The function is.nan will return TRUE for those components of its argument that are NaN. The function is.na will return true for those components that are NA or NaN. Comments begin with # and continue to the end of the line, as in Python or Perl. Functions The function definition syntax of R is similar to that of JavaScript. For example: f <- function(a, b) { return (a+b) } The function function returns a function, which is usually assigned to a variable, f in this case, but need not be. You may use the function statement to create an anonymous function (lambda expression). Note that return is a function; its argument must be contained in parentheses, unlike C where parentheses are optional. The use of return is optional; otherwise the value of the last line executed in a function is its return value. Default values are defined similarly to C++. In the following example, b is set to 10 by default. f <- function(a, b=10) { return (a+b) } So f(5, 1) would return 6, and f(5) would return 15. R allows more sophisticated default values than does C++. A default value in R need not be a static type but could, for example, be a function of other arguments. C++ requires that if an argument has a default value then so do all values to the right. This is not the case in R, though it is still a good idea. The function definition f <- function(a=10, b) { return (a+b) } is legal, but calling f(5) would cause an error. The argument a would be assigned 5, but no value would be assigned to b. The reason such a function definition is not illegal is that one could still call the function with one named argument. For example, f(b=2) would return 12. Function arguments are passed by value. The most common mechanism for passing variables by reference is to use non-local variables. (Not necessarily global variables, but variables in the calling routine’s scope.) A safer alternative is to explicitly pass in all needed values and return a list as output. Scope R uses lexical scoping while S-PLUS uses static scope. The difference can be subtle, particularly when using closures. Since variables cannot be declared — they pop into existence on first assignment — it is not always easy to determine the scope of a variable. You cannot tell just by looking at the source code of a function whether a variable is local to that function. Misc. Here are a few miscellaneous facts about R that may be useful. help(fctn)displays help on any function fctn, as in Python. - To invoke complex arithmetic, add 0ito a number. For example, sqrt(-1)returns NaN, but sqrt(-1 + 0i)returns 0 + 1i. sessionInfo()prints the R version, OS, packages loaded, etc. ls()shows which objects are defined. rm(list=ls())clears all defined objects. dev.new()opens a new plotting window without overwriting the previous one. - The function sort()does not change its argument. - Distribution function prefixes d, p, q, rstand for density (PDF), probability (CDF), quantile (CDF-1), and random sample. For example, dnormis the density function of a normal random variable and rnormgenerates a sample from a normal random variable. The corresponding functions for a uniform random variable are dunifand runif.
https://www.johndcook.com/blog/r_language_for_programmers/
CC-MAIN-2021-49
refinedweb
2,470
64.3
In the month of January, I offered exclusive training to my newsletter subscribers. The training was extremely unique and was available for a limited time. Quite a lot of newsletter subscribers took advantage of this limited time offer of “SQL Server Performance Tuning Practical Workshop“. If you have yet not signed up with a newsletter which has many such exclusive offer, you can sign up here:. When I decided to offer training, I initially thought I would do every week two trainings. That means I was planning to do a total of 8 training in one month. However, as of today, I have delivered a total of 36 training sessions in January and when I write this there are 10 confirmed training in February. I am indeed overwhelmed with the love and support of all of you. Hence, I decided to write the entire story over here in this blog post. What Attendees are Saying- Here is what some of the attendees say about this training- “This training is not for the fainthearted, it is very fast paced. You should only sign up for this training, if you are willing to challenge your old thought process for performance tuning.” ~ Mattew G. “We will never look at the indexes the same way after this training”. ~ Leah E. “This is single no-nonsense training, super energy and amazing storyline.” ~ Kristofer M D “We built 10 point action plan from this training and we have just completed 6th action item and our performance is roof top.” ~ Karim A. “No BS, Pure Performance. Extremely Unique Experience!” ~ Murudeshwara NSV The First Week The first week when I offered this workshop, it was a bit slow week as not many had bought the idea that one can learn Performance Tuning in just 3 to 4 hours which can help you fix over 80% of performance issues. Many of us still believe it is a good idea to pay more and take longer courses which can go up to 5-7 days (8 hours every day). Honestly, the world has changed, we really do not have time to take mini – vacations from our day job and spend over 40-60 hours of learning theories, which we can hardly put into action in the real world. First Trainings However, quite a few organizations who have worked with me before jumped immediately to reserve training hours. If you have worked with me before you know that I talk only practical solutions and never give long theoretical answers (unless asked to discuss in detail) which eventually confuses many. After the first week, the word of mouth spread for this training and I saw ever increasing demand for this training. Word of Mouth After the word of mouth spread for the practicality of this training, I received an unprecedented amount of request for this training in the second week. Today, when I am writing this email. I have already done 38 Practical Workshop for Performance Tuning for a total of 26 different organizations. Silly Typo and Confusing Words This training was exclusively available to subscribers of this newsletter and was not available outside. I initially wanted to only do training in the month of January, however, when I sent email initially, I had made a silly typo in it. What I wanted to say – “The training is only available during the month of January.” What I had said – “The training is only available to register during the month of January.” Well, if you read it carefully, you will understand that both the statement has a different meaning. When I started to get requests from users to register for the training in February and March, I realized that what I wanted to say was the training has to be completed in the month of January but from what I had said it meant, someone can register in for future date training in January. I immediately stopped sending emails and corrected my mistakes in all the unsent emails. Well, it was too late for many emails. Finally – I Kept My Words Well, the training is very popular and one of the organizers liked it so much that they wanted me to deliver it to their global audience multiple times during different Timezone. The training is very sharp and effective, users can immediately start taking advantage of many of the different tricks immediately. I think I finally gave into the request and opened up the training for anyone who registers in the month of January. My Confession and FAQ So essentially, if you initiated request in January, I am open to extend the actual delivery in February. However, no later than February 28th. Here are top five frequently asked training about the training: Q1) How is this training delivered and how long it is? A1) The training is delivered via gotomeeting and the typical duration is between 3 to 4 hours. Q2) How do I register for this training? A2) There is no online link for the training. You just have to reply to this email with answer to following four questions. 1) Name of your organizations 2) Available time slot of 4 hours (date and time with Timezone) 3) Number of attendees 4) Number of SQL Server Instances in your organizations In response to the above information, I will send you my fees and availability. Once we agree on the same, I will send GoToMeeting Link for meeting and PayPal Link for payment Q3) What is covered in the training? A3) In this session we learn about - Index Strategies - Server Configuration for Performance - Instance Configuration for Performance - Wait Stats Analysis - DBCC Best Practices After the training, once you implement all the learning points in the action, I am EXTREMELY CONFIDENT that you will get amazing performance from your existing system. It will be like adding six months of additional lifetime to existing infrastructure. Q4) Is it 1:1 training or a public class training? A4) This is 1:1 personalized training to you or your team. It is not a public class or public webinar where there will be many different individuals. My experience says, public classes are way less efficient than customized training build for your server environment. Q5) Do you really give all the scripts and associated material covered during the session? A5) Absolutely YES. Before we are done with the call, I send you zip file which contains all the scripts which we have learned in the session along with reference material. Positive Aftermath Since I have started Practical Workshop for Performance Tuning, I am getting lesser request for my most popular service of Index Tuning and Strategy Guidance (99 minutes), I believe this is because after attending this training users are doing it themselves. Though, it has reduced my business by a bit, I am very happy that my training attendees are helping their servers themselves. There is nothing more beautiful than knowing tricks to fix your own server. Free Webinar Now if you have read this blog post so far, you indeed deserve a gift. Click here to watch my free webinar on SQL Server Performance Tuning. This free webinar will give you glimpse how I explain a very high impact performance tuning tricks with simple action words. If you have missed the training, well too bad, but do not miss watching this fast paced 50 minute webinar. Do You Want to Learn? Well, the training was available for a limited time and I no longer do the training. However, if you are really really keen on learning SQL Server Performance Tuning, do reach out to me at pinal@sqlauthority.com from your work email address with following information and I will immediately revert it back with further instructions. 1) Name of your organizations 2) Available time slot of 4 hours (date and time with Timezone) 3) Number of attendees 4) Number of SQL Server Instances in your organizations Please note, you must only contact if you are serious about learning SQL Server Performance Tuning Practical Workshop. Reference: Pinal Dave ()
https://blog.sqlauthority.com/2017/02/01/sql-server-performance-tuning-practical-workshop-notes-thoughts/
CC-MAIN-2017-26
refinedweb
1,342
59.74
49036/please-explain-lambda-function-actually-nameless-function This is done because these functions are nameless and therefore require some name to be called. But, this fact might seem confusing as to why use such nameless functions when you need to actually assign some other name to call them? And of course, after assigning the name a to my function, it doesn't remain nameless anymore! Right? It's a legitimate question, but the point is, this is not the right way of using these anonymous functions. Anonymous functions are best used within other higher-order functions that either make use of some function as an argument or, return a function as the output. For example: def new_func(x): return(lambda y: x+y) t=new_func(3) u=new_func(2) print(t(3)) print(u(3)) OUTPUT: 6 5 As you can see, in the above example, the lambda function which is present within new_func is called whenever we make use of new_func(). Each time, we can pass separate values to the arguments. They are usually used along with filter(), map() and reduce() functions since these functions take other functions as parameters. Suppose your file name is demo.py and ...READ MORE Hey, @Subi, Regarding your query, you can go ...READ MORE Hi, You can use this piece of code, ...READ MORE Hello @Roshni, Python has a built-in module called ...READ MORE Python lambda functions can be used to ...READ MORE The main purpose of anonymous functions come ...READ MORE The main purpose of anonymous functions come ...READ MORE Yes you can use lambda inside lambda. ...READ MORE Join() function is used in threading to ...READ MORE To check if a website allows web ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/49036/please-explain-lambda-function-actually-nameless-function
CC-MAIN-2020-45
refinedweb
294
73.88
2018-07-12 00:16:07 8 Comments I own a FontAwesome Pro License and I use the Vue-FontAwesome Component. When I try to import all icons from both the free and Pro repo I get an "Duplicate declaration error ..." and if I change the declaration name it can't be found anymore. import { library } from '@fortawesome/fontawesome-svg-core' import { fab } from '@fortawesome/free-brands-svg-icons' import { fas } from '@fortawesome/pro-solid-svg-icons' import { far } from '@fortawesome/pro-regular-svg-icons' import { fal } from '@fortawesome/pro-light-svg-icons' import { fas } from '@fortawesome/free-solid-svg-icons' import { far } from '@fortawesome/free-regular-svg-icons' library.add(fab) library.add(fas) library.add(far) library.add(fal) How do I import all icons from Free and Pro? Related Questions Sponsored Content 5 Answered Questions [SOLVED] Using FontAwesome with Sass - 2013-09-02 09:59:08 - ithil - 47113 View - 24 Score - 5 Answer - Tags: sass compass-sass font-awesome 2 Answered Questions [SOLVED] Import all icons from Fontawesome - 2018-04-17 15:30:45 - Vladimir Humeniuk - 1564 View - 4 Score - 2 Answer - Tags: angular font-awesome font-awesome-5 angular-fontawesome 1 Answered Questions [SOLVED] fontawesome error "Could not find one or more icon" - 2018-07-06 09:30:18 - Jiu - 1862 View - 7 Score - 1 Answer - Tags: vue.js font-awesome vuepress 1 Answered Questions [SOLVED] Fontawesome 5 in Android, 3 files - 2018-05-29 16:11:43 - WinterChilly - 230 View - 1 Score - 1 Answer - Tags: android kotlin textview font-awesome font-awesome-5 3 Answered Questions [SOLVED] Font Awesome 5 icons not working with React ("Could not find icon" error) - 2018-04-30 19:51:05 - dannymcgee - 2659 View - 5 Score - 3 Answer - Tags: javascript reactjs font-awesome 1 Answered Questions [SOLVED] Vue.js how to expose component data properties for use in third party script? - 2017-10-09 09:11:38 - Stephan-v - 412 View - 3 Score - 1 Answer - Tags: javascript vue.js vuejs2 vue-component 1 Answered Questions [SOLVED] how to avoid duplicate import and component declarations in VueJS 2 Answered Questions [SOLVED] Use HTML element instead of icon for map marker with gmap3? - 2013-11-17 20:50:46 - Scott Beeson - 1327 View - 1 Score - 2 Answer - Tags: javascript google-maps font-awesome jquery-gmap3 glyphicons 1 Answered Questions [SOLVED] Unable to create proper size and aligned icons from fontcustom when manually creating SVG files from font awesome SVG file - 2013-01-18 00:04:56 - Destiny In Ur Hands - 894 View - 0 Score - 1 Answer - Tags: twitter-bootstrap svg custom-font font-awesome @Coreus 2019-01-30 12:11:55 You're in effect importing multiple icon packs into to the same var for both farand fas, hence the error "Duplicate declaration". As stated in comments, if you have FontAwesome Pro, that includes everything in FontAwesome Free. Import the pro-packages you need, and forget about the free edition. That being said, importing the entire thing isn't ideal. If you're using a bundle manager with tree shaking (i.e webpack), it will save your application's weight impact tenfold. You rarely need all of the 5k icons. Continuing down that road, that is; not importing the entire package: You can import different icon versions by importing and casting them. Like so: More on all of this in the official docs for FA-Pro.
https://tutel.me/c/programming/questions/51295730/vuefontawesome+how+to+import+all+free+and+pro+icons+duplicate+declaration+error
CC-MAIN-2019-09
refinedweb
564
55.47
Java, Unicode, and the Mysterious Compile Error Unicode is a text encoding standard which supports a broad range of characters and symbols. Although the latest version of the standard is 9.0, JDK 8 supports Unicode 6.2 and JDK 9 is expected to be released with support for Unicode 8.0. Java allows you to insert any supported Unicode characters with Unicode escapes. These are essentially a sequence of hexadecimal digits representing a code point. In this post I’m going to cover how to use Unicode escapes in Java and how to avoid unexplainable compiler errors caused by Unicode escape misuse. What are Unicode Escapes? Let’s start from the beginning. Unicode escapes are used to represent Unicode symbols with only ASCII characters. This will come in handy when you need to insert a character that cannot be represented in the source file’s character set. According to section 3.3 of the Java Language Specification (JLS) a unicode escape consists of a backslash character (\) followed by one or more ‘u’ characters and four hexadecimal digits. UnicodeEscape: \ UnicodeMarker HexDigit HexDigit HexDigit HexDigit UnicodeMarker: u UnicodeMarker u So for example \u000A will be treated as a line feed. Example Usage The following is a piece of Java code containing a Unicode escape. public class HelloUnicode { public static void main(String[] args) { // \u0055 is a Unicode escape for the capital U character (U) System.out.println("Hello \u0055nicode".length()); } } Take a moment to think about what will be printed out. If you want, copy and paste the code to a new file, compile and run it. At first glance it looks like the program prints out 18. There’s 18 characters between the double quotes, so the length of the string should be 18. But if you run the program, the output is 13. As the comment suggests, the Unicode escape will be replaced with a single character. Equipped with the knowledge that Unicode escapes are replaced with their respective Unicode characters, let’s look at the following example. public class NewLine { public static void main(String[] args) { // \u000A is a unicode escape for the line feed (LF) // \u0055 is a Unicode escape for the capital U character (U) System.out.println("Hello \u0055nicode".length()); } } Can you guess what will be printed out now? The answer should be the same as before, right? I’m sure some of you might suspect that this is a trick question and as a matter of fact, it is. This example will not compile at all. $ javac NewLine.java:5: error: ')' expected System.out.println("Hello \u0055nicode".length()); ^ 6 errors What!? So many errors! My IDE doesn’t show any squiggly red lines and I can’t seem to find any syntax errors myself. Error on line 3? But that’s a comment. What is going on? What caused the error? To get a better understanding of what is going on, we need to look at section 3.2 of the Java Language Specification – Lexical Translations. I cannot speak for all compilers that have ever existed but usually the first job of a compiler is to take the source code of a program, treat it as a sequence of characters and produce a sequence of tokens. A token is something that has a meaning in the context of the language. For example in Java it can be a reserved word ( public, class or interface), an operator ( +, >>) or a literal (a notation for representing a fixed value). The process of generating tokens from a sequence of characters is called lexical analysis (or lexical translation as it is called in the Oracle docs) and the program that performs that is called a lexer or a tokenizer. The Java Language Specification says that lexical translation is performed in the following 3 steps, where each step is applied to the result of the previous step: - Translation of Unicode escapes. - Divide stream of input characters into lines by recognizing line terminators (LF, CR or CR LF). - Discard whitespace and comments and tokenize the result from the previous step. As you can see, the very first step processes Unicode escapes. This is done before the compiler has had the chance to separate the source code into tokens. Broadly speaking, this is like applying a search and replace function on the source code, replacing all well formed Unicode escapes with their respective Unicode characters, and then letting the compiler work on the rest of the code. Keep in mind, when Unicode escapes are being processed, the compiler does not differentiate comments from actual code. It can only see a sequence of characters. And this explains the erroneous code you saw in the introduction of this post. Let’s have a look at it again. //This is the original source code public class NewLine { public static void main(String[] args) { // \u000A is a unicode escape for the line feed (LF) // \u0055 is a Unicode escape for the capital U character (U) System.out.println("Hello \u0055nicode".length()); } } //This is what it looks like after Unicode escapes have been processed public class NewLine { public static void main(String[] args) { // is a unicode escape for the line feed (LF) // U is a Unicode escape for the capital U character (U) System.out.println("Hello Unicode".length()); } } The Unicode escape representing the line feed character is replaced with a line feed and now part of the comment is on a new line. Unfortunately the new line does not start with a double-slash ( //) and the rest of the line is not valid Java code. Hence the confusing compiler error shown previously. Quick Detour: native2ascii You can play around with Unicode conversion yourself. Up to Java 8 the JRE is bundled with a tool called native2ascii, which converts a file with characters in any supported character encoding to one with ASCII and/or Unicode escapes, or visa versa. $ native2ascii -reverse NewLine.java public class NewLine { public static void main(String[] args) { // is a unicode escape for the line feed (LF) // U is a Unicode escape for the capital U character (U) System.out.println("Hello Unicode".length()); } } What about Java 9 (and later)? Prior to it, Java property files use the ISO-8859-1 character set by default. Characters that cannot be represented in ISO-8859-1 are converted to Unicode escapes using the native2ascii tool. But JEP 226 changes that and property files can now be encoded in UTF-8, which means that the native2ascii tool is not needed anymore. In this post, native2ascii is used to demonstrate what the Java source file would look like if Unicode escapes were replaced with actual Unicode characters. For Java 9 users, I recommend to use uni2ascii, which can achieve the same result. # uni2ascii package consists of two programs: uni2ascii and ascii2uni. # Commandline argument -a U specifies the format of Unicode escapes # which matches the one used in Java ascii2uni -a U NewLine.java Hiding Code in Comments If Unicode escapes are processed before everything else, then can I cleverly hide code inside comments which will later be executed? The somewhat scary answer to this question is yes. Looking back at the previous example, we saw that a line feed was inserted and the rest of the comment was on the next line, resulting in invalid Java code. But we could have written the following public class HidingCode { public static void main(String[] args) { //\u000A System.out.println("This is a comment"); System.out.println("Hello world"); } } If the Unicode escape is replaced with a line feed, then it should be clear there’s actually two print statements executed. $ native2ascii -reverse HidingCode.java public class HidingCode { public static void main(String[] args) { // System.out.println("This is a comment"); System.out.println("Hello world"); } } $ javac HidingCode.java $ java HidingCode This is a comment Hello world Why does Java allow that? This all seems weird, right? Why is Java designed like that? Is it a bug that was accidentally introduced and never fixed because it would break something else? To find an answer to that question we need to look at section 3.1 and section 3.3 of the Java Language Specification (JLS). From section 3.1: The Java programming language represents text in sequences of 16-bit code units, using the UTF-16 encoding. From section 3.3: The Java programming language specifies a standard way of transforming a program written in Unicode into ASCII that changes a program into a form that can be processed by ASCII-based tools. The transformation involves converting any Unicode escapes in the source text of the program to ASCII by adding an extra u – for example, \uxxxx becomes \uuxxxx – while simultaneously converting non-ASCII characters in the source text to Unicode escapes containing a single u each. Unicode escapes were designed to ensure compatibility with a wide variety of character sets. Think of the following scenario. You receive a piece of code with an encoding your text editor does not understand (i.e. the code includes characters not available in the encoding you use). This can be solved by replacing all unknown characters with Unicode escapes. As ASCII is the lowest common denominator of character sets, it is always possible to represent Java code in any encoding by replacing characters that are not supported by the target encoding with Unicode escapes. Today Unicode is fairly common and this should not be an issue, but I guess back in the early days this was useful. The transformed version is equal to the initial version and the compiler treats them as the same. As this process is reversible, the compiler can go back to the initial version by replacing Unicode escapes with respective Unicode characters. From section 3.3 This transformed version is equally acceptable to a Java compiler and represents the exact same program. The exact Unicode source can later be restored from this ASCII form by converting each [Unicode] escape sequence where multiple u’s are present to a sequence of Unicode characters with one fewer u, while simultaneously converting each [Unicode] escape sequence with a single u to the corresponding single Unicode character. Prefer Escape Sequences Because Unicode escapes are processed before everything else in the compilation process, they can create a considerable amount of confusion. Therefore it is better to avoid them if possible. Instead prefer escape sequences, for example \n for line feeds or \” for double quotes, in string or character literals. There’s no need to use Unicode escapes for ASCII characters. Unicode Escapes Have to Be Well Formed I mentioned previously that only well formed Unicode escapes are replaced with Unicode characters during the compilation process. You will get an error if there’s an ill-formed Unicode escape in your code. Have a look at the following example. public class IllFormedUnicodeEscape { public static void main(String[] args) { // user data is read from C:\data\users\profile System.out.println("User data"); } } This seems like an innocent looking piece of code. The comment tries to be helpful and communicate something important to the reader. Unfortunately there’s a Unicode escape lurking in this code which is not well formed. As you know by now, Unicode escapes start with \u and the compiler expects four hexadecimal digits to be followed. When this rule is not met, the compiler will throw an error. Windows path names use backslashes to separate directory names. But if one of those backslashes is followed with the u character, you can run into unexpected situations. The problem in this example is the sequence of characters \users which is in fact an ill-formed Unicode escape. Taking It to the Extreme We have looked at several examples where Unicode escapes can cause harm. Your eye should be trained enough to spot most of them by now. For the next example I’m going to show you a piece of code that I first saw when I read the book Java Puzzlers by Joshua Bloch and Neal Gafter. What? Really? This looks like an entry to a code obfuscation contest. But if you think about it, this seems like it should compile, granted that all the Unicode escapes actually represent characters that make up a valid Java program. We learned that the very first thing the compiler does is look for Unicode escapes and replace them. It does not know anything about the program structure at that point. You can try it yourself. Copy the text into a file called Ugly.java. Then compile and run the program. By the way, there’s no point trying to run it from an IDE (at least IntelliJ IDEA is baffled and is only able to show squiggly red lines). Use command line tools instead. $ javac Ugly.java $ java Ugly Hello world Additionally you can use the native2ascii tool to view what the code looks like if all Unicode escapes have been replaced. $ native2ascii -reverse Ugly.java public class Ugly {public static void main( String[] args){ System.out .println( "Hello w"+ "orld");}} I have only one thing to say. Just because you can doesn’t mean you should. Summary Professionally I have never had the need to insert a Unicode escape. Nowadays Unicode is fairly common and most text editors can display non-ASCII characters. If I find myself in a situation where I need to insert a character that’s not available on my keyboard, I can use methods provided by most operating systems to input them. If possible, avoid Unicode escapes because they create confusion. Prefer escape sequences instead. Learn the basics of programming with the web's most popular language - JavaScript A practical guide to leading radical innovation and growth.
https://www.sitepoint.com/java-unicode-mysterious-compile-error/
CC-MAIN-2021-43
refinedweb
2,286
64.3
Re: ISP's DNS as secondary DNS? - From: "Dmitry Korolyov [MVP]" <d__k@xxxxxxxxxxxxxxxxxxxxxx> - Date: Tue, 7 Feb 2006 12:30:50 +0300 I would never recommend setting up ISP's DNS servers in AD environment. All your AD clients (all computers in either domain) should use DNS servers that are able to resolve names within all your AD domain namespaces. -- Dmitry Korolyov [d__k@xxxxxxxxxxxxxxxxxxxxxx] MVP: Windows Server - Directory Services "ttblum" <toddb@xxxxxxxxxxxxx> wrote in message news:1139261804.298604.179140@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Hi, I have a basic Win2003 active directory domain with all the XP machines pointing to the domain controller for DNS. Would there be a problem with having the ISP's DNS as the secondary DNS for the workstations? The most critical server that is used here is across the internet, so users still need to have internet even if the domain controller goes down. Thanks for your help, Todd Blum MBS/Net Inc. . - References: - ISP's DNS as secondary DNS? - From: ttblum - Prev by Date: Re: Multiple Names Single domain - Next by Date: Why do they use the word "recursion" anyway? - Previous by thread: Re: ISP's DNS as secondary DNS? - Next by thread: Re: ISP's DNS as secondary DNS? - Index(es):
http://www.tech-archive.net/Archive/Windows/microsoft.public.windows.server.dns/2006-02/msg00097.html
crawl-002
refinedweb
204
72.56
Introducing time-machine, a New Python Library for Mocking the Current Time2020-06-03 Whilst writing Speed Up Your Django Tests, I wanted to add a section about mocking the current time. I knew of two libraries for such mocking, but I found it hard to pick one to recommend due to the trade-offs in each. So I delayed adding that section and shaved a rather large yak by writing a third library. This post is my introduction to the problem, the trade-offs with the other libraries, and how my new library, time-machine, tries to solve them. The next version of Speed Up Your Django Tests can now include a section on mocking time. The Problem It’s especially common in web projects to have features that rely on changes to the current date and time. For example, you might have a feature where each customer may only make an order once per day. For testing such features, it’s often necessary to mock the functions that return the current date and time. In Python’s standard library, these live in the datetime and time modules. (Wrappers, such as arrow and Delorean, still use these under the hood.) There are various ways of doing this mocking: it can be done generically with unittest.mock, or in a more targeted fashion with a time-mocking library. Using unittest.mock works, but it’s often inaccurate as each patcher can only mock a single function reference. This inaccuracy is exacerbated when mocking the current time, as there are many different functions that return the current time, in different formats. Due to the way Python’s imports work, it takes a lot of mocks to replace every instance of functions from datetime and time in a code path, and is sometimes impossible. (See: Why Your Mock Doesn’t Work.) I know of two existing Python libraries that have tried to provide a better way to mock the current time: freezegun and libfaketime. Let’s look at them now, before I introduce time-machine. freezegun freezegun is a very popular library for mocking the current time. It has a great, clear API, and “does what it says on the tin.” For example, you can write a time-mocking test like so: import datetime as dt import freezegun @freezegun.freeze_time("1955-11-05 01:22") def test_delorean(): assert dt.date.today().isoformat() == "1955-11-05" The main drawback is its slow implementation. It essentially does a find-and-replace mock of all the places that the relevant functions from the datetime and time modules have been imported. This gets around the problems with using unittest.mock, but it means the time it takes to do the mocking is proportional to the number of loaded modules. In large projects, this can take a second or two, an impractical overhead for each individual test. It’s also not a perfect search, since it searches only module-level imports. Such imports are definitely the most common way projects use date and time functions, but they’re not the only way. freezegun won’t find functions that have been “hidden” inside arbitrary objects, such as class-level attributes. It also can’t affect C extensions that call the standard library functions, including (I believe) Cython-ized Python code. libfaketime python-libfaketime is a much less popular library, but it is much faster. It wraps the LD_PRELOAD library libfaketime, which replaces all the C-level system calls for the current time with its own wrappers. It’s therefore a “perfect” mock, affecting every single point the current time might be fetched from the current process. It also has much the same API: import datetime as dt import libfaketime @libfaketime.fake_time("1955-11-05 01:22") def test_delorean(): assert dt.date.today().isoformat() == "1955-11-05" The approach is much faster since starting the mock only requires changing an environment variable that libfaketime reads. The python-libfaketime README has a benchmark showing it working 300 times faster than freezegun. This benchmark is even favourable to freezegun, since the environment has no extra dependencies, and freezegun’s runtime is proportional to the number of imported modules. I learnt about python-libfaketime at YPlan, where we were first using freezegun. Moving to python-libfaketime took our Django project’s test suite (of several thousand tests) from 5 minutes to 3 minutes. Unfortunately python-libfaketime comes with the limitations of LD_PRELOAD. This is a mechanism to replace system libraries for a program as it loads (explanation). This causes two issues in particular when you use python-libfaketime. First, LD_PRELOAD is only available on Unix platforms, which prevents you from using it on Windows. This can be a blocker for many teams. Second, you have to help manage LD_PRELOAD. You either use python-libfaketime’s reexec_if_needed() function, which restarts (re-execs) your test process while loading, or manually manage the LD_PRELOAD environment variable. Neither is ideal. Re-execing breaks anything that might wrap your test process, such as profilers, debuggers, and IDE test runners. Manually managing the environment variable is a bit of overhead, and must be done for each environment you run your tests in, including each developer’s machine. time-machine My new library, time-machine, is intended to combine the advantages of freezegun and libfaketime. It works without LD_PRELOAD but still mocks the standard library functions everywhere they may be referenced. It does so by modifying the built-in functions at the C level, to point them through wrappers that return different values when mocking. Normally in Python, built-in functions are immutable, but time-machine overcomes this by using C code to replace their function pointers. Again, it has much the same API as freezegun, except from the names: import datetime as dt import time_machine @time_machine.travel("1955-11-05 01:22") def test_delorean(): assert dt.date.today().isoformat() == "1955-11-05" Its weak point is that libraries making their own system calls won’t be mocked. (Cython use of the datetime and time modules should be mocked, although I haven’t tested it yet). However I believe such usage is rare in Python programs - freezegun also shares this weakness, but that hasn’t stopped it becoming popular. If you have time, please try out time-machine in your tests! It’s available now for Python 3.6+. Because of its implementation, it only works with CPython, not PyPy or any other interpreters. It’s my first open source project using a C extension. Let me know how it works, and if you’re switching from freezegun, how much it speeds up your tests. If it is found to work well, it may be possible to merge its technique into freezegun, to share the speed boost without causing churn. Fin May time make you ever stronger, —Adam Working on a Django project? Check out my book Speed Up Your Django Tests which covers loads of best practices so you can write faster, more accurate tests. One summary email a week, no spam, I pinky promise. Related posts: - The Fast Way to Test Django transaction.on_commit() Callbacks - Django's Test Case Classes and a Three Times Speed-Up Tags: django, python
https://adamj.eu/tech/2020/06/03/introducing-time-machine/
CC-MAIN-2021-04
refinedweb
1,202
64
Finding the power of a number using recursion in Python A recursive function is a function that continuously calls itself. Here, in this tutorial, we are seeing how to find the power of a number using a recursive function in Python. How to find the power of a number using recursion in Python The function that we are making is going to take a base number and an exponent as the argument and the function further works as following: - Pass the arguments to the recursive function to find the power of the number. - Give the base condition for the case where we have the exponent argument as 1. - If the exponent is not equal to 1, return the base multiplied by the function with base and exponent minus 1 as parameter. - The function calls itself until the exponent value is 1. - Print the power of the given base number. def power(base,expo): if(expo==1): return(base) if(expo!=1): return(base*power(base,expo-1)) base=5 expo=3 print("Result:",power(base,expo)) base=12 expo=1 print("Result:",power(base,expo)) Output: Result: 125 Result: 12 Here for the first set of inputs, the function runs recursively whereas, in the second set of inputs the base value is 1 and therefore, the first if the condition is satisfied and output comes. Also read: Neon numbers in a range in Python
https://www.codespeedy.com/finding-the-power-of-a-number-using-recursion-in-python/
CC-MAIN-2020-29
refinedweb
234
50.16
From: Peter Dimov (pdimov_at_[hidden]) Date: 2001-08-24 06:41:29 From: <jaakko.jarvi_at_[hidden]> > Dave's previous comments sure influenced in the decision to drop the > subnamespace :): [...] My first reaction is that the compile-time list support should probably be factored out into a submodule. Many of the tuple_* operations are actually list operations; a compile-time list library would be useful for template metaprogramming, although I don't know how this will be affected by the upcoming boost::mpl. > reference_wrapper > ref > cref Of course I think that these should stay in boost::. I've already factored them out in boost/ref.hpp; they are of general utility (not tuple-specific) and are used by Bind as well. > So if tuples go back to a subnamespace, the questions are: > > 1. What is the name of the namespace (tuples or tuple?) A possible alternative is to define a tuple namespace and a nested class template named 'type'; a tuple will then be referred to as tuple::type<X, Y> t; > Tuple has a typedef 'inherited' which gives the underlying cons list > type, e.g.: > tuple<A, B, C>::inherited equals cons<A, cons<B, cons<C,null_type> > > Have you considered tuple<...>::list_type? -- Peter Dimov Multi Media Ltd. Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2001/08/16433.php
CC-MAIN-2021-49
refinedweb
230
58.89
Data.Bson.Mapping Description This module aims to make mapping between algebraic data types and bson documents easy. You can also generate documents with selectFields, which takes a list of functions names that of type a -> b and returns a function of type a -> Document. Example: import Data.Bson.Mapping import Data.Time.Clock import Data.Data (Data, Typeable) data Post = Post { time :: UTCTime , author :: String , content :: String , votes :: Int } deriving (Show, Read, Eq, Ord, Data, Typeable) $(deriveBson ''Post) main :: IO () main = do now <- getCurrentTime let post = Post now "francesco" "lorem ipsum" 5 (fromBson (toBson post) :: IO Post) >>= print print $ toBson post print $ $(selectFields ['time, 'content]) post Synopsis Documentation class (Show a, Eq a, Data a, Typeable a) => Bson a whereSource selectFields :: [Name] -> Q ExpSource Select only certain fields in a document, see the code sample at the top. Please note that there is no checking for the names to be actual fields of the bson document mapped to a datatype, so be careful. getConsDoc :: Name -> Q ExpSource Get a document that identifies the data type - getConsDoc ''Post. This is useful to select all documents mapped to a certain data type. subDocument :: Label -> Document -> DocumentSource Simple function to select fields in a nested document.
http://hackage.haskell.org/package/bson-mapping-0.1.3/docs/Data-Bson-Mapping.html
CC-MAIN-2016-40
refinedweb
204
51.48
Opened 6 years ago Closed 6 years ago #15834 closed defect (invalid) % mode switching on the command line is sometimes broken Description Try typing each of these alone on a line, and you'll agree we have a problem: %maxima %gap %gp %pari %singular %lisp The relevant code is this in misc/sage_extension.py: def register_interface_magics(self): """Register magics for each of the Sage interfaces""" from sage.misc.superseded import deprecation interfaces = [(name, obj) for name, obj in sage.interfaces.all.__dict__.items() if isinstance(obj, sage.interfaces.interface.Interface)] for real_name, obj in interfaces: def tmp(line, name=real_name): self.shell.run_cell('%s.interact()' % name) Change History (5) comment:1 Changed 6 years ago by comment:2 Changed 6 years ago by Everything work fine for me with a 6.2.beta2. Could you please explain what problem you run into ? comment:3 Changed 6 years ago by - Status changed from new to needs_info comment:4 Changed 6 years ago by Hello, could you please be more precise ? As far as I can see, there is no problem here. comment:5 Changed 6 years ago by - Resolution set to invalid - Status changed from needs_info to closed Wow, everything is fixed now (in 6.1.beta)-- before when I was testing this in a recent version of Sage there were numerous issues. Nice work. Closing as invalid. Note: See TracTickets for help on using tickets. Something has been changed in #6288, maybe there was a mistake ?
https://trac.sagemath.org/ticket/15834
CC-MAIN-2020-16
refinedweb
246
64.2
IDLE is Python’s Integrated Development and Learning Environment. IDLE has the following features: tkinterGUI toolkit IDLE has two main window types, the Shell window and the Editor window. It is possible to have multiple editor windows simultaneously. Output windows, such as used for Edit / Find in Files, are a subtype of edit window. They currently have the same top menu as Editor windows but a different default title and context menu. IDLE’s menus dynamically change based on which window is currently selected. Each menu documented below indicates which window type it is associated with. Create a new file editing window. Open an existing file with an Open dialog. Open a list of recent files. Click one to open it. Open an existing module (searches sys.path). Show functions, classes, and methods in the current Editor file in a tree structure. In the shell, open a module first. Show sys.path directories, modules, functions, classes and methods in a tree structure. Save the current window to the associated file, if there is one. Windows that have been changed since being opened or last saved have a * before and after the window title. If there is no associated file, do Save As instead. Save the current window with a Save As dialog. The file saved becomes the new associated file for the window. Save the current window to different file without changing the associated file. Print the current window to the default printer. Close the current window (ask to save if unsaved). Close all windows and quit IDLE (ask to save unsaved windows). Undo the last change to the current window. A maximum of 1000 changes may be undone. Redo the last undone change to the current window. Copy selection into the system-wide clipboard; then delete the selection. Copy selection into the system-wide clipboard. Insert contents of the system-wide clipboard into the current window. The clipboard functions are also available in context menus. Select the entire contents of the current window. Open a search dialog with many options Repeat the last search, if there is one. Open a file search dialog. Put results in a new output window. Open a search-and-replace dialog. Move cursor to the line number requested and make that line visible. Open a scrollable list allowing selection of keywords and attributes. See Completions in the Tips sections below. Expand a prefix you have typed to match a full word in the same window; repeat to get a different expansion. After an unclosed parenthesis for a function, open a small window with function parameter hints. Highlight the surrounding parenthesis. Shift selected lines right by the indent width (default 4 spaces). Shift selected lines left by the indent width (default 4 spaces). Insert ## in front of selected lines. Remove leading # or ## from selected lines. Turn leading stretches of spaces into tabs. (Note: We recommend using 4 space blocks to indent Python code.) Turn all tabs into the correct number of spaces. Open a dialog to switch between indenting with spaces and tabs. Open a dialog to change indent width. The accepted default by the Python community is 4 spaces. Reformat the current blank-line-delimited paragraph in comment block or multiline string or selected line in a string. All lines in the paragraph will be formatted to less than N columns, where N defaults to 72. Remove any space characters after the last non-space character of a line. Scroll the shell window to the last Shell restart. Restart the shell to clean the environment. Stop a running program. Look on the current line. with the cursor, and the line above for a filename and line number. If found, open the file if not already open, and show the line. Use this to view source lines referenced in an exception traceback and lines found by Find in Files. Also available in the context menu of the Shell window and Output windows. When activated, code entered in the Shell or run from an Editor will run under the debugger. In the Editor, breakpoints can be set with the context menu. This feature is still incomplete and somewhat experimental. Show the stack traceback of the last exception in a tree widget, with access to locals and globals. Toggle automatically opening the stack viewer on an unhandled exception. Open a configuration dialog and change preferences for the following: fonts, indentation, keybindings, text color themes, startup windows and size, additional help sources, and extensions (see below). On OS X, open the configuration dialog by selecting Preferences in the application menu. To use a new built-in color theme (IDLE Dark) with older IDLEs, save it as a new custom theme. Non-default user settings are saved in a .idlerc directory in the user’s home directory. Problems caused by bad user configuration files are solved by editing or deleting one or more of the files in .idlerc. Open a pane at the top of the edit window which shows the block context of the code which has scrolled above the top of the window. Toggles the window between normal size and maximum height. The initial size defaults to 40 lines by 80 chars unless changed on the General tab of the Configure IDLE dialog. The rest of this menu lists the names of all open windows; select one to bring it to the foreground (deiconifying it if necessary). Display version, copyright, license, credits, and more. Display a help file for IDLE detailing the menu options, basic editing and navigation, and other tips. Access local Python documentation, if installed, or start a web browser and open docs.python.org showing the latest Python documentation. Run the turtledemo module with example python code and turtle drawings. Additional help sources may be added here with the Configure IDLE dialog under the General tab. Copy selection into the system-wide clipboard; then delete the selection. Copy selection into the system-wide clipboard. Insert contents of the system-wide clipboard into the current window. Editor windows also have breakpoint functions. Lines with a breakpoint set are specially marked. Breakpoints only have an effect when running under the debugger. Breakpoints for a file are saved in the user’s .idlerc directory. Set a breakpoint on the current line. Clear the breakpoint on that line. Shell and Output windows have the following. Same as in Debug menu. In this section, ‘C’ refers to the Control key on Windows and Unix and the Command key on Mac OSX. Some useful Emacs bindings are inherited from Tcl/Tk: Standard keybindings (like C-c to copy and C-v to paste) may work. Keybindings are selected in the Configure IDLE dialog.. Currently, tabs are restricted to four spaces due to Tcl/Tk limitations. See also the indent/dedent region commands in the edit menu. Completions are supplied for functions, classes, and attributes of classes, both built-in and user-defined. Completions are also provided for filenames. The AutoCompleteWindow (ACW) will open after a predefined delay (default is two seconds) after a ‘.’ or (in a string) an os.sep is typed.. ‘Show Completions’ will force open a completions window, by default the C-space will open a completions window.. Cursor keys, Page Up/Down, mouse selection, and the scroll wheel all operate on the ACW. “Hidden” attributes can be accessed by typing the beginning of hidden name after a ‘.’, e.g. ‘_’. This allows access to modules with __all__ set, or to class-private attributes. Completions and the ‘Expand Word’ facility can save a lot of typing! Completions are currently limited to those in the namespaces. Names in an Editor window which are not via __main__. A calltip consists of the function signature and the first line of the docstring. For builtins without an accessible signature, the calltip consists of all lines up the fifth line or the first blank line. These details may change.. (This could change.) Enter turtle.write( and nothing appears. Idle does not import turtle. The menu or shortcut do nothing either. Enter import turtle and then turtle.write( will work. In an editor, import statements have no effect until one runs the file. One might want to run a file after writing the import statements at the top, or immediately run an existing file before editing. >>>prompt Alt-/ (Expand word) is also useful to reduce typing Command history Idle defaults to black on white text, but colors text with special meanings.. To change the color scheme, use the Configure IDLE dialog Highlighting tab. The marking of debugger breakpoint lines in the editor and text in popups and dialogs is not user-configurable.: -, -c, or ris used, all arguments are placed in sys.argv[1:...]and sys.argv[0]is set to '', '-c', or '-r'. No editor window is opened, even if that is the default set in the Options dialog. sys.argvreflects the arguments passed to IDLE itself. As much as possible, the result of executing Python code with IDLE. IDLE contains an extension facility. Preferences for extensions can be changed with Configure Extensions. See the beginning of config-extensions.def in the idlelib directory for further information. The default extensions are currently: © 2001–2020 Python Software Foundation Licensed under the PSF License.
https://docs.w3cub.com/python~2.7/library/idle
CC-MAIN-2021-10
refinedweb
1,539
68.77
One of the first items you learn as a beginner Python programmer is how to import other modules or packages. However, I’ve noticed that even people who have used Python casually for multiple years don’t always know how flexible Python’s importing infrastructure is. In this article, we will be looking at the following topics: - Regular Imports - Using From - Relative Imports - Optional Imports - Local Imports - Import Pitfalls Regular Imports A regular import, quite possibly the most popular, goes like this: import sys All you need to do is use the word “import” and then specify what module or package you want to actually import. The nice thing about import though is that it can also import multiple packages at once: import os, sys, time While this is a space-saver, it goes against the Python Style Guide’s recommendations of putting each import on its own line. Sometimes when you import a module, you want to rename it. Python supports this quite easily: import sys as system print(system.platform) This piece of code simply renames our import to “system”. We can call all of the modules methods the same way before, but with the new name. There are also certain submodules that have to be imported using dot notation: import urllib.error You won’t see these very often, but they’re good to know about. Using From Module Import Something There are many times when you just want to import part of a module or library. Let’s see how Python accomplishes this: from functools import lru_cache What the code above does is allow you to call lru_cache directly. If you had imported just functools the normal way, then you would have to call lru_cache using something like this: functools.lru_cache(*args) Depending on what you’re doing, the above might actually be a good thing. In complex code bases, it’s quite nice to know where something has been imported from. However, if your code is well maintained and modularized properly, importing just a portion from the module can be quite handy and more succinct. Of course, you can also use the from method to import everything, like so: from os import * This is handy in rare circumstances, but it can also really mess up your namespace. The problem is that you might define your own function or a top-level variable that has the same name as one of the items you imported and if you try to use the one from the os module, it will use yours instead. So, you end up with a rather confusing logic error. The Tkinter module is really the only one in the standard library that I’ve seen recommended to be imported in total. If you happen to write your own module or package, some people recommend importing everything in your __init__.py to make your module or package easier to use. Personally, I prefer explicit to implicit, but to each their own. You can also meet somewhere in the middle by importing multiple items from a package: from os import path, walk, unlink from os import uname, remove In the code above, we import five functions from the os module. You will also note that we can do so by importing from the same module multiple times. If you would rather, you can also use parentheses to import lots of items: from os import (path, walk, unlink, uname, remove, rename) This is useful technique, but you can do it another way too: from os import path, walk, unlink, uname, \ remove, rename The backslash you see above is Python’s line continuation character, which tells Python that this line of code continues on the following line. Relative Imports PEP 328 describes how relative imports came about and what specific syntax was chosen. The idea behind it was to use periods to determine how to relatively import other packages/modules. The reason was to prevent the accidental shadowing of standard library modules. Let’s use the example folder structure that PEP 328 suggests and see if we can get it to work: my_package/ __init__.py subpackage1/ __init__.py module_x.py module_y.py subpackage2/ __init__.py module_z.py module_a.py Create the files and folders above somewhere on your hard drive. In the top-level __init__.py, put the following code in place: from . import subpackage1 from . import subpackage2 Next, navigate down in subpackage1 and edit its __init__.py to have the following contents: from . import module_x from . import module_y Now, edit module_x.py such that is has the following code: from .module_y import spam as ham def main(): ham() Finally, edit module_y.py to match this: def spam(): print('spam ' * 3) Open a terminal and cd to the folder that has my_package, but not into my_package. Run the Python interpreter in this folder. I’m using iPython below mainly because its auto-completion is so handy: In [1]: import my_package In [2]: my_package.subpackage1.module_x Out[2]: <module 'my_package.subpackage1.module_x' from 'my_package/subpackage1/module_x.py'> In [3]: my_package.subpackage1.module_x.main() spam spam spam Relative imports are great for creating code that you turn into packages. If you have created a lot of code that is related, then this is probably the way to go. You will find that relative imports are used in many popular packages on the Python Packages Index (PyPI). Also, note that if you need to go more than one level, you can just use additional periods. However, according to PEP 328, you really shouldn’t go above two. Also, note that if you were to add an “if __name__ == ‘__main__’” portion to the module_x.py and tried to run it, you would end up with a rather confusing error. Let’s edit the file and give it a try! from . module_y import spam as ham def main(): ham() if __name__ == '__main__': # This won't work! main() Now navigate into the subpackage1 folder in your terminal and run the following command: python module_x.py You should see the following error on your screen for Python 2: Traceback (most recent call last): File "module_x.py", line 1, in <module> from . module_y import spam as ham ValueError: Attempted relative import in non-package And, if you tried to run it with Python 3, you’d get this: Traceback (most recent call last): File "module_x.py", line 1, in <module> from . module_y import spam as ham SystemError: Parent module '' not loaded, cannot perform relative import What this means is that module_x.py is a module inside of a package and you’re trying to run it as a script, which is incompatible with relative imports. If you’d like to use this module in your code, you will have to add it to Python’s import search path. The easiest way to do that is as follows: import sys sys.path.append('/path/to/folder/containing/my_package') import my_package Note that you want the path to the folder right above my_package, not my_package itself. The reason is that my_package is THE package, so if you append that, you’ll have issues using the package. Let’s move on to optional imports! Optional Imports Optional imports are used when you have a preferred module or package that you want to use, but you also want a fallback in case it doesn’t exist. You might use optional imports to support multiple versions of software or for speed ups, for example. Here’s an example from the package github2 that demonstrates how you might use optional imports to support different versions of Python: try: # For Python 3 from http.client import responses except ImportError: # For Python 2.5-2.7 try: from httplib import responses # NOQA except ImportError: # For Python 2.4 from BaseHTTPServer import BaseHTTPRequestHandler as _BHRH responses = dict([(k, v[0]) for k, v in _BHRH.responses.items()]) The lxml package also makes use of optional imports: try: from urlparse import urljoin from urllib2 import urlopen except ImportError: # Python 3 from urllib.parse import urljoin from urllib.request import urlopen As you can see, it’s used all the time to great effect and is a handy tool to add to your repertoire. Local Imports A local import is when you import a module into local scope. When you do your imports at the top of your Python script file, that is importing the module into your global scope, which means that any functions or methods that follow will be able to use it. Let’s look at how importing into a local scope works: import sys # global scope def square_root(a): # This import is into the square_root functions local scope import math return math.sqrt(a) def my_pow(base_num, power): return math.pow(base_num, power) if __name__ == '__main__': print(square_root(49)) print(my_pow(2, 3)) Here we import the sys module into the global scope, but we don’t actually use it. Then in the square_root function, we import Python’s math module into the function’s local scope, which means that the math module can only be used inside of the square_root function. IF we try to use it in the my_pow function, we will receive a NameError. Go ahead and try running the code to see this in action! One of the benefits of using local scope is that you might be using a module that takes a long time to load. If so, it might make sense to put it into a function that is called rarely rather than your module’s global scope. It really depends on what you want to do. Frankly, I’ve almost never used imports into the local scope, mostly because it can be hard to tell what’s going on if the imports are scattered all over the module. Conventionally, all imports should be at the top of the module after all. Import Pitfalls There are some very common import pitfalls that programmers fall into. We’ll go over the two most common here: - Circular imports - Shadowed imports Let’s start by looking at circular imports Circular imports Circular imports happen when you create two modules that import each other. Let’s look at an example as that will make it quite clear what I’m referring to. Put the following code into a module called a.py # a.py import b def a_test(): print("in a_test") b.b_test() a_test() Then create another module in the same folder as the one above and name it b.py import a def b_test(): print('In test_b"') a.a_test() b_test() If you run either of these modules, you should receive an AttributeError. This happens because both modules are attempting to import each other. Basically, what’s happening here is that module a is trying to import module b, but it can’t do that because module b is attempting to import module a which is already being executed. I’ve read about some hacky workarounds but, in general, you should just refactor your code to prevent this kind of thing from happening Shadowed imports Shadow imports (AKA name masking) happen when the programmer creates a module with the same name as a Python module. Let’s create a contrived example! In this case, create a file named math.py and put the following code inside it: import math def square_root(number): return math.sqrt(number) square_root(72) Now open a terminal and try running this code. When I tried this, I got the following traceback: Traceback (most recent call last): File "math.py", line 1, in <module> import math File "/Users/michael/Desktop/math.py", line 6, in <module> square_root(72) File "/Users/michael/Desktop/math.py", line 4, in square_root return math.sqrt(number) AttributeError: module 'math' has no attribute 'sqrt' What happened here? Well when you run this code, the first place Python looks for a module called “math” is in the currently running script’s folder. In this case, it finds the module we’re running and tries to use that. But our module doesn’t have a function or attribute called sqrt, so an AttributeError is raised. Wrapping Up We’ve covered a lot of ground in this article and there’s still a lot more to learn about Python’s importing system. There’s PEP 302 which covers import hooks and allows you to do some really cool things, like import directly from GitHub. There’s also Python’s importlib which is well worth taking a look at. Get out there and start digging in the source code to learn about even more neat tricks. Happy coding! Related Reading - Import traps - Circular imports in Python 2 and Python 3 - Stackoverflow – Python relative imports for the billionth time {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/python-101-all-about-imports
CC-MAIN-2017-04
refinedweb
2,136
62.98
Training, saving and loading Artificial Neural Networks in Keras Sign up for FREE 1 month of Kindle and read all our books for free. Get FREE domain for 1st year and build your brand new site Reading time: 30 minutes | Coding time: 15 minutes One of the main reasons why Deep Learning projects take weeks or even months to complete, is that the size of datasets is extremely large. This makes training of the neural network a very long process. In this article, we will explore the concept of saving your own trained neural network models for the future, thereby having to train it only once, and loading it later. All the code demonstrations are done in Keras, a high level API based on Tensorflow. Taking an example of Diabetes detection Let's take an example of a Neural Network built for detecting the presence of diabetes in a patient. The dataset used is the Pima Indian Diabetes dataset. Importing dependencies First, let's import the essential libraries from keras.models import Sequential from keras.layers import Dense from keras.models import model_from_json import numpy as np import pandas as pd Fetching and preparing the data Next, we'll just import the dataset using Pandas and create the input feature vector (X) and target variable (Y) dataset = pd.read_csv("diabetes.csv") X = dataset.drop("Outcome",axis=1) Y = dataset["Outcome"] Before we go ahead and train our neural network, let's first have a look at the input features and target variable: Defining the model structure Next, we'll define our simple neural network. The architecture of the neural network has: - Input layer (8 input features) - Hidden layer 1 (12 neurons) - Hidden layer 2 (8 neurons) - Output layer (1 neuron, softmax function having "0" or "1" as output) model = Sequential() model.add(Dense(12, input_dim=8, kernel_initializer='uniform', activation='relu')) model.add(Dense(8, kernel_initializer='uniform', activation='relu')) model.add(Dense(1, kernel_initializer='uniform', activation='sigmoid')) Building the model Next, we'll build the model using Adam optimizer: model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) Training the model Next, we train the model for 10 epochs model.fit(X, Y, epochs=10, batch_size=10) Epoch 1/10 768/768 [==============================] - 0s 134us/step - loss: 0.4180 - acc: 0.8047 Epoch 2/10 768/768 [==============================] - 0s 117us/step - loss: 0.4208 - acc: 0.7943 Epoch 3/10 768/768 [==============================] - 0s 123us/step - loss: 0.4152 - acc: 0.7982 Epoch 4/10 768/768 [==============================] - 0s 122us/step - loss: 0.4077 - acc: 0.8073 Epoch 5/10 768/768 [==============================] - 0s 114us/step - loss: 0.4030 - acc: 0.8138 Epoch 6/10 768/768 [==============================] - 0s 126us/step - loss: 0.4084 - acc: 0.8047 Epoch 7/10 768/768 [==============================] - 0s 118us/step - loss: 0.4079 - acc: 0.8008 Epoch 8/10 768/768 [==============================] - 0s 129us/step - loss: 0.4083 - acc: 0.7995 Epoch 9/10 768/768 [==============================] - 0s 130us/step - loss: 0.4059 - acc: 0.8008 Epoch 10/10 768/768 [==============================] - 0s 118us/step - loss: 0.4139 - acc: 0.8073 Evaluating the model Finally, let's evaluate our model: scores = model.evaluate(X, Y, verbose=0) print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100)) acc: 80.86% Now that we have defined, built, trained and evaluate our model, we may feel the need to save it for later, to avoid going through the entire process again. Saving the model for later Saving a model requires 2 steps: Saving the model and saving the weights. The model can be saved to a json file using the to_json() function. The weights are saved to a .h5 file using the save_weights() method. Here's a code snippet showing the steps: model_json = model.to_json() with open("model.json", "w") as json_file: json_file.write(model_json) model.save_weights("model.h5") Once these steps are run, the .json and .h5 files will be created in the local directory. These can be used to load the model as it is in the future. These files are the key for reusing the model. Now that the model has been saved, let's try to load the model again and check for accuracy. This is shown in the code snippet below: file = open('model.json', 'r') loaded = file.read() file.close() loaded_model = model_from_json(loaded) loaded_model.load_weights("model.h5") It is important to note that you must always compile a model again after loading it, in order for it to run. loaded_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) Accuracy check on loaded model Here, we will try and achieve the same accuracy score on our loaded model as we got earlier, i.e. 80.86%. score = loaded_model.evaluate(X, Y, verbose=0) print("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100)) acc: 80.86% Hence, we can verify that the performance of our loaded model is exactly same as the model we spent time training. This shows that for other models as well, we can conveniently save a model after training on a large dataset and come back to it later to resume to the same state as earlier. What we have done, saving a model for later is not limited to one's own models. Keras supports Transfer learning, allowing us to access pre-trained models by others, thus greatly reducing the amount of time and effort we need to spend. What is Transfer learning? Traditionally, in order to train a model with good enough accuracy, we needed to have a large size of the dataset, enough time (a few weeks), and sufficient computational power. This is no longer the case with the approach of Transfer learning. Once a model is trained by someone, the pre-trained model can be used by anyone else for solving their problem using this approach. Transfer learning basically allows us to use either some or all layers of a neural network originally trained for some other purposes. Keras allows free and open access to a variety of pre trained models, which anyone can use for training their own modified models with minimal computational effort. Transfer learning will be the next driver of ML success - Andrew Ng
https://iq.opengenus.org/train-save-load-models-keras/
CC-MAIN-2021-17
refinedweb
1,019
67.55
The objective of this post is to explain how to get started with the aREST library running on the Arduino core, on the ESP32. The tests were performed using a DFRobot’s ESP-WROOM-32 device integrated in a ESP32 FireBeetle board. Introduction The objective of this post is to explain how to get started with the aREST library running on the Arduino core, on the ESP32. You can check here the GitHub repository for the library. This is a very simple library that implements a REST API [1], having support for the ESP32 microcontroller. Explaining the concept of REST is outside the scope of this post, but you can read more about it here. Installing aREST on the Arduino environment is very simple and can be done via de Arduino IDE Library Manager. Thus, after opening the IDE, we simply need to go to Sketch -> Include library -> Manage Libraries and on the window that pops put “arest” on the search text box. As can be seen below in figure 1, the aREST library should appear in the list. Figure 1 – Installing aREST via Arduino IDE libraries manager. On this example we will check how to define an endpoint on a REST API that will trigger the execution of a function when a HTTP request is received. The code shown in this tutorial was tested on a DFRobot’s ESP-WROOM-32 device integrated in a ESP32 FireBeetle board. Global variables In order for our application to be reached by client applications, we need to have the ESP32 connected to a WiFi network. Thus, we need to include the WiFi.h library. Besides that, we need to include the aREST.h library, which will expose all the functionality needed for us to develop our REST application. #include <WiFi.h> #include <aREST.h> After these includes, we will declare a global variable of class aREST and instantiate it. The created object will be latter used to setup the API and define the endpoint that will trigger the execution of a function. aREST rest = aREST(); We are also going to need an instance of the WiFiServer class, which will later be needed to handle the incoming HTTP connections. Nonetheless, we will not need to worry about the low level details, since they are all going to be handled by the aREST object we created. The constructor of this class receives as input the port where the server will be listening. We will use port 80, which is the default HTTP port. WiFiServer server(80); Since we are going to need to connect to a WiFi network, we will also store the network name (SSID) and password on two global variables. const char* ssid = "yourNetworkName"; const char* password = "yourNetworkPassword"; Route handling function As stated in the introductory section, we will bind a route from our REST API to a handling function that is executed when a request is performed. The handling functions to be used always need to receive as input a String, as unique argument, and return int [1]. We will not make use of this argument in this tutorial. We will keep things simple for this introduction to the library and thus our function will simply print a information message on the serial console, indicating that a request has been received. int testFunction(String command) { Serial.println("Received rest request"); } The setup function Moving forward to the setup function, we first open a serial connection to output the results of our program. Serial.begin(115200); Next we will need to bind our previously declared function with a specific route in our API. To do so, we simply call the function method of our aREST object and pass as first argument a string with the route where it will be listening and as second our defined function. We will use the “test” route for this example. rest.function("test",testFunction); After this bind, we need to connect the ESP32 to a WiFi network. You can check this previous post for more details on how to do it. Finally, we start the WiFi server by calling the begin method on our WiFiServer object. You can check below the full setup function, which already includes this call and the WiFi connection code. void setup() { Serial.begin(115200); rest.function("test",testFunction); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("WiFi connected with IP: "); Serial.println(WiFi.localIP()); server.begin(); } The main loop On our main loop, we will do the actual handling of the received requests. First, we need to check if a client is has contacted our server. To do so, we call the available method of our WiFiServer object. This function method receives no arguments and returns an object of class WiFiClient if there is a client contacting the server. WiFiClient client = server.available(); After having the WiFiClient instance, we must check if it is available, with a call to the available method. This will return 0 if the client is not available or another value if it is. So, we will simply poll the client until it is available. Note that this is not the most robust approach since we may run into problems if the client suddenly disconnects, but for keeping the code simple we will use the polling approach. Nonetheless, you can check in this example from the ESP32 Arduino core libraries how to check for the client availability in a more robust way. Finally, once the client is available, we call the handle method of our aRest object and pass as input our WiFiClient instance. The remaining operations will be automatically handled by the library. You can check below the full code for the main loop. void loop() { WiFiClient client = server.available(); if (client) { while(!client.available()){ delay(5); } rest.handle(client); } } The full code You can check below the full source code for this tutorial. #include <WiFi.h> #include <aREST.h> aREST rest = aREST(); WiFiServer server(80); const char* ssid = "yourNetworkName"; const char* password = "yourNetworkPassword"; int testFunction(String command) { Serial.println("Received rest request"); } void setup() { Serial.begin(115200); rest.function("test",testFunction); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("WiFi connected with IP: "); Serial.println(WiFi.localIP()); server.begin(); } void loop() { WiFiClient client = server.available(); if (client) { while(!client.available()){ delay(5); } rest.handle(client); } } Testing the code To test the code, simply compile it and upload it to your ESP32 board using the Arduino IDE. Then, open the Arduino IDE serial monitor and copy the IP that gets printed there. To make a request to the route we specified, simply open a web browser and put, the address bellow, changing {yourIP} by the IP of the ESP32 in the network, which you have just copied. You should get an output similar to figure 2. As can be seen, it returns a JSON with some values, but for this tutorial we will not analyse them. Figure 2 – Output of the HTTP Request. If you go back to the serial monitor, the message we defined on our route handling function should now be printed, as shown in figure 3. Figure 3 — Output of the Arduino program, upon receiving the request. Important: At the time of writing, there is a bug that makes the handling function being executed twice when a request is made from a web browser. Nonetheless, if we use a software such as Postman, this doesn’t happen. You can track this issue on GitHub here. Related Posts - ESP32 MicroPython: HTTP Webserver with Picoweb - ESP32: Connecting to a WiFi network - ESP32 Arduino: Setting a soft AP - ESP32: HTTP GET Requests References [1]
https://techtutorialsx.com/2017/10/12/esp32-getting-started-with-the-arest-library/
CC-MAIN-2017-43
refinedweb
1,280
64.41
In this lesson we will begin adding Stats to our game. Experience and Level are particularly important stats, so we will begin by focusing on those and show how we might distribute experience between heroes in a party. As enough experience is gained, the level of the hero can also be incremented. Along the way I will also address how one system might create an exception-to-the-rule in another system and offer a solution on how to allow them to interract while keeping things as decoupled as possible. Preface As usual, I internally debated on the implementation for this portion of the project – should I use GameObjects and Monobehaviours or simple C# objects? I know a lot of the more advanced users will complain if I use a Monobehaviour for stuff like this. Simple C# classes provide some nice flexibility, and reducing it further (to something like a database), would probably be even better. In an effort to implement the game with native C# objects I created my own custom component based system. Because it was based on Unity, I found it very easy to adapt to and I had all the flexibility and speed I wanted without losing the features I needed. Unfortunately, very few people seemed interested in the system (almost no views), and the only feedback I received was negative. The comments I received were basically that it was a lot of extra work for no extra features, or that Unity’s component based architecture sucked and I should have gone for an Entity Component System if I was going to bother to change anything. So what to do? I decided to embrace my toolset. I like Unity, and I like working with GameObjects and MonoBehaviours. By using Unity’s implementation we will be able to make use of a lot of great features including their component architecture (hopefully you don’t hate it), serialization (within a scene and or the project itself), editor visual aids (the inspector is great during development for debugging), etc. Sure they might not be the most efficient, but they are feature rich and good enough that you can certainly create a game, and even a nicely performant game at the level I am aiming for without worry. Perhaps if I were making the next multi-million dollar MMORPG I would need something more advanced, but I am not there yet, so I wouldn’t be a great teacher on that anyway. If you are advanced enough to think my decision is too primitive, then you probably are skilled enough to make good use of my earlier mentioned system or an ECS, etc. Simply adapt the ideas I present here if you like them. Otherwise, don’t be so quick to judge. The speed at which Unity helps one prototype a game is hard to compete with. Notifications This lesson will be taking advantage of my notification center. I will be using the version I blogged about most recently, here. Of course you can also get a copy from the repository here. Because I have already spoken a lot on the notification center I wont spend much time on it now. For a quick introduction, you can think of it as a messaging system which is similar to events. However, any object can post any notification and any object can listen to any notification (and you can specify whether you wish to listen to ALL senders and or from a targeted sender). The notification itself is a string, which means it can be dynamic, and this is something we will be taking advantage of in this lesson. Base Exception Don’t confuse this with C# language Exceptions (an error occuring during application execution). Here I am talking about the complex interactions between systems of an RPG. For example, you may normally be able to move, except you stepped in some glue and are waiting for the effect to wear off. Or you might normally do X amount of damage, but your sword has an elemental charge that the opponent is weak to so it now does extra damage. Rather than have all systems know about all other systems to handle each use-case, I have decided to create an exception class which is posted along with notifications where an exception might be needed. Listeners which need to produce the exception can then listen and alter a scenario as necessary. The most basic level of exception I will model is one where a thing is normally allowed (but might be able to be blocked) or vice-versa. For this, create a new script named BaseException in the Scripts/Exceptions folder. using UnityEngine; using System.Collections; public class BaseException { public bool toggle { get; private set; } private bool defaultToggle; public BaseException (bool defaultToggle) { this.defaultToggle = defaultToggle; toggle = defaultToggle; } public void FlipToggle () { toggle = !defaultToggle; } } Modifiers We are creating a stat system, and the exceptions we will be interested in will probably extend beyond whether or not to allow a stat to be changed and into the realm of how to change it. For example, if you are awarding experience to a hero, but your hero has equipped an amulet which causes experience to grow faster, then it will want a chance to modify the value which will be assigned. When you post a notification, you wont know the order in which listeners are notified. However, the order which modifications are applied can be significant. For example, the following two statements would produce different results based on the order of execution indicated by the parentheses: - 532 * (0 + 10) = 5,320 - (532 * 0) + 10 = 10 I want to allow multiple listeners the chance to apply changes but I also want some changes to be done earlier than other changes, or want to specify another change to happen after all other changes. If you have spent any time looking at damage algorithms in Final Fantasy you wont be surprised to see twenty or so steps along the way. They might start with a base damage formula, then add bonuses for equipment, then buffs, then the phase of the moon (possibly not joking here), and perhaps next would be the angle between the attacker and defender. Then they may clamp some values for good measure before continuing down the path. It is quite complex! I chose to accomplish this in the following way. Any exception which includes modifiers will store them all as a list. All modifiers will have a sort order. After all modifiers have been added, they will be sorted based on their sort order, and then their modifications will be applied sequentially. Create another subfolder in Scripts/Exceptions/ called Modifiers. Following is the implementation for the base Modifier. using UnityEngine; using System.Collections; public abstract class Modifier { public readonly int sortOrder; public Modifier (int sortOrder) { this.sortOrder = sortOrder; } } As I indicated, there may be lot’s of different kinds of modifiers taking place (particularly in regard to modifying a value), some for adding, some for multiplying, some for clamping values, etc. Here is the base abstract class for a value modifier followed by several concrete implementations: using UnityEngine; using System.Collections; public abstract class ValueModifier : Modifier { public ValueModifier (int sortOrder) : base (sortOrder) {} public abstract float Modify (float value); } using UnityEngine; using System.Collections; public class AddValueModifier : ValueModifier { public readonly float toAdd; public AddValueModifier (int sortOrder, float toAdd) : base (sortOrder) { this.toAdd = toAdd; } public override float Modify (float value) { return value + toAdd; } } using UnityEngine; using System.Collections; public class ClampValueModifier : ValueModifier { public readonly float min; public readonly float max; public ClampValueModifier (int sortOrder, float min, float max) : base (sortOrder) { this.min = min; this.max = max; } public override float Modify (float value) { return Mathf.Clamp(value, min, max); } } using UnityEngine; using System.Collections; public class MaxValueModifier : ValueModifier { public float max; public MaxValueModifier (int sortOrder, float max) : base (sortOrder) { this.max = max; } public override float Modify (float value) { return Mathf.Max(value, max); } } using UnityEngine; using System.Collections; public class MinValueModifier : ValueModifier { public float min; public MinValueModifier (int sortOrder, float min) : base (sortOrder) { this.min = min; } public override float Modify (float value) { return Mathf.Min(min, value); } } using UnityEngine; using System.Collections; public class MultValueModifier : ValueModifier { public readonly float toMultiply; public MultValueModifier (int sortOrder, float toMultiply) : base (sortOrder) { this.toMultiply = toMultiply; } public override float Modify (float value) { return value * toMultiply; } } Value Change Exception Based on the ideas I brought forth in the topics of value modifiers, here is a concrete subclass of the Base Exception which holds a list of value modifiers to modify the value which will be assigned in an exception use-case. using UnityEngine; using System.Collections; using System.Collections.Generic; public class ValueChangeException : BaseException { #region Fields / Properties public readonly float fromValue; public readonly float toValue; public float delta { get { return toValue - fromValue; }} List<ValueModifier> modifiers; #endregion #region Constructor public ValueChangeException (float fromValue, float toValue) : base (true) { this.fromValue = fromValue; this.toValue = toValue; } #endregion #region Public public void AddModifier (ValueModifier m) { if (modifiers == null) modifiers = new List<ValueModifier>(); modifiers.Add(m); } public float GetModifiedValue () { float value = toValue; if (modifiers == null) return value; modifiers.Sort(Compare); for (int i = 0; i < modifiers.Count; ++i) value = modifiers[i].Modify(value); return value; } #endregion #region Private int Compare (ValueModifier x, ValueModifier y) { return x.sortOrder.CompareTo(y.sortOrder); } #endregion } Stat Types Individual stat types are just an abstract idea. Most every RPG out there, including those within the same series (like Final Fantasy), use a different set of stats to represent each game. Even if you have similarly named stats, the formulas you use for level growth, damage, etc can all be wildly different. There are often a lot of different stats, and because I am in a prototype stage it doesn’t necessarily make a lot of sense to hard code each stat. Instead, I will begin with an enumeration. By associating the enum type with a value, we can also make it really easy for other game features to target and or respond to a particular stat in a DRY (Dont Repeat Yourself) manner. Create a new script named StatTypes in the Scripts/Enums folder. The implementation follows: using UnityEngine; using System.Collections; public enum StatTypes { LVL, // Level EXP, // Experience HP, // Hit Points MHP, // Max Hit Points MP, // Magic Points MMP, // Max Magic Points ATK, // Physical Attack DEF, // Physical Defense MAT, // Magic Attack MDF, // Magic Defense EVD, // Evade RES, // Status Resistance SPD, // Speed MOV, // Move Range JMP, // Jump Height Count } Stat Component Anything which needs stats (heroes, enemies, bosses, etc) will have a Stat component added to it. This component will provide a single reference point from which we can relate a stat type to a value held by the stat. Create a subfolder called Actor under Scripts/View Model Component and add a new script there named Stats. using UnityEngine; using System.Collections; using System.Collections.Generic; public class Stats : MonoBehaviour { // Add Code Here } If you were confused earlier when I said we wouldn’t hard code our stats (but then I hard coded an enumeration), hopefully it is about to make more sense. Instead of having individual int fields for each of the stat types, I can make an array which aligns a stat type to an int. If I want to add, remove, or rename a stat I only have to worry about the enum and this will still work. Note that I wont actually make the backing array public. Other classes dont need to know how or where I store the data. Instead, I will add an indexer which allows getting and setting values safely: public int this[StatTypes s] { get { return _data[(int)s]; } set { SetValue(s, value, true); } } int[] _data = new int[ (int)StatTypes.Count ]; The setter (via the SetValue method) will handle several bits of logic. Don’t miss the fact that I am able to reuse this logic regardless of which stat is changing! One job of the setter will be to post notifications that we will be changing a stat (in case listeners want a chance to make some sort of exception) and another notification will be posted after we did change a stat (in case listeners want a chance to respond based on the change). For example, after incrementing the experience stat, a listener might also decide to modify the level stat to match. After incrementing the level stat, a variety of other stats might change such as attack or defense. The notifications for each stat are built dynamically and stored statically by the class. This way both the listeners and the component itself can continually reuse a string instead of constantly needing to recreate it.}DidChange", type.ToString())); return _didChangeNotifications[type]; } static Dictionary<StatTypes, string> _willChangeNotifications = new Dictionary<StatTypes, string>(); static Dictionary<StatTypes, string> _didChangeNotifications = new Dictionary<StatTypes, string>(); The first thing our setter checks is whether or not there are any changes to the value. If not we just exit early. If exceptions are allowed we will create a ValueChangeException and post it along with our will change notification. If the value does change, we assign the new value in the array and post a notification that the stat value actually changed. public void SetValue (StatTypes type, int value, bool allowExceptions) { int oldValue = this[type]; if (oldValue == value) return;), oldValue); } Components which handle loading and or initialization can make use of the public method directly and specify that exceptions should not be allowed. Pretty well any other time that the stat values need to be set or modified should probably go through the indexer which does allow for exceptions. Rank Our hero actors will have a component called Rank which determines how the experience (EXP) stat relates to the level (LVL) stat. For example, as the experience stat increments so will the level stat (though not at the same rate). The leveling curve is based on an Ease In Quad curve, which means that low levels can be attained with less experience than high levels. For instance, it only takes 104 experience to go from level 1 to level 2, but it takes 20,304 experience to go from level 98 to level 99! I think of this component as something like a wrapper because it doesn’t hold any new fields of its own, it simply exposes convenience properties around the existing Stats component’s values. Add another script called Rank to the Scripts/View Model Component/Actor/ folder. The implementation follows: using UnityEngine; using System.Collections; public class Rank : MonoBehaviour { #region Consts public const int minLevel = 1; public const int maxLevel = 99; public const int maxExperience = 999999; #endregion #region Fields / Properties public int LVL { get { return stats[StatTypes.LVL]; } } public int EXP { get { return stats[StatTypes.EXP]; } set { stats[StatTypes.EXP] = value; } } public float LevelPercent { get { return (float)(LVL - minLevel) / (float)(maxLevel - minLevel); } } Stats stats; #endregion #region MonoBehaviour void Awake () { stats = GetComponent<Stats>(); } void OnEnable () { this.AddObserver(OnExpWillChange, Stats.WillChangeNotification(StatTypes.EXP), stats); this.AddObserver(OnExpDidChange, Stats.DidChangeNotification(StatTypes.EXP), stats); } void OnDisable () { this.RemoveObserver(OnExpWillChange, Stats.WillChangeNotification(StatTypes.EXP), stats); this.RemoveObserver(OnExpDidChange, Stats.DidChangeNotification(StatTypes.EXP), stats); } #endregion #region Event Handlers void OnExpWillChange (object sender, object args) { ValueChangeException vce = args as ValueChangeException; vce.AddModifier(new ClampValueModifier(int.MaxValue, EXP, maxExperience)); } void OnExpDidChange (object sender, object args) { stats.SetValue(StatTypes.LVL, LevelForExperience(EXP), false); } #endregion #region Public public static int ExperienceForLevel (int level) { float levelPercent = Mathf.Clamp01((float)(level - minLevel) / (float)(maxLevel - minLevel)); return (int)EasingEquations.EaseInQuad(0, maxExperience, levelPercent); } public static int LevelForExperience (int exp) { int lvl = maxLevel; for (; lvl >= minLevel; --lvl) if (exp >= ExperienceForLevel(lvl)) break; return lvl; } public void Init (int level) { stats.SetValue(StatTypes.LVL, level, false); stats.SetValue(StatTypes.EXP, ExperienceForLevel(level), false); } #endregion } Note that this component subscribes to the EXP Will Change stat notification. It creates a clamp modifier with the highest possible sort order (to make sure it is the last modifier to be applied). It makes sure that experience is ONLY allowed to increment – not decrement. No un-leveling in this game. Of course you may not wish to have this constraint in your own game. Perhaps the ability to lose experience could be a fun feature! Who knows? We also subscribe to the EXP Did Change stat notification. This way we can make sure that the LVL stat is always correctly set based on how the experience growth curve would specify. One final note is that I expose a couple of public static methods which allow you to convert between experience values and level values. These might be useful if you were creating a UI which showed some sort of progress bar of how close you are to the next level. Experience Manager Next let’s create a system which can distribute experience among a team of heroes. Perhaps in a normal battle, every enemy unit killed adds a certain amount of experience to a shared pool for later. If, and only if, the level/battle is conquered will the team actually receive the experience points and have a chance to “Level-up”. I would like heroes that are lower level to receive more experience than the heroes with a higher level, but I want to make sure that all heroes still gain experience points. Of course there can still be exceptions here like perhaps any KO’d heroes will not be able to receive experience. Create a script called ExperienceManager in the Scripts/Controller folder. Following is the implementation: using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using Party = System.Collections.Generic.List<UnityEngine.GameObject>; public static class ExperienceManager { const float minLevelBonus = 1.5f; const float maxLevelBonus = 0.5f; public static void AwardExperience (int amount, Party party) { // Grab a list of all of the rank components from our hero party List<Rank> ranks = new List<Rank>(party.Count); for (int i = 0; i < party.Count; ++i) { Rank r = party[i].GetComponent<Rank>(); if (r != null) ranks.Add(r); } // Step 1: determine the range in actor level stats int min = int.MaxValue; int max = int.MinValue; for (int i = ranks.Count - 1; i >= 0; --i) { min = Mathf.Min(ranks[i].LVL, min); max = Mathf.Max(ranks[i].LVL, max); } // Step 2: weight the amount to award per actor based on their level float[] weights = new float[party.Count]; float summedWeights = 0; for (int i = ranks.Count - 1; i >= 0; --i) { float percent = (float)(ranks[i].LVL - min) / (float)(max - min); weights[i] = Mathf.Lerp(minLevelBonus, maxLevelBonus, percent); summedWeights += weights[i]; } // Step 3: hand out the weighted award for (int i = ranks.Count - 1; i >= 0; --i) { int subAmount = Mathf.FloorToInt((weights[i] / summedWeights) * amount); ranks[i].EXP += subAmount; } } } Note that this sample is just a rough prototype and hasn’t really been play-tested. If your game’s party only consisted of 2 units, one at level 4 and one at level 5, it might seem odd for the first unit to get three times as much experience as the other unit. If you had a party of 6 or so units you may never notice. By keeping the system separate it should be easy to tweak to our hearts content without fear of messing up anything else. Test & Demo Let’s wrap this lesson up with a quick test which also serves as a demo. In this test I want to verify that my implementation of converting back and forth between LVL and EXP in the Rank component works for every level as expected. So I will loop from level 1 thru 99 and verify that the output from the static methods match. For my second test / demo I will create an array of heroes, init them all to random levels, and then use the manager to award the party an amount of experience. I will use a variety of modifiers to tweak the value awarded and print each step along the way to verify that it all works as expected. Create a new scene and add a new script to the camera called TestLevelGrowth. The implementation follows. using UnityEngine; using System.Collections; using System.Collections.Generic; using Party = System.Collections.Generic.List<UnityEngine.GameObject>; public class TestLevelGrowth : MonoBehaviour { void OnEnable () { this.AddObserver(OnLevelChange, Stats.DidChangeNotification(StatTypes.LVL)); this.AddObserver(OnExperienceException, Stats.WillChangeNotification(StatTypes.EXP)); } void OnDisable () { this.RemoveObserver(OnLevelChange, Stats.DidChangeNotification(StatTypes.LVL)); this.RemoveObserver(OnExperienceException, Stats.WillChangeNotification(StatTypes.EXP)); } void Start () { VerifyLevelToExperienceCalculations (); VerifySharedExperienceDistribution (); } void VerifyLevelToExperienceCalculations () { for (int i = 1; i < 100; ++i) { int expLvl = Rank.ExperienceForLevel(i); int lvlExp = Rank.LevelForExperience(expLvl); if (lvlExp != i) Debug.Log( string.Format("Mismatch on level:{0} with exp:{1} returned:{2}", i, expLvl, lvlExp) ); else Debug.Log(string.Format("Level:{0} = Exp:{1}", lvlExp, expLvl)); } } void VerifySharedExperienceDistribution () { string[] names = new string[]{ "Russell", "Brian", "Josh", "Ian", "Adam", "Andy" }; Party heroes = new Party(); for (int i = 0; i < names.Length; ++i) { GameObject actor = new GameObject(names[i]); actor.AddComponent<Stats>(); Rank rank = actor.AddComponent<Rank>(); rank.Init((int)UnityEngine.Random.Range(1, 5)); heroes.Add(actor); } Debug.Log("===== Before Adding Experience ======"); LogParty(heroes); Debug.Log("====================================="); ExperienceManager.AwardExperience(1000, heroes); Debug.Log("===== After Adding Experience ======"); LogParty(heroes); } void LogParty (Party p) { for (int i = 0; i < p.Count; ++i) { GameObject actor = p[i]; Rank rank = actor.GetComponent<Rank>(); Debug.Log( string.Format("Name:{0} Level:{1} Exp:{2}", actor.name, rank.LVL, rank.EXP) ); } } void OnLevelChange (object sender, object args) { Stats stats = sender as Stats; Debug.Log(stats.name + " leveled up!"); } void OnExperienceException (object sender, object args) { GameObject actor = (sender as Stats).gameObject; ValueChangeException vce = args as ValueChangeException; int roll = UnityEngine.Random.Range(0, 5); switch (roll) { case 0: vce.FlipToggle(); Debug.Log(string.Format("{0} would have received {1} experience, but we stopped it", actor.name, vce.delta)); break; case 1: vce.AddModifier( new AddValueModifier( 0, 1000 ) ); Debug.Log(string.Format("{0} would have received {1} experience, but we added 1000", actor.name, vce.delta)); break; case 2: vce.AddModifier( new MultValueModifier( 0, 2f ) ); Debug.Log(string.Format("{0} would have received {1} experience, but we multiplied by 2", actor.name, vce.delta)); break; default: Debug.Log(string.Format("{0} will receive {1} experience", actor.name, vce.delta)); break; } } } Run the scene and look through the console’s output to verify that everything is as you would expect it to be. Summary That ended up being a lot longer than I expected, again. One might think that something as simple as adding some stats and tying EXP to LVL would be easy. But then we started adding exceptions to the rule, value modifiers, a manager to distribute the experience among a party, etc. and things got a lot more complex. Hopefully you were able to follow along with all of my examples and implementations. If not, feel free to add a comment below! 53 thoughts on “Tactics RPG Stats” Cool blog, thanks for sharing your skills! Hi, thanks for continuing these articles. Again I found an error !! In the SetValue method in this line // The notification is unique per stat type this.PostNotification (WillChangeNotification (type), exc); The PostNotification method has not been defined. Thanks Sorry friend, I no agree the Notification Center attach to my proyect. Please look again under the heading for Notifications – you should see a link for the older post or you can just look through the history of my blog for Better than events. In the same section I also provided a link to my project repository where you can get the Notification and NotificationExtensions classes. Toward the beginning of the article I mentioned including the NotificationCenter class I wrote in another post and provided the link. However, I could have been more clear and also mention that I also included the companion script NotificationExtensions which is where PostNotification is actually declared. Hi, thanks for your answers. I have a couple of questions I hope not bother much with them. First the easy question, in the method: LevelForExperience public static int (int exp) { int lvl = maxLevel; for (; lvl> = MinLevel; –lvl) if (exp> = ExperienceForLevel (lvl)) break; lvl return; } At the beginning of the cycle for not declare the variable only use; this is the first time I see it. The system then uses the variable declared in the previous line, this is so? My other question is that I read the scripts and see several times the test code, but can not find where you set the amount of experience needed to level up. This amount is exponential? I remember the expericia necessary to level up was in Final Fantasy Tactics Advance, always 1000 and each offensive or defensive action gives you some experience. I mention this because, in my game is that I would use a system similar to the FFTA experience. Allowing level up in the course of the fight both heroes and foes. Your system could be adapted for this? Once I appreciate your answers. Greetings 1.) In a for loop, all of the expressions are optional (that goes for the initializer, condition and iterator). You still need the semicolons though as I show by simply skipping the initializer and beginning with a semicolon. In this case I used a variable which was declared outside of the for loop so that I could determine at which point I break out of the loop. 2.) You won’t see a place where I hard code an amount of experience required for each individual level up, because I used a curve to define it for me. The curve is based on start(0) and end(999,999) values which I interpolate over. It isn’t an exponential curve in the pure mathematical term, but it does require more experience with each gained level. I included this version because it could be used in other RPG’s and was probably more confusing for people to implement. A fixed level growth system would be far easier than a curve to implement. Define an int variable in the class to hold the amount of experience you need for each level: int growRate = 1000;The ExperienceForLevel method would be as simple as return growRate * level;and the LevelForExperience method would also be easy return exp / growRate; I really enjoyed this implementation of a stats system, and especially the examples of how to use the notification system. I had a quick question for you- In the Stats class, in the SetValue method, last line, you send oldValue through the PostNotification method. Why do you send the old value? Or am I misunderstanding what is going on here? Thank you for this great tutorial series! Great question Jordan. The reason I include the “oldValue” is because there are often a variety of reasons I want to know more than just what the current value is. I want to know by how much a value has changed and whether the change was positive or negative. For example, sometimes you may want to show text on the screen over a character as a stat changes. You are more likely to show the amount of change than the current value, so by passing the oldValue and the object from which you can get the current value, you can then determine the amount of change. Ok brother, I like it this way rather than fixed values. Simply fails to understand all the code correctly. If it’s not too much trouble, you could include an example? It really cost me follow this tutorial. I’m glad you like it. I’m always happy to elaborate on any area which is unclear, but I already included a demo so you will have to be more specific in what you need help with. Could you give me an example of calculating experience. Suppose a unit gain experience with each hit from this point then hitting the enemy and methods come into play when called until the hero gains a level.You receive as much exp per hit, how much you need to level up, etc.I am that what I ask is tedious, but I would greatly help to follow the logic of this lesson. Thank you very much for your willingness to serve all doubts. Hey Gustavo, there is no limit to the number of different ways experience could be gained and every game will do it a little different. I can’t cover every possible way but I could share a few examples. In the example I created here I had imagined a scenario where every opponent would have some sort of “Enemy” component which included information like how much experience they would give for being defeated, and what rewards they could drop such as gold, etc. In this scenario, I would wait for the battle to actually be completed, and then the game would loop through all of the enemies, sum up the total amount of experience, and distribute it among all of the heroes in the player’s party. It sounds like you want something different, where you gain experience at each hit. For this scenario, I would still have an “Enemy” component which determined how much experience could be gained from defeating an enemy. Then, when you actually hit the enemy I would award a percentage of its experience according to the percentage of its health you took away. For example, say an Enemy has 100 hit points and your attack did 10 damage. You would then award 10% of whatever experience the enemy could award. If you go this route you would have to keep in mind ways that players could kind of cheat the system. For example, if a particular enemy is worth a lot of experience and they get experience for each hit, then they could attack it, heal it, and attack it again. By not actually letting the enemy die they could farm experience as much as they wanted. You could get around this by holding two fields, one for the max amount of experience it could award (use this stat for determining the percentage to give) and another which begins at the full amount and decrements with each hit until zero. When you award experience you would take the amount of experience the enemy had left or the amount determined by the percentage – whatever was less. In this way you could cap the amount of experience that players could farm out of any one enemy. Other games also award experience based on the technique. So for example, Skyrim which awards experience in a variety of categories based on the action you take. In this case, you gain levels in each category, and leveling up in the categories levels up the overall player level. In this case I wouldn’t necessarily have an “Enemy” component with an experience award stat for defeating the enemy – instead, there would be a stat on each skill that would say something like, for successfully hitting an enemy with this magic spell, award X amount of experience to the magic category. Does that help? Let me start by saying I love these ideas even thought I haven’t fully understood them yet :p (I didn’t know about indexers and they seem super useful!) I also have a few questions about why you did some stuff but I’ll have to reread before I get to asking. just a quick doubt for now: You’d still need to make components to handle some stats, like health and mana, no? For example, to handle death, healing/damage particle effects and all that. On the other hand move speed and jump height wouldn’t need one.. Yes, just like we made the Rank component to wrap up special functionality for the Experience and Level, we would be able to make a health and mana component to handle the relationships between HP & MHP, and MP & MMP. Its kind of funny the timing of the question because my next post should actually include examples of both of those. Would those be sub-components of the stats component or base components of the character? I’ll be waiting for that article then :p In my implementation they would be components on the root of the character (at the same level as the Stats component) although it doesn’t actually matter where they are located. In fact, you could even make manager style components or systems on completely separate objects that listen to the notifications for all characters and clamp values etc. The units don’t necessarily need their own. Hey, So I am experiencing a strange bug where when I do a normal attack, how much damage it does is being affected by my Magic Attack stat as well as my attack stat. To test this I set everything stat to 1, and for all my units it said they would do 5 damage. Then I raised my magic attack, and their damage went up for regular attacks. The peculiar thing is that something else must be messing with my stats, because when I did the same test in your repository, the units all did 1 damage when I put all their stats to 1, and yours didn’t have the same bug, obviously. Found the bug. The Base Ability Power script was old code. Updated it to your newest, and its working. Quick question, won’t AwardExperience return NaN if you only have one hero in your party? the following line should give NaN since it’s dividing by zero: “float percent = (float)(ranks[i].LVL – min) / (float)(max – min);” I added the following custom code to the beginning of the function to account for this: if (party.Count == 1) { Rank rank = party[0].GetComponent(); if (rank != null) rank.EXP += amount; return; } Great catch, you are right! Now that I look at it again, it could also happen even with multiple party members that all had the same LVL stat. In order to handle both cases, you might try something else like adding one to the max level and subtracting one from the min level so that there is always a range. Ah, thanks, didn’t think of that. Just wanted to thank you again for this tutorial, Unity was a bit intimidating at first but I feel like I have a much deeper understanding of its utilities after following along here. I was stuck a little bit. I am trying to implement the experience gain in the endbattlestate. Everything seems to be running correctly with the test code here, except that the value for the experience is always -2147483648 (I placed a debug.log to read the subamount). Then I did as Chris (if I may call you Chris ;)) and you mentioned here, and it was fixed! if (max == min) { max = max + 1; // max += max; } On a side note, if a character gains 1000 exp and levels from 1 to 10 for example, is there a way I can count easily the number of levels gained? Or can I make the onlevel up post notification happen each time a unit gains a level, not just the final level? I was using the onlevelup listener to trigger something else, however the onlevelup only seems to trigger one time for the final new level. Yes, you can easily determine the amount of levels earned. Take a look at the “OnExpDidChange” method… if you were to store the new “LevelForExperience” stat result in a temporary variable before updating the real LVL stat, then it should be pretty trivial to determine the difference between the current LVL stat and the new temporary variable. The code might look something like: var nextLevel = LevelForExperience(EXP); var changeInLevels = nextLevel - stats[StatTypes.LVL]; stats.SetValue(StatTypes.LVL, nextLevel, false); Or, you could separately observe the “DidChangeNotification” for the LVL stat which includes the “oldValue” as an argument. This approach guarantees that any modifiers would also be taken into account. Hey, your tutorials are great! I followed it up so far and managed to finish it. But now I want to tweak it a bit, and I’ve stumbled into a problem. I wanted to change the combat system from using ATK, DEF, and Evade (and MATK and MDEF) into a system where hit or miss (and damage) is determined by the attacker rolling d10s and seeing how many rolls under a certain number. So, now I have an ATKROLL stat (which is how many dice rolled in an attack), and ATKRATING stat (which is the number the rolls must beat). Each roll that pass is a hit, and vice-versa each roll that failed is a miss. Now, the problem is that each ability (and each weapon) would have different ATKROLL and ATKRATING stats, with maybe the Unit itself having an increased ATKROLL or ATKRATING with leveling up. So, is attaching a Stat component (with only those two stats in it) onto the Ability or Equipment gameObject the right way to do it, or should I do something else? I also want to show the rolls visually, how do I track the dices being rolled? Thanks for the time, I really need a second opinion on this. Hey, your question is very applicable to the next post in this series, “Tactics RPG Items and Equipment”. In particular, I had imagined that weapons and armor would modify a unit’s stats by the “StatModifierFeature”. Your other questions are outside the scope of this tutorial, but if you want to open a thread on my forum I would be happy to go into more depth there. Hey there, thanks again for all you’ve done for us with this set of tutorials! I have a quick question regarding the numbers I’m getting in the Test scene. For instance, I see these results in the console logs: Name:Josh Level:3 Exp:416 Josh would have received 90 experience, but we multiplied by 2 Name:Josh Level:4 Exp:1012 Of course, it’s kind of obvious that in this case we multiplied Josh’s *total* EXP by two, after first adding the 90. This is not how I imagine it should go, and seems that the order of operations is wrong. I’m having an issue untangling exactly where/what to change, as I’m still somewhat new to events, handlers and arguments, and keeping a clear head about what we’ve done from previous lessons is a bit rough. Is there some way to make the multiply modifier apply to the 90 experience (in this case), or are we stuck modifying the total? Am I correct that this is a ‘bug’ or is this intentional? You are right, it was a bug – I didn’t notice it until part 17: Status Effects. You can read all about it and how to fix it there. Thank you for the reply! As per the forum post, I think I tracked down the functionality and understand why it’s happening. I just didn’t give a second thought as to whether or not it was supposed to be this way and assumed I was missing something. Glad to know it’s touched on later and I don’t have to deviate from your excellent tutorial just yet 🙂 Hi, thank you again for your amazing content. I have hit a bug but I can’t find the solution to fix it, the first time I ran the scene everything worked as expected but then an error appeared and not the console does not log anything at all on subsequent tests. The console logs: ArgumentNullException: Argument cannot be null. Parameter name: key System.Collections.Generic.Dictionary`2[System.Object,System.Collections.Generic.List`1[System.Action`2[System.Object,System.Object]]].ContainsKey (System.Object key) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:458) NotificationCentre.RemoveObserver (System.Action`2 handler, System.String notificationName, System.Object sender) (at Assets/Scripts/Model/NotificationCentre.cs:79) NotificationCentre.RemoveObserver (System.Action`2 handler, System.String notificationName) (at Assets/Scripts/Model/NotificationCentre.cs:57) NotificationExtensions.RemoveObserver (System.Object obj, System.Action`2 handler, System.String notificationName) (at Assets/Scripts/Model/NotificationExtensions.cs:29) TestLevelGrowth.OnDisable () (at Assets/Scripts/Temp/TestLevelGrowth.cs:14) Any help is appreciated. Without seeing your code I can only guess. The logs make me think the problem is related to your use of the Notification Center. My primary guess is that you have tried to use “RemoveObserver” more than once with the same key (The part that looks something like this: Stats.DidChangeNotification(StatTypes.LVL)). It’s possible you have additional issues if you aren’t seeing notifications any more. Perhaps you accidentally used “RemoveObserver” when you meant to use “AddObserver” or perhaps you tried to “RemoveObserver” at the wrong time. Are you merely following along with the “Test & Demo” section, or have you started adding your own code as well? Hi, I haven’t changed anything, but I did find a “return” that i missed and now everything is working fine, thank you for your help and sorry if this was trivial, again amazing work as always. Hi, I thanks for the tutorial, I’m really enjoying it so far. I just noticed a minor typo in some of your code, since you seem to like you job well done (otherwise the tutorial wouldn’t have this quality) you might want to correct it ^^ In the first lines of the “ValueChangeException” script you wrote #region Fields/Properteis” I guess you wanted to say properties. It’s no big deal tho so take your time. Thanks for the good work! Fixed 🙂 Hello, love these posts. I am making a little tactics game in my free time and the focus on architecture and design has been very helpful, especially this post about exceptions, which was a real stumbling block for me. I have a question about modelling derived stats. Say you have an armor class, that is based off your Agility, but can be adjusted separately from Agility. Derived stats wouldn’t need to be stored in job or class data or save data, but calculated at run time based on base stats and exceptions. Curious how would you expand the design from the post to model something like this? I’ve been trying to come up with an elegant solution and coming up.. inelegant… Have you completed the series yet? The next lesson on Items and Equipment might help explain the general idea, because the resulting stat will be based on an event like equipping or removing an item. If that doesn’t quite cover what you meant, then I’d recommend starting up a new thread on my forum so we can go a bit more in depth. Hope that helps. I am pretty sure this wouldn’t cover the case that I am thinking of. To the forums! Hello JON, I really appreciate all your precious work here. I’m planning to make my own game (not yet firmly fixed the game design, but it might be a type of Board Game + CCG that has a lot of things to learn from your works!), so I’m following your tutorial (4 years from the first post! lol). While following yours, however, I’ve met a NullReferenceException at your Stats.SetValue Method. Below is my new debugged code : ****************************************************************************** public void SetValue (StatTypes type, int value, bool allowExceptions) { int oldValue = this[type]; if (oldValue == value) return; //Allow exceptions to the rule here /* I’ve put it outta the if phrase! */ ValueChangeException exc = new ValueChangeException(oldValue, value); if(allowExceptions) { /), exc); /* The original post, the second parameter was ‘oldValue’, not ‘exc’! */ } ****************************************************************************** Without this fixation, the script meets problem at Rank.OnExpWillChange : ****************************************************************************** void OnExpWillChange(object sender, object args) { ValueChangeException vce = args as ValueChangeException; vce.AddModifier(new ClampValueModifier(int.MaxValue, EXP, maxExperience)); } ****************************************************************************** Here we are trying to change ‘object args’ to ‘ValueChangeException’ type. The original code just passed an int value (oldValue), which can’t translated to ValueChangeException type whose form is (fromValue, toValue). My scripts have no problem after changing the ‘oldValue’ to ‘exc’. If this is a definite problem, however, I can’t understand that why no other guys have experienced same problems. There were no reply same to mine! Could you please check this, JON? Do you think I am doing right, or there might be something missing? (It’s hard to post my full code here, basically I’ve made almost same codes as you posted.. If you want to see other method or classes, please tell me where to post as comment here.) The reason my code works is because there are two different notifications posted. The first one, “WillChangeNotification” passes along the “ValueChangeException” object so that there is a single place where each observer can know the old value and the potential (but changeable) new value. This is the notification that “Rank.OnExpWillChange” is observing, so there is no problem casting the args accordingly. The second notification, “DidChangeNotification” doesn’t need to provide the new value, because that is simply the stat’s current value, but it still might be interesting to observers to know what the old value had been, so I pass that along. I didn’t pass the “ValueChangeException” in the “DidChangeNotification” because exceptions may not have even been allowed, and in that case, I wouldn’t even bother creating that object. Either way both the old value and new (current) value are available at that time. Also, the info that is passed with each notification helps indicate the purpose and potential of the notification. I didn’t intend for anyone to modify stat values in a “DidChangeNotification” – because at that point I want to indicate that everything is “final”. Had I passed a “ValueChangeException”, then people might think it is still ok to modify the stat at that time, but any changes made wouldn’t actually be kept and so this would be misleading. Thank you for the quick reply. Now I know that you intended to use the ‘oldValue’ because you don’t want ‘exceptions’ allowed here. After reverting back to the original code, however, I meet error as below (which doesn’t occur at the fixed code) : **************************************************************************** NullReferenceException: Object reference not set to an instance of an object Rank.OnExpWillChange (System.Object sender, System.Object args) (at Assets/Scripts/View Model Component/Actor/Rank.cs:64) NotificationCenter.PostNotification (System.String notificationName, System.Object sender, System.Object e) (at Assets/Scripts/Common/NotificationCenter/NotificationCenter.cs:185) NotificationExtensions.PostNotification (System.Object obj, System.String notificationName, System.Object e) (at Assets/Scripts/Extensions/NotifitcationExtensions.cs:15) Stats.SetValue (StatTypes type, System.Int32 value, System.Boolean allowExceptions) (at Assets/Scripts/View Model Component/Actor/Stats.cs:83) Rank.Init (System.Int32 level) (at Assets/Scripts/View Model Component/Actor/Rank.cs:94) TestLevelGrowth.VerifySharedExperienceDistribution () (at Assets/Temp/TestLevelGrowth.cs:44) TestLevelGrowth.Start () (at Assets/Temp/TestLevelGrowth.cs:21) **************************************************************************** As I mentioned at the first reply, the problem occurs at Rank.OnExpWillChange() : ****************************************************************************** void OnExpWillChange(object sender, object args) { ValueChangeException vce = args as ValueChangeException; // After using ‘Debug.Log()’, I could find the ‘vce’ have some problem. // My assumption is that, the problem caused because we’re trying to throw ‘oldValue(int)’ to ‘ValueChangeException’ type. // If I want to preserve the original code as you intended, what I have to do now? vce.AddModifier(new ClampValueModifier(int.MaxValue, EXP, maxExperience)); } ****************************************************************************** It sounds like there must be a difference between your code and the project code. If you download the project repository, check out this lesson’s commit, and run the sample it should build and play without errors. My guess is that your implementation of Rank might accidentally have linked the “DidChangeNotification” to the “OnExpWillChange” handler instead of the “OnExpDidChange” handler. You will find that connection made in the “OnEnable” method. Oh, I’ve found your reply just now, then SUCCEED to find the reason!!}WillChange”, type.ToString())); return _didChangeNotifications[type]; } the ctrl + c v PROBLEM was here….. I added “Stats.{0}Willchange” again to DICTIONARY _didChangeNotifications! Sorry for bothering you with such a trivia :d And REALLY THANKS!!! Hello Jon, My question for you today (sorry I post so much, I’m devouring your tutorials during confinement) is about a certain syntax you use in this tutorial. I don’t understand how the syntax works for the modification of the ValueChangeException. I tested the whole thing and everything works, so it’s not a debugging question, I just need to understand what exactly is happening. In the stats script, inside of the SetValue method we have:; } So the valueChangeException in this script is stored in a variable exc, which is local to this method. In the rank script, we have this method to prevent EXP from decreasing: void OnExpWillChange(object sender, object args) { ValueChangeException vce = args as ValueChangeException; vce.AddModifier(new ClampValueModifier(int.MaxValue, EXP, maxExperience)); } I don’t understand why the vce variable, which is local to this OnExpWillChange method, affects the other exc variable. Somehow, they point to the same ValueChangeException, but how? Shouldn’t this be a case of int a = 4; int b = a; b+=3; so b==7 but a==4 still? In programming there are two main types of data: value-types and reference-types. In your example with the “int” data-types what you have is a value-type. Value-types are copied by their value, which is why `b` is able to hold the same value as `a` without modifying the value of `a`. Reference-types are passed by a reference, which is like a memory address of where it exists. So when we pass this type of object in a parameter to a method, even though it looks like a local variable, it is actually still pointing to the same memory as from earlier. It wont matter “where” we modify it. You can know something is a Reference type because it is defined as a “class”. If you see something defined as a “struct” or which uses one of the base level data types like an “int”, then those will be value-types. Ah, I’ll have to get used to that. Thanks for the explanation! Hey John, been following along quietly these past few weeks in what time I can afford. I’ve rewritten my state machine (3 times) based on your earlier articles in the series and I’m finally at a place I am comfortable with it. I finally have a question for you, so I will throw in a bit of feedback as well. I haven’t finished the whole project series yet (and probably won’t for a while), so if you’ve addressed anything in a later article feel free to send me packing. 1) First to say, thanks for all this, and for continuing to reply and engage with your audience 5 years (!) later. I have looked several times over the past 8 months for actual source code of a tactics rpg in a somewhat complete state, and yours is the only thing I found worthwhile. 2) Looking ahead in the series, that last article was from Dec 2016. Is this project complete? Do you have any articles that address some of the significant changes in C# and Unity versions since then? I’m thinking Unity’s input system, GUI, and some C# features like events/delegates, expression functions, LINQ, netcore, etc. I am impressed by your explorations of the reasoning behind the decisions you make so I’d love to hear your opinions on where you would take this project with new features in Unity and .NET. 3) What’s the deal with Unity code style? Coming from several years of professional C# dev (and Java before that), Unity’s naming conventions and style like you use here confuse me. I’m all for adopting a new convention, but it seems people are all over the place with Unity’s style vs MS’ style. I haven’t been able to find any standards guidelines either. What’s your take? 4) Finally, actually related to this specific article: I’ve been pretty on board with everything you’ve done so far, but this one has me scratching my head. Can you elaborate on your reasons to make each stat its own component rather than simple properties (perhaps with property change notifications), and why you index them by an enum rather than hard-coded property names? The other thing that is a bit strange to me is calling SetValue again from OnExpDidChange. I understand why it works, but it seems weird and prone to confusion/bugs, since the SetValue gets called twice, and the ExpWillChange notification only getting fired when exceptions are allowed, with the ExpDidChange notification getting skipped the second time based on that == check. Is there actual value in having that second SetValue call? Without experimenting with it yet, it seems to me that the SetValue should be expected to set the correct value from the modifiers everytime. Again, I only ask because I find your explanations (in comments here and on reddit) to be almost as useful as the articles themselves. Once again, thanks for all of these guides! I just realized that OnExpDidChange sets the *Level* not the Exp again, so ignore that comment :/ You’re very welcome. It is rewarding to me to know that my work has maintained value for so long, so I am happy to help out where I can. I wouldn’t say the project is “complete”, but that it is “complete enough” – my primary goal was to make something that resembled a complete battle engine for a Tactics RPG which I felt would be the greatest challenge in programming that kind of game. I feel like I accomplished that much. There is always room for polish, more features, maintenance to keep things up-to-date, etc and it is possible that I will revisit it, but I don’t have active plans to do anything at the moment. I somewhat intentionally stayed away from implementing too many Unity specific features like GUI because I knew that those kinds of things would be the most likely to change over the years. As for advancements in things like .NET – I would be happy to update those, but my job has shifted to Swift rather than C# and so I am out of date myself 🙂 Unity’s code style? My honest guess would be that a large part of the Unity community are not professional programmers. There are a ton of self-taught hobbyists who learn by doing and then share what they did. I am a professional, but am a self-taught programmer as well, and I have dabbled in so many languages simultaneously that my style probably got a bit blurred. In addition, a lot of best practices (like using properties and not fields directly) are abandoned in favor of ease-of-use within Unity for things like serialization to appear in the inspector pane. As for the stat architecture, just to make sure we are on the same page, each stat is NOT its own component. All stats live within a single component and are stored by an array of stat values. Regarding their access via an enumeration, I wanted to make something very flexible design-wise and also easy to use in Unity. Using things like strings or enums are very easy to use in the inspector and are easy for other beginners to understand as well. For example, I want to make a piece of equipment with a feature that boosts a specific type of stat – to build all of that at design time, I felt like it would be far simpler to just let it save an enum representing the stat to modify since it can already be serialized in the inspector. With all of that said, if you know of a better way to accomplish the same goals, feel free to mention it here or in the forums as I am sure other readers would benefit as well. After working on implementing this and playing around with it, I’m not sure if I mispoke or just misunderstood, but yes I see now the stats collection is it’s own component. I did not think about how the enum based stat would affect it’s interaction with modifying effects… that is a very good point. I was thinking of just representing them as first class fields on the component. eg: class Stats { public int level; public int exp; public int maxHp; //…etc } but that’d be a lot of messy control statements for handling items, skills, etc that would be configured to increase a stat. So you’ve convinced me! My plan right now is to try to stick as close as possible to your tutorial, with some minor low level modifications (eg. I used a dictionary instead of the array for stats). Then, see where I might like to experiment. And if I find something I think works better, I will definitely bring it up for your feedback. Wrt. hobby programming vs learning professionally, game development has been completely a hobby project for me, and developing large-scale web services is an entirely different ball game. The optimization concerns and design patterns are really different and at times counter-intuitive. I am having trouble sometimes wrapping my head around the differences, but explanations like you provide and discussions like these comments have been great, so thanks! Question aout the set value method and the exception class. Doesn’t this generate garbage everytime a value is changed?! So using this system for an RTS would be suicidal or am I talking stupid? Isn’t there a way to turn exceptions into structs? The architecture here wasn’t designed for an RTS, it was designed for a turn-based RPG and so I was able to take a much more relaxed position with my architecture. With that said, I don’t know that I would go so far as to say the pattern is suicidal – feel free to profile to see how big of an impact the extra garbage collection will make. You could certainly opt to use other architectural patterns that create less objects, but it would not be trivial to change “this” pattern to use structs because structs cant use inheritance and even using it with the notification pattern will still result in boxing (the creation of another object). Well I’mnot making an RTS, nor am I planning to. In fact given my current project this aproach seems like a better option. I am mostly asking for pure curiosity, I respect you a lot as a programmer, as reading trough your blog has helped me improve a lot. And I was looking for your input, sorry if that sounded condescending. But I would love to hear what approach would you use for an RTS… If possible. During my research I came across this It seem lika good aproach too! On another note. 1.- Would the rough ideas on your pokemon game translate well to unity’s DOTS? I’m looking to learn it, and I feel like a full game would be a way to learn 1.- Have you considered a youtube channel? As much as I preefer written tutorials, blogging seems to be dying, and I feel like a youtube channel would get your work much more widespread. No worries, I didn’t think you were being condescending. I just wanted to point out that I wasn’t intending to create a one-size-fits-all architecture. In my personal opinion, trying to do that often results in an inferior experience for all. DOTS would probably (eventually at least) be a great approach for an RTS. I watched the series you linked to. It’s also a nice solution, and you could do a lot with it. Of course, every approach will have pros and cons. Some things to think about: 1. Both the StatModifier class and CharacterStat class will grow in length as more types are added to the StatModType. I usually prefer to solve this problem with polymorphism (sub types of StatModifier that know how to apply themselves), though in some cases like with percent add it may actually be easier to work with all of them in a wrapping system rather than within the sub type itself. 2. You must apply the modifier statically not dynamically, and it must be per character. Say for example that you want some sort of feature that applies to all units within a party. Can that feature turn on and off? Is it easy to have an event where you apply and remove the feature as needed? Are there other flows you might forget to think about? For example, say a unit is spawned after the fact – will you remember to go back and look for environment features that were already turned on that should apply to it, and how easy will it be to find and apply them? My system is already dynamic and I wont have to think about state or flows like this because of it. 3. Persistence – what do you want to be able to save and how to you want to save it? Would you want to save the list of stat modifiers within the character stat class? If you need to load something and a character already had equipped items, does it unserialize already equipped, or do you need to instantiate and then re-equip the items the unit should have been wearing? Will that get confusing by potentially re-adding modifiers to the stat modifier list? Note that my tutorial project doesn’t cover persistence either, but I do feel like some of the pain points will be avoided in my approach. Regarding your other questions, I’ve looked at DOTS a few times, hoping each time that it has evolved a bit more. It looks very powerful, but it is nowhere near as intuitive to use. It also looks like overkill for many types of games, including turn-based games like this one or my pokemon board game. Some things may translate, but I, for one, have not yet felt like it is ready to really try to. Perhaps as I use it more it will be more obvious how to structure heavily intertwined and dynamic stat tracking systems, but at the moment I would rather a more traditional object oriented / component based approach. I have considered a youtube channel, but to me it all seems a bit overwhelming. The amount of production necessary to record, edit, etc, vs just typing some text is a lot. Plus, I don’t consider myself interesting to listen to. It doesn’t mean I wont ever try it, but I don’t have plans to at the moment.
http://theliquidfire.com/2015/07/27/tactics-rpg-stats/?replytocom=21566
CC-MAIN-2020-45
refinedweb
10,471
54.12
.-. |o,o| ,| _\=/_ .-""-. ||/_/_\_\ /[] _ _\ |_/|(_)|\\ _|_o_LII|_ \._./// / | ==== | \ |\_/|"` |_| ==== |_| |_|_| ||" || || |-|-| ||LI o || |_|_| ||'----'|| /_/ \_\ /__| |__\ Lloyd Atkinson wrote:Xamarin so you can use C#/.NET Munchies_Matt wrote:That compiles to Java bytecode does it? ΑlphaΔeltaΘheta wrote:Microsoft made C# an ISO Spec, it's open to use by anyone... there has been a hell lot of apps running in Linuxes using C#/Mono Munchies_Matt wrote:OK. Well, MSIL is probably close to byte code anyway; didn't J++ run on .net unmodified? ΑlphaΔeltaΘheta wrote: J++ had been dead already public class SanderRossel : Lazy<Person> { public void DoWork() { throw new NotSupportedException(); } } Matt U. wrote:as long as there is no work to be done Matt U. wrote:We can bring children and pets to work with us Sander Rossel wrote:I liked listening to the music on my iPod (200GB) through my speakers. The report of my death was an exaggeration - Mark Twain Simply Elegant Designs JimmyRopes Designs I'm on-line therefore I am. JimmyRopes JimmyRopes wrote:Obviously others didn't. JimmyRopes wrote:Use headphones. Sander Rossel wrote:Not since the last few months (when the new guy came). Sander Rossel wrote:My other colleagues now listen to the music I introduced them to in their spare time Sander Rossel wrote:That won't work for me since I'm constantly calling customers or explaining stuff to colleagues... I can have a bit of music on the background, but I can't have it injected directly into my ears. JimmyRopes wrote:(S)he has a right to not listen to music (s)he doesn't like while at work. JimmyRopes wrote:Respect them and don't go on about how you are offended. Sander Rossel wrote:That's what you make of it. I simply asked what other people do that makes work more like-able. Sander Rossel wrote:A sort of complete silence then? Richard MacCutchan wrote:I'm with the new employee on this; I have never uinderstood why certain people believed that everyone else wanted to listen to their music. dandy72 wrote:but playing music that everyone can hear is a choice, and one that can be avoided. dandy72 wrote:Your idea that headphones are not a solution because you're often on the phone doesn't float with me. If the phone rings, you just take off the headphones and pick up, and put them back on when you're done. I had a coworker who did that all day, and it didn't kill him, and he didn't suffer from any repetitive strain injury. Sander Rossel wrote:What do you guys do to have a little fun while at work? _Maxxx_ wrote:Sander Rossel wrote:What do you guys do to have a little fun while at work? Go home. General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Lounge.aspx?msg=4822788
CC-MAIN-2014-52
refinedweb
508
72.16
Deprecation Notice: The API feature documented on this page, is deprecated as of May 21, 2013. This feature is sometimes referred to as the Files API, and is going to be removed at some time in the future. It is replaced by the Google Cloud Storage Client Library. The documentation for the deprecated API is retained for the convenience of developers still using the Files API. The Google Cloud Storage API allows your application to store and serve your data as opaque blobs known as "objects". While Cloud Storage offers a RESTful API, this documentation describes how to use Cloud Storage on App Engine. - Introducing Google Cloud Storage - Prerequisites - Using Google Cloud Storage - Complete sample app - Quotas and limits Introducing Google Cloud Storage Google App Engine provides an easier way to read from and write to Google Cloud Storage objects , which allows applications to create and serve data objects. These objects are stored within buckets in Cloud Storage but can be additionally accessed by Google App Engine applications through the Google Cloud Storage API. You can interact with the Google Cloud Storage API using the RESTful interface or through the Google Cloud Storage Python API for Google App Engine applications, which is discussed in this document. Cloud Storage is useful for storing and serving large files because it does not have a size limit for your objects. Additionally, Cloud Storage offers the use of access control lists (ACLs), the ability to resume upload operations if they're interrupted, use of the POST policy document, and many other features. Once you have created an object, it cannot be modified. To modify an existing object, you need to overwrite the object with a new object that contains your desired changes. For more information, see the Google Cloud Storage pricing. Prerequisites To use the Cloud Storage API, you must complete the following prerequisites: - Google Cloud Storage API for Python is available for App Engine SDKs 1.5.5 and later. So, if you are using an older SDK, you need to download the latest SDK. For instructions to update or download the App Engine SDK, see the downloads page. - Activate Cloud Storage. Activate the Cloud Storage service in the Google Developers Console. - Set up billing. Google Cloud Storage requires that you provide billing information. For details about charges, see the Google Cloud Storage pricing page. - Create a bucket. Cloud Storage is made up of buckets, basic containers that hold your data. Buckets hold all your data in the form of objects, individual pieces of data that you upload to Google Cloud Storage. Before you can use the Google Cloud Storage API, you need to create a bucket(s) where you would like to store your data. The easiest way to do so is using the gsutil tool or the online Google Storage browser that is accessible through the Google Developers Console. - Give permissions to your bucket or objects. To enable your app to create new objects in a bucket, you need to do the following: - Log into the App Engine Admin Console. - Click on the application you want to authorize for your Cloud Storage bucket. - Click on Application Settings under the Administration section on the left-hand side. - Copy the value under Service Account Name. This is the service account name of your application, in the format application-id@appspot.gserviceaccount.com. If you are using an App Engine Premier Account, the service account name for your application is in the format application-id.example.com@appspot.gserviceaccount.com. - Grant access permissions using one of the following methods: - The easiest way to grant app access to a bucket is to use the Google Developers Console to add the service account name of the app as a team member to the project that contains the bucket. You can do this under Permissions in the left sidebar of the Google Developers Console. The app should have edit permissions if it needs to write to the bucket. For information about permissions in Cloud Storage, see Scopes and Permissions. Add more apps to the project team if desired. Note: In some circumstances, you might not be able to add the service account as a team member. If you cannot add the service account, use the alternative method, bucket ACLs, as described next. - An alternate way to grant app access to a bucket is manually edit and set the bucket ACL and the default object ACL, using the gsutil utility: - Get the ACL for the bucket and save it to a file for editing: gsutil acl get gs://mybucket > myAcl.txt - Add the following Entry to the ACL file you just retrieved: <Entry> <Scope type="UserByEmail"> <EmailAddress> your-application-id@appspot.gserviceaccount.com </EmailAddress> </Scope> <Permission> WRITE </Permission> </Entry> - If you are adding multiple apps to the ACL, repeat the above entry for each app, changing only the email address to reflect each app's service name. - Set the modified ACL on your bucket: gsutil acl set myAcl.txt gs://mybucket - You also need to set the default object ACL on the bucket. Many App Engine features require access to objects in the bucket, for example, the Datastore Admin backup and restore feature. To set the default object ACL on the bucket: - Get the default object ACL for the bucket and save it to a file for editing: gsutil defacl get gs://mybucket > myDefAcl.txt - Add the same entries that you added above to the bucket ACL, but replacing WRITE with FULL_CONTROL. - Set the modified default object ACL on your bucket: gsutil defacl set myDefAcl.txt gs://mybucket - If you need to prevent non-authorized applications from reading certain objects, you can: - Set the predefined project-private ACL on your objects manually - Store your objects in a bucket with the default project-private object ACL - Then, add the service account as a project viewer in the Google Developers Console, giving your App Engine application READ-ONLYaccess to your objects. You can also set the predefined public-read ACL, which allows all users, whether or not they are authenticated, access to read your object. You won't need to add your application's service account name as a project viewer, but if you have data you do not want to be publicly accessible, do not set the public-readACL on your object. Note: Setting READpermission only on your buckets does not provide READpermission to any objects inside those buckets. You must set READpermission on objects individually or by setting the default ACL before creating any objects in the bucket. Using Google Cloud Storage Applications can use Cloud Storage to read from and write to large files of any type, or to upload, store, and serve large files from users. Files are called "objects" in Google Cloud Storage once they're uploaded. Before you begin You can use the Cloud Storage API from your App Engine application to read and write data to Cloud Storage. In order to use the Cloud Storage Python API, you must include the following import statement at the beginning of your code: from google.appengine.api import files Creating an object To create an object, call the files.gs.create() function. You need to pass a file name, which must be of the form /gs/bucket_name/desired_object_name, and a MIME type: # Create a file filename = '/gs/my_bucket/my_file' writable_file_name = files.gs.create(filename, mime_type='application/octet-stream', acl='public-read') In this example, we also pass in the acl='public-read' parameter, as described below. If you do not set this parameter, Cloud Storage sets this parameter as null and uses the default object ACL for that bucket (by default, this is project-private). You can use the following optional parameters to set ACLs and HTTP headers on your object: The following code snippet provides an example using some of these optional parameters: params = {'date-created':'092011', 'owner':'Jon'} files.gs.create(filename='/gs/my_bucket/my_object', acl='public-read', mime_type='text/html', cache_control='no-cache', user_metadata=params) Opening and writing to the object Before you can write to the object, you must open the object for writing by calling files.open(), passing in the file and 'a' as parameters. Then, write to the object using files.write(): # Open and write the file. with files.open(writable_file_name, 'a') as f: f.write('Hello World!') f.write('This is my first Google Cloud Storage object!') f.write('How exciting!') The parameter 'a' opens the file for writing. If you want to open a file for read, pass in the parameter 'r', as described below. Finalizing the object Once you are done writing to the object, close it by calling files.finalize(): # Finalize the file. files.finalize(writable_file_name) Once you finalize an object, you can no longer write to it. If you want to modify your file, you will need to create a new object with the same name to overwrite it. Reading the object Before you can read an object, you must finalize the object. To read an object, call files.open(), passing in the full file name in the format '/gs/bucket/object', and 'r' as parameters. Passing 'r' opens the file for reads, as opposed to passing 'a', which opens the file for write. f.read() takes the number of bytes to read as a parameter: # Open and read the file. print 'Opening file', filename with files.open(filename, 'r') as f: data = f.read(1000) while data: print data data = f.read(1000) The maximum size of bytes that can be read by an application with one API call is 32 megabytes. Complete sample app The following is a sample application that demonstrates one use of the Cloud Storage API within an App Engine application. In order to successfully run the application, you must be an owner or have WRITE access to a bucket. The sample application demonstrates two different use cases of the Cloud Storage API: Making one-time requests The EchoPage function allows you to make a one-time request to create, write, and read to an object using the request format. Making multiple requests over time The CreatePage, AppendPage, and ReadPagefunctions create and maintain an event log that stores individual events as objects. This demonstrates how to use the Cloud Storage API to make multiple requests to an object. The main page of this application loads a form field with the name Title for the title of the event (and the object). After you provide a name and click the New Event Log button, the next page provides another form field to enter a message to write to the object. Enter your message and click Append Field. If you want to finalize the object, which means you cannot append to it later, check the Finalize log box. Your new object will appear on the main page. To set up and run this application: - Follow the instructions to create a simple Hello World app on the first Python Hello World page. - Edit your app.yamlfile and replace the value of the application:setting with the registered ID of your App Engine application. Replace the contents of helloworld.pywith the following sample code, replacing the parts where it asks for a bucket name. # Copyright 2011 Google Inc. All Rights Reserved. """Create, Write, Read and Finalize Google Cloud Storage objects. EchoPage will create, write and read the Cloud Storage object in one request: MainPage, CreatePage, AppendPage and ReadPage will do the same in multiple requests: """ import cgi import urllib import webapp2 from google.appengine.api import files from google.appengine.ext import db try: files.gs except AttributeError: import gs files.gs = gs class EchoPage(webapp2.RequestHandler): """A simple echo page that writes and reads the message parameter.""" # TODO: Change to a bucket your app can write to. READ_PATH = '/gs/bucket/obj' def get(self): # Create a file that writes to Cloud Storage and is readable by everyone # in the project. write_path = files.gs.create(self.READ_PATH, mime_type='text/plain', acl='public-read') # Write to the file. with files.open(write_path, 'a') as fp: fp.write(self.request.get('message')) # Finalize the file so it is readable in Google Cloud Storage. files.finalize(write_path) # Read the file from Cloud Storage. with files.open(self.READ_PATH, 'r') as fp: buf = fp.read(1000000) while buf: self.response.out.write(buf) buf = fp.read(1000000) class EventLog(db.Model): """Stores information used between requests.""" title = db.StringProperty(required=True) read_path = db.StringProperty(required=True) write_path = db.TextProperty(required=True) # Too long for StringProperty finalized = db.BooleanProperty(default=False) class MainPage(webapp2.RequestHandler): """Prints a list of event logs and a link to create a new one.""" def get(self): """Page to list event logs or create a new one. Web page looks like the following: Event Logs * Dog barking * Annoying Squirrels (ongoing) * Buried Bones [New Event Log] """ self.response.out.write( """ <html> <body> <h1>Event Logs</h1> <ul> """) # List all the event logs in the datastore. for event_log in db.Query(EventLog): # Each EventLog has a unique key. key_id = event_log.key().id() if event_log.finalized: # Finalized events must be read url = '/read/%d' % key_id title = '%s' % cgi.escape(event_log.title) else: # Can only append to writable events. url = '/append/%d' % key_id title = '%s (ongoing)' % cgi.escape(event_log.title) self.response.out.write( """ <li><a href="%s">%s</a></li> """ % (url, title)) # A form to allow the user to create a new Cloud Storage object. self.response.out.write( """ </ul> <form action="create" method="post"> Title: <input type="text" name="title" /> <input type="submit" value="New Event Log" /> </form> </body> </html> """) class CreatePage(webapp2.RequestHandler): """Creates a Cloud Storage object that multiple requests can write to.""" BUCKET = 'my-bucket' # TODO: Change to a bucket your app can write to. def post(self): """Create a event log that multiple requests can build. This creates an appendable Cloud Storage object and redirects the user to the append page. """ # Choose an interesting title for the event log. title = self.request.get('title') or 'Unnamed' # We will store the event log in a Google Cloud Storage object. # The Google Cloud Storage object must be in a bucket the app has access # to, and use the title for the key. read_path = '/gs/%s/%s' % (self.BUCKET, title) # Create a writable file that eventually become our Google Cloud Storage # object after we finalize it. write_path = files.gs.create(read_path, mime_type='text/plain') # Save these paths as well as the title in the datastore so we can find # this during later requests. event_log = EventLog( read_path=read_path, write_path=write_path, title=title) event_log.put() # Redirect the user to the append page, where they can start creating # the file. self.redirect('/append/%d?info=%s' % ( event_log.key().id(), urllib.quote('Created %s' % title))) class AppendPage(webapp2.RequestHandler): """Appends data to a Cloud Storage object between multiple requests.""" @property def key_id(self): """Extract 123 from /append/123.""" return int(self.request.path[len('/append/'):]) def get(self): """Display a form the user can use to build the event log. Web page looks like: Append to Event Title /--------------\ |Log detail... | | | | | \--------------/ [ ] Finalize log [ Append message ] """ # Grab the title, which we saved to an EventLog object in the datastore. event_log = db.get(db.Key.from_path('EventLog', self.key_id)) title = event_log.title # Display a form that allows the user to append a message to the log. self.response.out.write( """ <html> <body> <h1>Append to %s</h1> <div>%s</div> <form method="post"> <div><textarea name="message" rows="5" cols="80"></textarea></div> <input type="checkbox" name="finalize" value="1">Finalize log</input> <input type="submit" value="Append message" /> </form> </body> </html> """ % ( cgi.escape(title), cgi.escape(self.request.get('info')), )) def post(self): """Append the message to the event log. Find the writable Cloud Storage path from the specified EventLog. Append the form's message to this path. Optionally finalize the object if the user selected the checkbox. Redirect the user to a page to append more or read the finalized object. """ # Use the id in the post path to find the EventLog object we saved in the # datastore. event_log = db.get(db.Key.from_path('EventLog', self.key_id)) # Get writable Google Cloud Storage path, which we saved to an EventLog # object in the datastore. write_path = event_log.write_path # Get the posted message from the form. message = self.request.get('message') # Append the message to the Google Cloud Storage object. with files.open(event_log.write_path, 'a') as fp: fp.write(message) # Check to see if the user is finished writing. if self.request.get('finalize'): # Finished writing. Finalize the object so it becomes readable. files.finalize(write_path) # Tell the datastore that we finalized this object. This makes the # main page display a link that reads the object. event_log.finalized = True event_log.put() self.redirect('/read/%d' % self.key_id) else: # User is not finished writing. Redirect to the append form. self.redirect('/append/%d?info=%s' % ( self.key_id, urllib.quote('Appended %d bytes' % len(message)))) class ReadPage(webapp2.RequestHandler): """Reads a Cloud Storage object and prints it to the page.""" @property def key_id(self): """Extract 123 from /read/123.""" return int(self.request.path[len('/read/'):]) def get(self): """Display the EventLog to the user. Web page looks like the following: Event Log Title Event log description. [ Download from Cloud Storage ] """ self.response.out.write( """ <html> <body> """) # Use the get request path to find the event log in the datastore. event_log = db.get(db.Key.from_path('EventLog', self.key_id)) read_path = event_log.read_path title = event_log.title # Print the title self.response.out.write( """ <h1>%s</h1> """ % cgi.escape(title)) # Read the object from Cloud Storage and write it out to the web page. self.response.out.write( """ <pre> """) with files.open(read_path, 'r') as fp: buf = fp.read(1000000) while buf: self.response.out.write(cgi.escape(buf)) buf = fp.read(1000000) self.response.out.write( """ </pre> """) self.response.out.write( """ <div><a href="/">Event Logs</a></div> </body> </html> """) app = webapp2.WSGIApplication( [ ('/create', CreatePage), ('/append/.*', AppendPage), ('/read/.*', ReadPage), ('/echo', EchoPage), ('/.*', MainPage), ], debug=True) Upload your application using the following command: appcfg.py update helloworld/ View your application at Quotas and limits Cloud Storage is a pay-to-use service; you will be charged according to the Cloud Storage price sheet.
https://cloud.google.com/appengine/docs/python/googlestorage/
CC-MAIN-2015-11
refinedweb
3,036
57.77
Extract Landsat surface reflectance time-series at given location from google earth engine Project description Google Earth Engine data extraction tool. Quickly obtain Landsat multispectral time-series for exploratory analysis and algorithm testing Online documentation available at Introduction A python library (API + command lines) to extract Landsat time-series from the Google Earth Engine platform. Can query single pixels or spatially aggregated values over polygons. When used via the command line, extracted time-series are written to a sqlite database. The idea is to provide quick access to Landsat time-series for exploratory analysis or algorithm testing. Instead of downloading the whole stack of Landsat scenes, preparing the data locally and extracting the time-series of interest, which may take several days, geextract allows to get time-series in a few seconds. Compatible with python 2.7 and 3. Usage API The principal function of the API is ts_extract from geextract import ts_extract from datetime import datetime # Extract a Landsat 7 time-series for a 500m radius circular buffer around # a location in Yucatan lon = -89.8107197 lat = 20.4159611 LE7_dict_list = ts_extract(lon=lon, lat=lat, sensor='LE7', start=datetime(1999, 1, 1), radius=500) Command line geextract comes with two command lines, for extracting Landsat time-series directly from the command line. - gee_extract.py: Extract a Landsat multispectral time-series for a single site. Extracted data are automatically added to a sqlite database. - gee_extract_batch.py: Batch order Landsat multispectral time-series for multiple locations. gee_extract.py --help # Extract all the LT5 bands for a location in Yucatan for the entire Landsat period, with a 500m radius gee_extract.py -s LT5 -b 1980-01-01 -lon -89.8107 -lat 20.4159 -r 500 -db /tmp/gee_db.sqlite -site uxmal -table col_1 gee_extract.py -s LE7 -b 1980-01-01 -lon -89.8107 -lat 20.4159 -r 500 -db /tmp/gee_db.sqlite -site uxmal -table col_1 gee_extract.py -s LC8 -b 1980-01-01 -lon -89.8107 -lat 20.4159 -r 500 -db /tmp/gee_db.sqlite -site uxmal -table col_1 gee_extract_batch.py --help # Extract all the LC8 bands in a 500 meters for two locations between 2012 and now echo "4.7174,44.7814,rompon\n-149.4260,-17.6509,tahiti" > site_list.txt gee_extract_batch.py site_list.txt -b 1984-01-01 -s LT5 -r 500 -db /tmp/gee_db.sqlite -table landsat_ts gee_extract_batch.py site_list.txt -b 1984-01-01 -s LE7 -r 500 -db /tmp/gee_db.sqlite -table landsat_ts gee_extract_batch.py site_list.txt -b 1984-01-01 -s LC8 -r 500 -db /tmp/gee_db.sqlite -table landsat_ts Installation You must have a Google Earth Engine account to use the package. Then, in a vitual environment run: pip install geextract earthengine authenticate This will open a google authentication page in your browser, and will give you an authentication token to paste back in the terminal. You can check that the authentication process was successful by running. python -c "import ee; ee.Initialize()" If nothing happens… it’s working. Benchmark A quick benchmark of the extraction speed, using a 500 m buffer. import time from datetime import datetime from pprint import pprint import geextract lon = -89.8107197 lat = 20.4159611 for sensor in ['LT5', 'LE7', 'LT4', 'LC8']: start = time.time() out = geextract.ts_extract(lon=lon, lat=lat, sensor=sensor, start=datetime(1980, 1, 1, 0, 0), end=datetime.today(), radius=500) end = time.time() pprint('%s. Extracted %d records in %.1f seconds' % (sensor, len(out), end - start)) # 'LT5. Extracted 142 records in 1.9 seconds' # 'LE7. Extracted 249 records in 5.8 seconds' # 'LT4. Extracted 7 records in 1.0 seconds' # 'LC8. Extracted 72 records in 2.4 seconds' Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/geextract/
CC-MAIN-2020-40
refinedweb
629
61.83
IOS Multitasking on iPad I'm considering picking up the Pythonista app so that I can learn python while I'm on the move. Does anyone know if the app supports iOS multitasking? I'd like to have both Pythonista and my Python book at the same time. The app keeps running in the background for a while after you close it, so there should be no issues switching back and forth between the book and Pythonista. Even if the app stops running, it will save all open files and remembers which tabs you had, so even if that happens you won't lose anything. I can't say anything about the new multitasking features in iOS 9 (split screen and such) because Apple decided that my device is too old for that. Someone else probably knows. - Webmaster4o Pythonista does not support multitasking, I don't think. I don't have a split-view enabled device, but I know it doesn't support slide-over. However, if your book is web-based, you can open that in a side pane as a built-in feature of pythonista. It will appear as the same width as a slide-over on the right, but you'll be able to focus on and work in both simultaneously, i.e. you don't have to close the book to write code. If you want to do this once you buy it (if you buy it), simply open the console, import webbrowser;webbrowser.open("")and then put the console in "docked" mode. You should also be able to do this with PDF files, if that's what your book is. Pythonista is a great app, definately worth the purchase. I'd definately recommend it. Thanks for your suggestion. Opening the book (PDF) in the console sounds like a decent enough workaround. If it does support split-view, I'll be sure to come back and reply here. @dranobob I can help you with that, it may not be completely straightforward. If it's a file that isn't online publicly, you'll have to import it into the Pythonista file system before opening it. That takes a little effort, but nothing too bad. As to original question: You can have the narrow band on the side but not the iPad 50/50 multitasking split screen. I recall (but cannot retrieve details) that omz chose not to implement multitasking in 2.0 because that would limit Pythonista's game-playing capabilities @dranobob If your PDF is in iBooks, iBooks has very limited sharing options for PDFs. The simplest way I've found to import from iBooks is to email it to myself from iBooks, and then Mail has the option to open in Pythonista. A real inconvenience, but I have no power over iBooks 🙃 Once you have it imported, you can use something like import webbrowser,os webbrowser.open("file://"+os.path.expanduser("~/Documents/book.pdf")) If the PDF is online, it's much simpler. Without any importing, this will work: import webbrowser webbrowser.open("") Once you put the console in "docked" mode, it will look something like this: I am fully able to type in the code field without closing my book. That book is "Programming Computer Vision with Python," the free PDF of which I've imported to Pythonista locally as a file. You can zoom, in case that looks horrendously small to you. @Webmaster4o, I wasn't completely sure, so I checked. It's on Twitter and mentions split screen, not multitasking, making is less easy to find, but I found it via @viticci review @Webmaster4o, ah, the ambiguity of "it" ;-) I can have Pythonista as the main on the ¾ left-hand side of my iPad Air 2, and any (multitasking-capable) other app on the ¼ right-hand. Not the other way around, as only multitasking-capable apps can do so, and Pythonista isn't (as per previous post). However, your solution inside Pythonista is better as that remains if you return to the code, whereas the other way it disappears. @Olaf ah, clear now. I was looking between "Pixelmator" and "Reminders" and not seeing anything :) If this is true, that's a great alternative to docked console. That will be way better. On my Pythonista version 2.0.1 (201000) on iOS 9.2.1 on a 64-bit iPad5,4 with a screen size of (1024 x 768) * 2 @ccc this is SlideOver. We were talking about full multitasking with a 3:1 ratio. SlideOver is not ideal, because one cannot type code without closing the book.
https://forum.omz-software.com/topic/2665/ios-multitasking-on-ipad/
CC-MAIN-2019-51
refinedweb
768
72.36
After a wait of so many updates, Python has finally introduced a switch-case like structure in its latest 3.10 version. If we talk about other programming languages like, C++, Java, and JavaScript all these three popular programming languages support switch case statement, which is an alternative to write efficient and cleaner conditional statement. Let's see an example of Switch Case statement in C++ Switch Case Statement in C++ #include <iostream> using namespace std; int main() { int http = 200; switch (http) { case 200: cout<<"OK"; break; case 201: cout<<"CREATED"; break; case 202: cout<<"ACCEPTED"; break; case 400: cout<<"BAD REQUEST"; break; case 404: cout<<"NOT FOUND"; break; case 503: cout<<"SERVICE UNAVAILABLE"; break; default: cout << "Error! HTTP Code is not valid"; break; } return 0; } OUTPUT ok The above code is very clean example of conditional statement. The switch case comes very handy when we have a conditional operation based on a single data object. Python Structural Pattern Matching In Python 3.10, the core developer team of Python introduced a new conditional statement syntax Structural Pattern Matching, which is a similar syntax to the switch case statement present in the other programming languages. Although Python contain if..else and if...elif...else statements to write conditional statements, but the all new Python Structural Pattern Matching provides a more elegant and legible way to write some conditional statement. Syntax match subject: case pattern1: #case 1 code block ..... .... ... case patternN: #case N code block Keywords matchis the keyword here. subjectis the value that need to be match. caseis also a keyword patternis the value that will be match with subjectif any case pattern matches the match subjectthat case code block will be executed. Example http = 200 match http: case 200: print("OK") case 201: print("CREATED") case 202: print("ACCEPTED") case 400: print("BAD REQUEST") case 404: print("NOT FOUND") case 503: print("SERVICE UNAVAILABLE") case _: print("Error! HTTP Code is not valid") Output OK Conclusion The new Python match case statement is an alternative of the switch case statement present in the other programming languages. Although the switch case statement provide an elegant way to write conditional statement, still for complex and multilayer conditional statement it is not a good option. It can only be used when the condition expression is a single value. Discussion (2) This is totally missing the mark. The match/case statement is not just a glorified switch/case. Maybe you should actually read the PEP 622 instead of writing an article based on assumptions. PEP 622 says the pattern matching statement is inspired by the similar syntax found in Scala, Erlang, and other languages. And Scala itself compares its PATTERN MATCHING syntax with Switch Case statements. As the standard Python also does not support core Array data structure, still we compare Arrays with Python’s List which are poles apart. The objective of this article is just to tell that Python now supports a similar syntax to the Switch Case statement that is already supported by its biggest rivals. Peace out....
https://dev.to/khatrivinay/python-310-structural-pattern-matching-match-case-35dh
CC-MAIN-2022-05
refinedweb
509
60.24
First entry into the “Swift 2 to 3” challenge comes from Cristian Filipov, who brings me a routine to extract words from phone numbers. There are several points of interest in this port, which I’ll get to in just a second, but since his code didn’t arrive with the vital isWord(string:) function, I had to build one myself. Building isWord It’s in Cocoa because I find that writing OS X Command Line apps are the most congenial way to build small Swift 3 apps. At this point, playgrounds (as you see, his code was originally intended for playground use with the in-line markup) do not support Swift 3. That should change within the next two weeks but I didn’t want to wait for WWDC to start showing tricks of the transition trade. So here’s the function in question: import Cocoa func isWord(string: String) -> Bool { // If it's a number, nope if let _ = Int(string) { return false } // Use NSSpellChecker to find misspelling // if it fails, the string is proper let range = NSSpellChecker.shared() .checkSpelling(of: string, startingAt: 0) return range.location == NSNotFound } Currying Christian’s code heavily depends on currying, which is one of the easiest points of transition in Swift 2 to Swift 3 code. Here’s an example: func transform<T: Hashable, V>(dict: [T:V])(element: T) -> V? { return dict[element] } Establishing the dictionary is curried from looking up an element in the dictionary. How to fix? - Place an arrow between each curried element - Use “ return { argument in...}” closures for each curry Here’s the fixed example func transform<T: Hashable, V>(dict: [T:V]) -> (element: T) -> V? { return { element in return dict[element] } } Mandated Function Parens This is one of the Swift 3 changes I was really excited to see adopted. Prior to Swift 3, you could specify types of T -> U. Now it’s uniformly (T) -> U. So this example: func not<T>(pred: T -> Bool)(e: T) -> Bool { return !pred(e) } becomes the following (with some bonus curry update): func not<T>(pred: (T) -> Bool) -> (e: T) -> Bool { return { e in return !pred(e) } } Taking Charge of Parameter Labels With Swift 3’s new mandated first parameter labels, it’s time to toss away duplicated names and add in first parameter labels that normally defaulted away. Starting here: func phoneWords(minLength minLength: Int)(number: String) -> [String] { if number.characters .filter(("2"..."9").contains) .count >= minLength { return phoneWords(number) } else { return [number] } } Ending up here: func phoneWords(minLength: Int) -> (number: String) -> [String] { return { number in if number.characters .filter(("2"..."9").contains) .count >= minLength { return phoneWords(number: number) } else { return [number] } } } Other tweaks I had to fix the isSeparator closure (needed a closure and a first parameter), and add in one or two more parentheses around parameter types but other than the mystifying spellchecker that insists that “eloydqs” is a word just like “flowers”, everything seems to work beautifully You can find the diffed/forked gist here. Got a short standalone Swift 2.2 code sample that needs updating to new syntax and concepts? Send it along and I may do a post on it. Please no requirements outside the sample, and keep the code short. Code that introduces new kinds of issues (for example, currying is pretty much already covered now) will be preferred. 9 Comments Wow, don’t know how I missed that. Updated the gist to include the isWord function I forgot to include: You can also use UIKit’s text checking, would simplify Yeah, I like your method better, just felt the need to correct the accidental omission. By the way, I thought this was no longer supposed to be possible in Swift 3: .map(String.init) Doesn’t that essentially make use of currying? “Curried function syntax has been deprecated, and is slated to be removed in Swift 3.0.” Not all currying functionality and not this particular use, just the declaration functionality syntax. I swear I saw mention of this specific use being deprecated too. But I can’t find it now so I must be mistaken. Erica, how can I filter a string in Swift 3.0 for only English Words and names? Any points in the right direction? Depends if it is single words, multiple words, case insensitive, dictionary membership, etc. Cocoa and Cocoa Touch have a number of classes that can help including NSLinguisticTagger and NSSpellChecker Thanks Erica, will check those out!
https://ericasadun.com/2016/06/03/swift-from-two-to-three-currying-favor/
CC-MAIN-2020-40
refinedweb
744
62.48
have this class on my project and I don't reference Mono.Android.Export.dll I get a non actionable error message. Class: public class Parcelable<T> :Java.Lang.Object { [ExportField("STUFF")] public static void Stuff() { } } Error message: /Library/Frameworks/Mono.framework/External/xbuild/Xamarin/Android/Xamarin.Android.Common.targets: error : Error executing task GenerateJavaStubs: Failed to create JavaTypeInfo for class: AndroidGenerics.Parcelable`1 If I run xbuild with /verbosity:diagnostic I get what I need, but this is not usable by regular users: Error executing task GenerateJavaStubs: System.ApplicationException: Failed to create JavaTypeInfo for class: AndroidGenerics.Parcelable`1 ---> System.InvalidOperationException: You need to add a reference to Mono.Android.Export.dll when you use ExportAttribute or ExportFieldAttribute. Going further, XS Errors pad gets it completely work. It shows the erros message and point the broken file to be Xamarin.Android.Common.Target. Double clicking it is extremely confusing. Finally, if I try to edit the opened file and save I get a cryptic XS exception due to: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.UnauthorizedAccessException: Access to the path "/Library/Frameworks/Mono.framework/External/xbuild/Xamarin/Android/.#Xamarin.Android.Common.targets" is denied. This was fixed in monodroid/7f6dfe69 as part of the fix for Bug #10135, and will now generate XA4207 ("[ExportField] cannot be used on a generic type") and (possibly) XA4208, "[ExportField] cannot be used on a method returning void.". Sorry; I misread the bug, and Comment #2 does not apply. This was fixed in monodroid/b692b221, and will now generate error XA4210 "You need to add a reference to Mono.Android.Export.dll when you use ExportAttribute or ExportFieldAttribute." Today we have checked this issue on following builds : XS 4.0.9 (build 12) X.Android 4.7.11002 When we run the given code in XS then we get error message as given in comment 2. But we are still not able to get error message as in comment 4. Please suggest us how to get error message as per comment 4 to verify this issue. @Saurabh: XA4210 is generated at package creation time. Thus: 1. Create a new project. 2. Add a new method which uses [Export], e.g. [Java.Interop.Export] void Foo () {} 3. Build. This will succeed w/o error. 4. Install the project onto a device. (4) should fail with XA4210. Thanks Jonathan. Now we are getting expected result as per comment 6 with following builds : XS 4.0.9 (build 12) X.Android 4.7.11002 Hence closing this issue. Changing its status to verified.
https://xamarin.github.io/bugzilla-archives/12/12504/bug.html
CC-MAIN-2019-47
refinedweb
432
52.66
How to include RF24 and RF24Network libraries into my package on RaspberryPi What is the right procedure to include these libraries into my ROS package? I have to create a .cpp file (called for example broadcaster.cpp) in my package(called for example mypackageexample) that is something similar to: #include <ros/ros.h> #include <tf/transform_broadcaster.h> #include <RF24/RF24.h> #include <RF24Network/RF24Network.h> int main() { //mycode } return 0; At this moment I am using VSCode and its plugin to develop with ROS. The link for the libraries are: and This package could be distributed and should work also on a raspberry pi different from mine. Thanks in advance for your time.
https://answers.ros.org/question/331481/how-to-include-rf24-and-rf24network-libraries-into-my-package-on-raspberrypi/
CC-MAIN-2019-39
refinedweb
113
61.02
Pikmin 2: FAQ/Walkthrough by The Sound Defense Version: 0.7 | Updated: 2006-12-16 | Original File ____ _ _ __ _ _ _ _ _ ____ | _ \ | | | | / / | \ / | | | | \ | | | \ | |_| | | | | |/ / | \ / | | | | \ | | |___ | | __/ | | | / | \/ | | | | \| | ___| | | | | | | \ | |\ /| | | | | |\ | | __/ | | | | | |\ \ | | \/ | | | | | | \ | | |___ |_| |_| |_| \_\ |_| |_| |_| |_| \_| |_____| Pikmin 2 FAQ/Walkthrough Copyright 2004 - Basics 2.1 - Characters 2.2 - Controls 2.3 - The Pikmin 3 - Walkthrough (I) 3.1 - Valley Of Repose 3.2 - Awakening Wood 3.3 - The Perplexing Pool 3.4 - Return To Awakening Wood 3.5 - Return To Valley Of Repose 3.6 - Return To The Perplexing Pool (N) 3.7 - Wistful Wild (N) 4 - Frequently Asked Questions 5 - Thanks To... 6 - Legal Info (I) = Incomplete (N) = Not started ---------------------------------------------------------------------- ---------------------------------------------------------------------- 1 - Version History Version 0.2 (3:58 AM EDT 9/12/2004) - Done up through the first trip to Awakening Wood. More to come. Version 0.4 (10:40 PM EDT 9/21/2004) - An update? *gasp* Yea, I found time to complete more stuff today. Next update's ASAP. Version 0.5 (1:54 AM EDT 10/3/2004) - Beat the game myself the other day on another file, but I've only got the rest of the Awakening Wood for you folk. Version 0.7 (7:26 PM EDT 10/4/2004) - Trying to go at a steady pace, Return to Valley of Repose is wrapped up. ---------------------------------------------------------------------- ---------------------------------------------------------------------- 2 - Basics ---------------------------------------------------------------------- 2.1 - Characters Captain Olimar - The hero of the original Pikmin has returned to their planet in order to save his failing company. Louie - Your stereotypical bumbling idiot, Louie botched a really important delivery, and needs to aid Olimar in rectifying his mistake. President - The Prez of Hocotate Freight's looking to save his company from bankruptcy. The Ship - Your new ship can talk, and it's got a lot of advice to dispense; disregard its yes-man disposition. ---------------------------------------------------------------------- 2.2 - Controls Start - Enter pause menu Control stick - Move cursor/captain A - Punch; pluck Pikmin; pick up/throw Pikmin; enter/exit caves B - Call Pikmin C-stick - Command Pikmin toward certain direction X - Separate Pikmin/captains Y - Switch captains Z - Change camera angle (bird's-eye/third-person) L - Center camera behind captain R - Zoom in/out D-pad up - Use ultra-bitter spray (stun enemy); switch leaf/bud/flower Pikmin (while holding one with A) D-pad down - Use ultra-spicy spray (speeds up, strengthens Pikmin); switch leaf/bud/flower Pikmin (while holding one with A) D-pad left/right - Switch Pikmin (while holding one with A) ---------------------------------------------------------------------- 2.3 - The Pikmin Red - The first color you'll find. They're the best fighters, and are fire-resistant. Purple - One of two new colors, these are basically sumo Pikmin. Each one has the strength and weight of 10 normal Pikmin, but are really slow. White - The other newcomers. These guys are really fast, poisonous and poison-resistant, and can dig up buried treasure when necessary. Yellow - These guys don't have bomb-rocks to hold anymore, but they're now resistant to electricity, and can still be thrown highest. Blue - They can swim. Bulbmin - You'll find these Pikmin/Bulborb hybrids in caves. When you kill their leader, you can command them with your other Pikmin. ---------------------------------------------------------------------- ---------------------------------------------------------------------- 3 - Walkthrough While Olimar was trying to survive on Earth in the original Pikmin, his company, Hocotate Freight, had to send another employee, Louie, on a job delivering golden Pikpik carrots. Unfortunately, a huge space bunny devoured the entire load, and Hocotate Freight had to take out a loan of enormous proportions, starting them on the road to bankruptcy. However, upon Olimar's return (shortly after his ship is reposessed), they discover that a simple souvenir from the other planet is worth a whole 100 pokos! The president of the company sends Olimar and Louie back to the planet to get enough treasure to repay the other 10,000 pokos. And thus our adventure begins... Note: I was going to organize it so there was one section for each level, but I decided to make it so you could read straight through without hopping about (since you can't get everything at once in any level, except the last). Also, treasures will be listed in this manner: Proper Name (what it is; ### pokos) This walkthrough is not spoiler-free. ---------------------------------------------------------------------- 3.1 - Valley Of Repose -- The First Day -- You'll end up making a near-crash landing in the Valley of Repose, seperating Olimar from Louie. You'll start out as the former, and the ship will point out some Pikmin in battle. Call them over with B (you'll be instructed), then us the C-Stick to swarm the Bulborb and kill it. The ship will then find Louie, so press Y to switch to him. Run up the slope to encounter the red Onion. Pluck the Pikmin that appears with A, then have it knock down all of the flowers around the Onion and produce more Pikmin. Once you've got 11, head down the other path (past the battery, which the ship will make a fuss over) to the paper bag. Throw all of your Pikmin on, then switch to Olimar and have him throw his on. Reunited, have the Pikmin take the Bulborb to the Onion to produce just enough Pikmin to dig the battery out and carry it back to the ship; it will be appraised as the Courage Reactor (280 pokos). So ends day one. -- All Proceeding Days -- The next day, take your Pikmin and gather more from all of the flowers in the area. Once you're done (you should have 42), take them to the other paper bag and flatten it. Swarm the Dwarf Bulborb to kill it, then sneak up behind the large Bulborb and throw Pikmin on its back unitl it dies (you shouldn't lose any). Take their bodies back for more Pikmin if you'd like, then go back and grab the Utter Scrap (crushed can; 170 pokos). Take them all back and order them toward the stick wall to break it down. Head toward the hole in the ground and the ship will make a remark, then go up to it and press A to enter the Emergence Cave. -- Emergence Cave -- Necessary Pikmin: red Sublevel 1: Separate all the Pikmin and go up to the hole in the next area with just Olimar to see a cutscene (to prevent the beasts from getting your Pikmin). Go back and get them, then kill all of the beasts and bring them back to the pod (they're worth something), along with the Quenching Emblem (bottle cap; 100 pokos) and the Citrus Lump (orange; 180 pokos). Continue to the next floor. Sublevel 2: Swarm two Bulborbs, then pass the globe (you need 101 Pikmin for it) and continue on until you reach the purple Candypop Buds. Throw 5 Pikmin into each one, and they'll come out as purple Pikmin; each one has the strength of 10 Pikmin. Pluck them all, then go back and retrieve the Spherical Atlas (globe; 200 pokos), which will become the Sphere Chart and let you access the next area. Grab the rest of the beasts, then go to the geyser and press A to exit the cave. -- Outside the cave again, the ship will make a big fuss, then the day will end. You're done getting treasure here until a bit later. ---------------------------------------------------------------------- 3.2 - Awakening Wood Upon landing, grab your red Pikmin and kill all of the Bulborbs in the area in front of the ship. Once that's done, get the Sunseed Berry (strawberry; 170 pokos) from the elevated area. Go up the slope near the ship and use the Pikmin to grab the berries from the plants there; ten of them will get you an Ultra-Spicy Spray that can temporarily strengthen and speed up your Pikmin. Go back and knock down the wall, then kill the enemy behind the wall by swarming it. Take the left path (watch out for the giant plant enemy) and go right to find the Hole of Beasts. -- Hole Of Beasts -- Necessary Pikmin: red, purple Sublevel 1: A simple level. Go forward and kill the sheargrubs that appear, then grab the Stone Of Glory (d-pad; 100 pokos) and go on to the next floor. Sublevel 2: Only things here are two more purple Candypop Buds; get yourself 10 more purple Pikmin and head on down. Sublevel 3: There are fire spouts all over the place; take your fire- resistant red Pikmin to disable them all, then get the Strife Monolith (Mah-Jong tile; 150 pokos) and the Cosmic Archive (floppy disk; 230 pokos). Sublevel 4: You'll need your red Pikmin to take out fire spouts here. Kill the Bulborb here to get the Dream Architect (Game and Watch; 280 pokos), then get the Luck Wafer (playing card; 140 pokos) near the Candypop Bud (5 more purple Pikmin). Sublevel 5: This'll be your first boss, the Empress Bulblax. Take your purple Pikmin and throw a few on her to wake her up. Throw some on her face; then call them off when she tries to shake them off. Once she starts shaking wildly, call them off and keep them off until she stops rolling around. She'll die eventually, and will leave behind the Prototype Detector (Love Tester; 200 pokos); the ship will derive from it the Treasure Gauge, which will alert you when treasure is near. Head outside. -- Back out, head back along the path toward the Hole of Beasts, but instead of taking a left past the old wall, head forward and flatten the paper bag. Kill the enemy here, then head into the next cave, the White Flower Garden. -- White Flower Garden -- Necessary Pikmin: red, purple Sublevel 1: Watch out when throwing Pikmin around here, they can fall to their deaths. Swarm all of the sheargrubs around here, then grab the Alien Billboard (shoe polish; 80 pokos). Sublevel 2: Go around with your red Pikmin and take out the Fiery Blowhogs here, then throw some Pikmin down (if necessary) to the Petrified Heart (jewel; 100 pokos) and grab the Drought Ender (bottle cap; 100 pokos). Sublevel 3: Nothing here but three white Candypop Buds; throw some red Pikmin into these to get white Pikmin back out. Once you've got 15, use your Treasure Gauge to track down a treasure, and the white Pikmin will dig it up. Haul the Superstick Textile (masking tape; 80 pokos) back to the pod. Sublevel 4: Use your white Pikmin to take out the poison spouts, then grab the Survival Ointment (chapstick; 90 pokos) and the Toxic Toadstool (mushroom; 30 pokos). Sublevel 5: Prepare yourself for the easiest boss fight ever. Take a smallish number of red Pikmin (like 25) into the next area, and the Burrowing Snagret should pop out. If he comes out all at once (up to the neck), run away. If he pokes his beak out, throw your Pikmin on him. Rinse and repeat. He'll go down like a sack of potatoes. You get from him the Five-man Napsack (glove; 100 pokos), which in turn becomes the Napsack; hold X to take a nap, and a couple of Pikmin will take you back ot the Onion. I, like most of the world, am mystified by what purpose this could possibly serve. humber_pig@hotmail.com suggests: "The nap function I have found very usefull it allows me to send one of the leaders back to the ship or onions with out leading him there. so I can continue useing the other one." -- Once you're outside again, take your army (reds, purples, whites) and head back to where the White Flower Garden was. Have your white Pikmin break down the wall and destroy the poison spouts (note: it takes 15 Pikmin forever squared to knock down a wall). Go over to the blocks and throw a single red on the raised block, then stand on the lower one and throw all of the others on the ledge. The lower block will eventually rise, so call your Pikmin and head forward to some purple berries. Have some Pikmin gather these, and have a few more get the Chance Totem (die; 100 pokos) from the ledge. After a bit, the berries will grow back, so pick them again and you'll get a helping of Ultra-Bitter Spray to paralyze the enemy. Get all of your Pikmin (don't forget that one red) and head back to the Hole of Beasts and go the opposite way at the T-split to find another poison wall; use whites to knock it down. Bring the rest along to roll out a bridge (watch out for a Creeping Chrysanthemum), and you can transport the Geographic Projection (globe; 200 pokos) to the ship, creating the Survey Chart and opening up The Perplexing Pool. This should exhaust your options for this area without yellow or blue Pikmin. No, you can't get the blue Pikmin yet. ---------------------------------------------------------------------- 3.3 - The Perplexing Pool This place seems like a later form of Pikmin's Distant Spring. Anyway, our first task is getting ourselves some yellow Pikmin. If you go forward a bit, the ship will alert you to their presence. Grab all your whites and maybe 50 reds. Go down the slope, then left. Sneak up on the Yellow Wollywog and throw Pikmin on until he turns around, then run. Your Pikmin will kill him by the time he lands. Continue on to the blocks; throw a red on one, throw the rest on the ledge. Take the Pikmin on the ledge and go forward to the Fiery Bulblax (if a Snitchbug takes your Pikmin, throw more Pikmin on it, then swarm). Separate your Pikmin and take your reds to the Bulblax, then continually throw them on until he dies. You can have reds haul stuff back if you want, then take your white Pikmin and knock down the poison wall. Once they're done, go forth alone to the tree with the yellow Pikmin; call them down, then have them get all of the yellow flowers here to generate a total of 24 yellows. Go back and get your reds, then take them past the entrance to the yellow Pikmin area, toward a Fiery Blowhog. Defeat it, then have them unfurl the bridge. Take a few yellow Pikmin (10 at least) to the bridge and go toward the large stump near it. Go around until you're up higher, then throw the Pikmin up to the Impediment Scourge (bottle opener; 50 pokos) and they'll bring it back. Go back there with yellows, to the weird platforms, and go to the very left, near a ramp. Throw the yellow Pikmin up, then walk up the ramp. Carefully walk along the left edge until you come to a dead end, then throw the Pikmin up to the Gherkin Gate (pickle jar top; 100 pokos). Go back once again with all of your yellow Pikmin and walk back toward where the blocks were, then knock down the nearby electric fence. Once it's all down, get some more Pikmin (reds, purples, maybe) and enter the Glutton's Kitchen. -- Glutton's Kitchen -- Necessary Pikmin: yellow Recommended Pikmin: red, purple Sublevel 1: Interesting level...anyway. Dwarf Bulbears are everywhere. Kill them however you wish (I prefer throwing purples on them), then grab the Master's Instrument (crayon; 30 pokos). Sublevel 2: The Breadbug makes his reapparance here. He'll try to steal your stuff, but if you swarm the item he's carrying you can drag him back to the ship and do serious damage (do not try this with Sheargrubs). Otherwise, just throw Pikmin on him. If he drags a Pikmin back to his hole, it will die, but if you kill the Breadbug, its hole will disappear, and sometimes treasure will come out. Grab the Imperative Cookie (swirly cookie; 25 pokos) and the Massive Lid (bottle cap; 100 pokos). Sublevel 3: You'll want to run around with your yellows for a bit, destroying electric traps and killing Anode Beetles (throw them on). There's also a Puffy Blowhog, and more Breadbugs. Here's a strategy: kill anode beetle, bring it near ship, have Breadbug grab, swarm, kill Breadbug. One of the Breadbugs is holding a treasure, either the Harmonic Synthesizer (castanets; 120 pokos) or the Director Of Destiny (broken compass; 100 pokos). Sublevel 4: Some Breadbugs are running around, as well as a Bulbear and some Dwarfs. Kill them off, and get the Happiness Emblem (bottle cap; 100 pokos); the Bulbear will come back to life unless you bring him to the ship quickly. There's also an Invigorator (coffee mug; 130 pokos) outside the boundaries a little, and a White Goodness (white chocolate; 60 pokos) up on a ledge; use yellows to get it. Sublevel 5: Some Cannon Beetles are wandering about; using their rocks to kill enemies is always fun. Afterward, take care of them (throw Pikmin in front of them between rocks), then collect the Boom Cone (party hat; 100 pokos) and the Sulking Antenna (portable antenna; 150 pokos). Sublevel 6: The boss level pits you against a Giant Breadbug. You can lure him back to your ship, as always, but use only yellows due to the electric traps and beetles; two whacks will do it. Also kill the Anode Beetles and Breadbugs for cash and perhaps treasure. Treasures here include the Hideous Victual (egg; 100 pokos), the Sweet Dreamer (donut; 40 pokos), the Meat Of Champions (ham; 35 pokos), and the Dream Material (eraser; 100 pokos) which comes out of the Giant Breadbug. This will give you the Anti-electrifier, making you invincible to electric attacks. Once done, leave. -- Okay, you're back outside. There's a cave right next to the landing site, the Citadel of Spiders. Get some reds, whites, yellows, and purples and head in. -- Citadel of Spiders -- Necessary Pikmin: red, yellow Recommended Pikmin: white Sublevel 1: Not much here; some Sheargrubs, and some leaf enemies (throw one Pikmin on and it dies). The only treasure around is the Love Nugget (tomato; 40 pokos). Sublevel 2: I recommend running around with reds to take out the flame traps. There are a couple of Wollywogs around, not too much trouble; one's holding a Creative Inspiration (bottle cap; 100 pokos). Some flame Dweevils (spiders) will be lurking about, picking up treasures. Get the Lip Service (lipstick; 50 pokos) and the Paradoxical Enigma (duck head; 80 pokos). Break down the wall to get to the exit. Sublevel 3: A level for yellows. Anode Beetles and Snitchbugs abound. The treasures are the Patience Tester (water chestnuts can; 130 pokos) and the Memorial Shell (shell; 100 pokos). Sublevel 4: We've got some blue enemies going round that pretty much instantly kill Pikmin; I used Olimar to kill them. I also used him to kill the crab-thing (lure him out, attack his butt). Otherwise, fire spouts make red Pikmin excellent for exploring. You can find a Flame of Tomorrow (matchbox; 10 pokos), and there's a Time Capsule (locket; 70 pokos) somewhere, and one of the crabs is holding a King of Sweets (dark chocolate; 15 pokos). Sublevel 5: This final level pits you against a Beady Longlegs. About 15 Pikmin (try not to use whites) should suffice. Take them and throw them on his body when he rests, then call them off before he spins. Don't let him squish your Pikmin. He'll drop The Key (key; 100 pokos), which will unlock Challenge Mode. Use your white Pikmin to dig up a Regal Diamond (diamond; 100 pokos) on a ledge, then leave. -- You're done with the Perplexing Pool for now. You should have about 5000 pokos by now. ---------------------------------------------------------------------- 3.4 - Return To Awakening Wood With yellows in tow, you can finally get the blue Pikmin. Grab all of your whites from the ship (and others, if you have less than 20) and go left of the ship to the flowerpots. Go around to the slope and go up, then throw whites into the upper pot to uncover the Pilgrim Bulb (bulb; 55 pokos); throw yellows onto it to get it down. Once it's back, put the whites away and grab all the yellows, then head toward the two caves (swarm the mold if it's there). On the way, you'll pass a stump with a Healing Cask (Carmex lip baum; 60 pokos); throw some yellows up to bring it back. Go back when they're done and head toward the White Flower Garden. Separate the Pikmin and go through the water alone, then use Olimar to kill the Burrow-nit near the electric fence. Go back and throw the yellows onto the ledge, then have them knock down the electric fence (you might want to throw them on). Go through and whistle the blue Pikmin off of the enemy, then have them kill it (not easy). Collect all of the flowers/enemies here to get max Pikmin, then have them return the Decorative Goo (paint tube; 80 pokos) to the ship. Once there, take out all the whites and purples, then put back yer blues (e-mail me if you get that reference and I'll put your name here - first five only!) and all but 20 yellows and take out as many reds as you can. Take only your blues toward the wall that's in the water (to the right of the path to the other two caves). Have them break the rock in the ground to drain the water, then take all your Pikmin over to break the wall. Go forward and throw your yellows up to break the electric fence, then take the other Pikmin up to the entrance via the stump bridge on the other side. Enter the Bulblax Kingdom. -- Bulblax Kingdom -- Necessary Pikmin: red, yellow, white Recommended Pikmin: purple Sublevel 1: There's a red Candypop Bud here, but who cares. Kill off the orange Bulborbs by throwing Pikmin on its back when it's facing away (purples are always nice for this); you can lure it out if you want, then it'll turn around when it gives up on you. You can kill it with Olimar if you want, but it takes a while without the Rocket Fist from later. One of them has the Crystal Clover (emerald broach; 150 pokos). Sublevel 2: This here's red Pikmin country. Fiery Dweevils and flame spouts abound; take them out and collect the Tear Stone (gemstone; 150 pokos). It may be up on the high ledge; to get it, throw reds onto the lower end, then go into the alcove, call them and direct them to the treasure, and they'll probably take out the flame spouts as well. Sublevel 3: Nothing here can kill you, luckily, but dang, those Blowhogs are annoying. Approach them from behind and throw Pikmin on to kill them without losing flowers. You can turn 5 reds into whites here, but you probably won't need that many to dig up the Olimarnite Shell (seashell; 40 pokos). Sublevel 4: You can turn 10 reds to purples here, and you'll want to for later. We've got some Anode Beetles here for yellows to kill, plus some electric traps, a gold Flint Beetle, and a gray Wollywog, the latter two of which hold the Unknown Merit (tablet; 100 pokos) and the Crystal King (crystal; 110 pokos). Sublevel 5: More Orange Bulborbs. There's an Anxious Sprout (closed pinecone; 50 pokos) to be dug up here, but watch out for the falling bomb-rocks, unless you're using them to kill Bulborbs. Sublevel 6: Still more Orange Bulborbs here, and they've thrown in some Fiery Dweevils to annoy me. There's red and purple Candypop Buds here; I would use the latter. Bomb-rocks still fall around here, near treasures sometimes, so keep on your toes. You can get the Colossal Fossil (skull; 140 pokos) here, and an Orange Bulborb holds the Eternal Emerald Eye (emerald broach; 150 pokos). Sublevel 7: Here you're fighting a fairly watered-down Emperor Bulblax that you can actually defeat in seconds. Use reds to disarm the traps leading up to him, then take purples and reds and throw them between its eyes (as always, start with purples). Keep throwing, and he'll die with no trouble at all. If you fail, run away and he'll go back to sleep; if you have to, throw Pikmin onto his face and watch out for his tongue. He'll leave behind the Forged Courage (robot; 100 pokos), which will turn into the Scorch Guard, which makes you invincible to fire. Once that is stored, knock down the far wall, then take reds along the right side and throw them onto the ledge. Go up the slope, then call them over to collect the Gyroid Bust (statue; 250 pokos). Leave via the geyser. -- Back outside, you'll need an army with at least 31 blues and all of your whites. Head to where you got the Geographic Projection (left at the Hole of Beasts) and keep going to the water. Use the blues to take out the Wollywog and unfurl the bridge. Have the whites unfurl the poison bridge and destroy the poison flumes, then take out the other Wollywog. Take the blues and both captains over to the block next to the wall, then throw at least 15 Pikmin on it, but it must be less than half of the blues (no going 50-50). Put one captain on with them, then take the other captain and throw the rest of the blues on the other block near the bridge. Switch back to the other captain and throw the blues up to the Air Brake (shuttlecock; 100 pokos) and bring it back, completing the above-ground treasure hunt here. Return to the poison bridge with an all-colored army of 76 Pikmin (you can get 24 from Queen Candypops in the cave). Take only about 15-20 agile ones (and by agile, I mean not purple) over to fight a Burrowing Snagret. Once he's gone, knock down the wall and enter the Snagret Hole. -- Snagret Hole -- Necessary Pikmin: yellow, blue, white Recommended Pikmin: red, purple Sublevel 1: Some Sheargrubs are around here, and these can actually kill your Pikmin, so be quick in killing them. Kill off the Orange Bulborb to get the Crystallized Telekinesis (marble; 120 pokos), then go up the long path to get the Levaithan Feather (feather; 10 pokos) and go down. Sublevel 2: Bunch of enemies here, including Creeping Chrysanthemums, Burrow-nits and Sheargrubs. Take them out and collect the Combustion Berry (strawberry; 190 pokos) and the Taste Sensation (sushi; 40 pokos). There's a white Candypop Bud here, too, if you want to utilize it. Sublevel 3: There's two Burrowing Snagrets around here; this should be easy for you by now, and one's got a Meat Satchel (hot dog; 40 pokos). Kill the Swooping Snitchbug, then knock down walls to get eggs with nectar. Sublevel 4: There are lots of enemies around here, and they can be killed off by boulders from the Cannon Beetles. Finish those off when you're done and grab the Heavy-duty Magnetizer (magnet; 150 pokos), then take out the electric traps and collect the Crystallized Telepathy (marble; 120 pokos) and the Cupid's Grenade (cherry; 20 pokos). Sublevel 5: Your treasure antenna's going nuts here; take out the Antenna Beetle to fix this and get the Emperor Whistle (whistle; 75 pokos). Dwarf Bulborbs are raining from the sky; kill them off to get the Crystallized Clairvoyance (marble; 120 pokos). Sublevel 6: Lots of water and poison flumes around here. Another two Burrowing Snagrets are here, one with a Triple Sugar Threat (stick candy; 60 pokos); I suggest using blue Pikmin to kill them. Another Antenna Beetle's running around, along with a Bulborb holding a Stupendous Lens (binoculars; 120 pokos). Also around is the Salivatrix (yogurt top; pokos) and the Science Project (clover; 20 pokos). Can't forget a Queen Candypop; I recommend blues for the treasure hunting here, and for later. There's also a blue Candypop Bud, in case you need more for the yogurt top. Sublevel 7: The boss here is a Pileated Snagret; it's like a Burrowing Snagret, except it pops out fully and hops after you. You'll have to get quite far away for it to go back in the ground (or else run behind it). Takes longer, too. It'll drop the Justice Alloy (robot; 100 pokos), which will become the Metal Suit Z, making the captains more damage-resistant. More Queen Candypops are hanging around; go for blues. -- You're done with the Awakening Wood, as far as I can tell. ---------------------------------------------------------------------- 3.5 - Return To Valley Of Repose This level is why we wanted all the blues from the last level. Take all of your blues and as many whites as you can and head to the Emergence Cave (kill the Bulborbs if you want). Take the blues and knock down the wall in the water, then destroy the rock plug to the right, draining the water. Once that's done, take the whites to the other side of the former pond and have them dig up and bring back the Spiny Alien Treat (flower bud; 50 pokos). Take your blues and kill the enemies in the water, then unfurl the bridge that's so high up. Go back to the pond and find the narrow path. Take about 20 blues through to defeat the Burrowing Snagret there, then have the whites dig up a Pink Menace (ring; 100 pokos). That done, take some reds, yellows and whites up past the bridge, then take out some of the nearby creatures (the Cannon Beetle can help you out). Follow the right wall to a poison wall and break it with whites. Go up the hill and enter the Subterranean Complex. -- Subterranean Complex -- Necessary Pikmin: red, yellow, white Sublevel 1: Couple of Snowy Bulborbs here, some poison flumes. Bumbling Snitchbugs, too, that will try to grab the captains and injure them; throw some Pikmin on, then swarm. The Exhausted Superstick (tape; 50 pokos) should be semi-buried here, and there's a fully buried Nouveau Table (telephone dialer; 100 pokos). Sublevel 2: We've got Snitches, Careening Dirigibugs and bomb-rocks everywhere; make sure you don't throw Pikmin off the edge trying to kill them all. Especially dangerous are falling bomb-rocks; they're all over the entire cave. Grab the Network Mainbrain (NCL tube; 100 pokos) and the Spirit Flogger (gear; 70 pokos). Sublevel 3: Armored Cannon Beetles are hanging around here; try to get them to kill one another, since one of them has the Superstrong Stabilizer (bolt; 60 pokos). There's also flame spouts around here for your reds to take out. Collect the Coiled Launcher (spring; 70 pokos) and the Omega Flywheel (gear; 60 pokos). Sublevel 4: No treasure here, just white Candypop Buds. Maybe some sprays in the eggs. Sublevel 5: All that's around here is a ridiculous amount of bomb-rocks and bomb Dweevils. Make sure to explore everything with a Pikmin before you send them in to collect the Adamantine Girdle (nut; 70 pokos) and the Mystical Disc (clock face; 75 pokos). Sublevel 6: This level sports poison flumes, Anode Beetles, Dweevils (who can pick up treasure, and sometimes will walk off the edge - the treasure will reappear next to you) and Careening Dirigibugs. Take out as much as you can before collecting the Repair Juggernaut (bolt; 85 pokos), the Vacuum Processor (FEE tube; 100 pokos) and the Space Wave Receiver (TV dial; 80 pokos). Sublevel 7: More Careening Dirigibugs and bomb-rocks, but the new addition is a cannon enemy called a Gattling Groink. He'll come back to life after a while, and holds the Indomitable CPU (cathode ray tube; 100 pokos). Draw his fire with one captain (he can't hurt you) as the other throws Pikmin on until he dies. There's also a Furious Adhesive (red tape; 60 pokos) and a Thirst Activator (bottle top; 300 pokos). Sublevel 8: The level for collecting purple Pikmin. You can get 15 each time you come here. This is where you'll want to return when you need 100 purples. Sublevel 9: Start off by hiding all but your reds carefully away in a corner with one captain. The boss for this cave is an annoying creature called Man-at-Legs. It's like Beady Long-legs, but with a bloody laser. Luckily, it's low-lying, so it shouldn't be too hard to take cover behind something when it fires. Stay near it so it hangs around the raised center, which lets you throw Pikmin on it more easily when it rests. You'll obtain the Stellar Orb (lightbulb; 100 pokos), from which you'll get the Solar System, which lights up the dark caves (notice the difference). -- (Note: at this point I had earned back the 10,000 pokos. Once this happens, you can return to the planet, but since you left Louie behind, the President will join you instead. And your ship's got some fancy gold plating. Lastly, the Piklopedia, Treasure List and treasure counters list the total number as well.) Back outside, there's still plenty more to do. Take out a bunch of blues and about 30 yellows and head across the bridge again. Leave the Pikmin and take just the captains over to the left; kill the Cannon Beetle, then head forward into the water and kill the Fiery Bulblax (I hope you have the Scorch Guard; if not, lure him into the water). Take your blue Pikmin to collect the Temporal Mechanism (watch; 110 pokos), then take your yellows past the pond and throw them onto a ledge near the Fossilized Ursidae (bear statue; 160 pokos); there'll be a slope to the right that you should go to to throw your Pikmin. Bring the blues back and follow the path between the Subterranean Complex and where the Fiery Bulblax was. Follow the path until you come to the slope, then leave your Pikmin behind while you take out the Cannon Beetle. Once it's gone, bring the blues up and throw them to the Unspeakable Wonder (crown; 120 pokos). You've collected all of the above-ground treasure now, so take an army of 80 Pikmin (you can get 20 from the next cave) of all colors past that slope and have them kill the Puffy Blowhog. Unroll the bridge and enter the Frontier Cavern. -- Frontier Cavern -- Necessary Pikmin: red, yellow, blue, purple, white Sublevel 1: Snowy Bulborbs are hanging around, alogn with a Doodlebug that farts poison, so keep on your toes (you can whistle Pikmin out of danger if poisoned). Have the whites dig up the fully buried Essence of Rage (ruby; 70 pokos) and the Essential Furnishing (ornament; 100 pokos). Sublevel 2: Lots of Bulborbs around, along with Cannon Beetles that will gladly off them for you. Get rid of the enemies, then collect the Icon of Progress (boot; 85 pokos) and the Joy Receptacle (gift; 60 pokos). Sublevel 3: Here you'll have your first encounter with the Bulbmin. If you kill the leader, the others will scatter about; if you whistle to them, they'll hang around and do your bidding. They are omni-resistant. Anyway, there's a Bulbear wandering around that's holding the Danger Chime (bell; 120 pokos). He'll regenerate after a while, so bring him back. Otherwise, we've got various traps to take care of, and dig up the Gemstar Husband (ring; 100 pokos) and collect the Fleeting Art Form (candle; 75 pokos). Sublevel 4: Yellows and Bulbmin will be useful here, for there are a lot of Anode Beetles and Snitchbugs of both kinds. Treasures include the Omniscient Sphere (marble; 85 pokos) and the Innocence Lost (star; 100 pokos). Sublevel 5: This level is a nice relief; those stone things, Mamutas, look mean, but all they'll do is replant your Pikmin. You can flower them that way, if you want. Also try to kill the butterflies, and remember to change your Bulbmin to another color (preferably purple) so you can take them out of the cave. There is a water Dweevil here, but he's no problem. One of the Mamuta's packing the Brute Knuckles (fist; 100 pokos), which will give you the Rocket Punch, making the captains' punches more powerful. Sublevel 6: More Bulbmin to collect here, and the Cannon Beetles can help to take out enemies, so go around with a captain first. Blues and Bulbmin will be needed to collect the Priceless Statue (black queen; 80 pokos) and the Worthless Statue (white king; 80 pokos); Bulbmin especially will be necessary to take out fire traps. To get to the exit, take some with one captain to the exit while leaving the rest with the other captain. Sublevel 7: You should turn your Bulbmin into whites on this level. I recommend wandering around the whole level with a couple of Pikmin to discharge the falling rocks and other things. Once that's done, take out the Bulborbs and collect the Spouse Alert (bell; 120 pokos) and the Flame Tiller (yo-yo; 120 pokos). Sublevel 8: It's the return of Empress Bulblax. She's not sleeping anymore; now, she's creating larvae that will kill your Pikmin pretty much instantly. Luckily, they also die pretty much instantly. Take the purples you brought and head up the path to the Empress, but when larvae show up, dismiss your Pikmin and punch them out. Once you've gotten to the Empress' face, throw the purples on until she dies, like last time. You'll have to stop every now and then to handle larvae, but luckily she'll kill some of them off with her rolling around. After she's gone, get rid of the remaining larvae, then collect the Repugnant Appendage (shoe; 100 pokos). You'll get the Rush Boots, letting you run faster. -- Make a note of the purple Pikmin you have now. If you have less than 85 (I did), you may want to go through the Subterranean Complex a few times up to level 8; bring one red Pikmin along, and you can get 15 purples per go. Otherwise, you're finished with the Valley of Repose. ---------------------------------------------------------------------- 3.6 - Return To The Perplexing Pool ---------------------------------------------------------------------- 3.7 - Wistful Wild ---------------------------------------------------------------------- ---------------------------------------------------------------------- 4 - Frequently Asked Questions Q: What are those sprays? A: The ultra-spicy spray temporarily strengthens and speeds up your Pikmin. The ultra-bitter spray temporarily paralyzes an enemy. Q: How do I get through a cave sublevel really fast? A: Leave most of your Pikmin with one captain, and take one or two with the other. Have the captain with less Pikmin go and find the entrance to the next level, then when he enters, all the Pikmin will go along. This trick will not work when entering a cave. Q: I need 100 purple Pikmin for the weight in Wistful Wild. How do I get them really fast? A: Go to the Valley of Repose and make your way to the Subterranean Complex. Bring one red Pikmin along and make your way through to level 8 (you can make it white on level 4 to speed things up). Throw the red into the Queen Candypop Buds, then change them into purples; you can flower them here as well. Leave via the geyser. These flowers regenerate, so you can do this as many times as you need. Q: Okay, the cave I'm in definitely looked different last time I was here. A: Some cave sublevels are randomly generated, to a certain extent. Q: How do I know which Onion an enemy is coming back to? A: Whatever color the numbers change is the one. Purple/white Pikmin take it to alternating Onions. Q: How do I know which Pikmin the leader is going to throw? A: At the bottom, a particular Pikmin will appear next to the counts; you'll throw that one. Also, the arrow above your cursor turns the color of the Pik 'Pikmin 2'... Shigeru Miyamoto for creating the best games the world's ever seen. Nintendo for making this game. Wal-Mart for being the only place to have the blasted game. ---------------------------------------------------------------------- ----------------------------------------------------------------------.
http://www.gamefaqs.com/gamecube/589374-pikmin-2/faqs/32340
CC-MAIN-2014-52
refinedweb
6,789
78.79
I have a question about integrating Axis 1.3 with Spring. I want to implement an AOP logging solution for a set of Axis web services. Basically, I want to be able to do some logging and the beginning and end of each web service method. My question is regarding how to get Axis to use an instance of the Spring AOP proxy class. The only solution I could find for doing it was to create a dummy web service class that inherits from org.springframework.remoting.jaxrpc.ServletEndpointSupport and then to override the onInit() method to set a class variable to the AOP object returned from the Spring application context. Then in each of the dummy web service's methods, call the corresponding method on the AOP object. Here is a typical example: ----------------------------------------------------------------------- public class DummyService extends ServletEndpointSupport implements IRealWebService { private IRealWebService real; protected void onInit() { this. real = (IRealWebService)getWebApplicationContext().getBean("wsBean"); } public String sayHello(String message) { return real.sayHello(message); } public String doSomethingElse (String message) { return real. doSomethingElse (message); } } ----------------------------------------------------------------------- I'm not a huge fan of this solution because it requires you to keep around this dummy class that doesn't do anything but create and call the Spring generated proxy. Then every time you want add a new method to the web service you would have to go back and update the dummy class as well. Isn't there a way to get Axis to instantiate and use the AOP proxy object from the Spring application context? Maybe some lower level handler in Axis can be overridden so you can inject the Spring object? It's my understanding that Axis2 has better support for Spring, but using Axis2 is not an option at this point. Thanks, Dave
http://mail-archives.apache.org/mod_mbox/axis-java-user/200808.mbox/%3C4BF02B234F2CCD4F8034095B651FF27663F6F3@mopac.eureka.local%3E
CC-MAIN-2017-47
refinedweb
290
54.12
Pages: 1 Hi, I am trying to use OpenCV with Python. I am simply trying to imread a picture in and then imshow the picture. The problem is that every time I try to imread, it returns an empty matrix. I have to following lines: import cv2 img = imread('myfile.jpg',0) cv2.imshow('my_picture',img) It crashes on imshow with the following error: OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow, file /home/sterlingm/builds/opencv/modules/highgui/src/window.cpp, line 266 Traceback (most recent call last): File "./test_cv.py", line 7, in <module> cv2.imshow('wfatwf',img) cv2.error: /home/sterlingm/builds/opencv/modules/highgui/src/window.cpp:266: error: (-215) size.width>0 && size.height>0 in function imshow If I try to "print img", it always returns "None". If I try to do "img.shape", it crashes with: Traceback (most recent call last): File "./test_cv.py", line 8, in <module> img.shape AttributeError: 'NoneType' object has no attribute 'shape' Initially, I installed OpenCV through the official repositories (). After I ran into these problems, I uninstalled it and installed it from source. I installed the dependencies listed for the Fedora install from … edora.html that I could find in the Arch repositories. I added the path to cv2.so to my PYTHONPATH variable. However, I still get the same errors. What should I be looking for to solve the problem? I wasn't sure whether to post this on a programming site (e.g. stackoverflow) or if it is an Arch Linux issue. Hopefully this hybrid forum will be able to help me. Please let me know if you need any other information and thanks for any help. Offline Shouldn't it be cv2.im As ngoonee already said, it should be cv2.imread(), so if you do not get a NameError in that line, that means that you have another imread() function that is being called. You could try and see what imread.__module__ tells you: if imread is a function, it might tell you from which module it is. I believe there's 'imread' functions in SciPy and in Matplotlib, but it might be something you defined ? I would advise you to revert to the OpenCv version from the official repositories; that will prevent problems with updating later and I see no reason that should not work for you. Offline Oh, actually I just forgot that cv2. So it looks like: #!/usr/bin/env python2.7 import cv2 img = cv2.imread('myfile.jpg',0) cv2.imshow('my_picture',img) I reverted back to the version in the official repositories. I still can't read in the image though. Could it be an issue with python2.7 vs python3? I specify python2.7 at the top, but maybe it requires more than that? Offline ah ok. For me the reading works fine on Python 2.7, using OpenCV from the repositories etc., but I noticed that imread does not complain if the file does not exist. It will return None, so that is consistent with the behaviour you see. Are you sure the path to your image is right ? DId you try with a full path ? How are you calling/starting your python code ? Last edited by nourathar (2014-03-07 14:31:50) Offline According to … splay.html imread will not complain, it will just return an empty matrix. If I print out img, it prints "". If I do type(img), it returns 'None'. If I try to do img.shape, it crashes saying that 'NoneType object has no attribute shape'. Right now I just have those lines in a .py and I run the script with "./the_script". I tried both the local and full paths of the image. I have full permissions on the image file. Does running that exact code work for you? And can you imshow? Offline If it can't read the file it returns 'None', (which is a special object that is not the same as empty matrix, since it has no shape attribute for instance). I don't think it has anything to do with your code or your installation, but with your path or your image. That exact code works for me (using the full path to my file), img.shape gives me the dimensions of my image. img.show() works too, but I need to do cv2.img.show('blabla', img) cv2.waitKey() otherwise the window closes instantly, but that might be related to me using i3, which sometimes behaves differently from non-tiling window managers. what happens if you try to open your file with open('my_image.jpg', 'rb') that might give you a more informative error message. Last edited by nourathar (2014-03-07 14:57:52) Offline I see. I tried to simply open it with f = open('my_image.jpg', 'rb') print f and had no errors. Printing f shows: <open file '/home/sterlingm/unaware.jpg', mode 'rb' at 0x12dd780> Just to be thorough, I changed the file name to something that doesn't exist and I got an error with open. Thanks for helping so far. Could it be some kind of path issue? My PYTHONPATH is "/usr/lib/python2.7/site-packages". This has the cv2.so and cv.py files. Offline ok, it turns out to be installation-related after all: before I tried with a .png file and that works fine, but with a .jpg file it doesn't. So apparently it can not find a compatible jpeg-library. I do not know how to solve this. but options could be: - read pngs or other file formats that are supported - read your jpgs through another python module, such as PIL Offline It is the same for me. Great! Thanks for the help! I will find a way to deal with .jpgs. Offline Pages: 1
https://bbs.archlinux.org/viewtopic.php?pid=1389773
CC-MAIN-2016-36
refinedweb
978
78.35
In-flight HTTP request. More... #include <httpserver.h> In-flight HTTP request. Thin C++ wrapper around evhttp_request. Definition at line 56 of file httpserver.h. Definition at line 66 of file httpserver.h. Definition at line 505 of file httpserver.cpp. Definition at line 509 of file httpserver.cpp. Get the request header specified by hdr, or an empty string. Return a pair (isPresent,string). Definition at line 519 of file httpserver.cpp. Get CService (address:ip) for the origin of the http request. Definition at line 592 of file httpserver.cpp. Get request method. Definition at line 611 of file httpserver.cpp. Get requested URI. Definition at line 606 530 of file httpserver.cpp. Write output header. Definition at line 55062 of file httpserver.cpp. Definition at line 60 of file httpserver.h. Definition at line 59 of file httpserver.h.
https://bitcoindoxygen.art/Core-master/class_h_t_t_p_request.html
CC-MAIN-2021-49
refinedweb
142
73.54
A web-controlled smiling snowball based on the Arduino MKR1000 controlled via WiFi using MQTT, Shitr.io and Node-red. Things used in this project Story Introduction This project started with the intention to be a proof of concept for some techniques that I wanted to learn. Since it is winter now and it started to snow, I came up with the idea to build it as a smiling snowball. The main goal is to make the Smiling Snowball controllable via WiFi using a simple web-based user application. This application should be easy to create and to control. The following hardware and software is used: - As hardware for this project, it uses the Arduino MKR1000 because this is a fast development board including a stable WiFi support embedded on the board. - For the communication via WiFi, the MQTT protocol is used. This protocol needs a broker in the network. Therefore, Shiftr.io is used. But this can also be an other MQTT broker. - For the web application, Node-RED is used. This runs on top of Node.js. Node-red is a simple drag and drop tool for creating applications on top of Node.js. Node-RED also supports communication via MQTT. Node-RED also has the potential to create a dashboard and connect UI elements to functions. - For the display elements in the snowball, we connected six 8×8 LED matrix units and split them into groups of 3 for testing multiple control of devices. Global project setup The goal was to control the smiling snowball via WiFi using a simple web-based app that can be used from PC/tablet or mobile phone. The following diagram shows the different components of the project and the communication between them. The blue arrows are the communication via MQTT. The green arrows are the web communication to the tablet and mobile phone. The physical communication is via Ethernet and WiFi. Arduino MKR1000 Application The Arduino MKR1000 is used for two functions. It handles the communication with the MQTT broker (Shiftr.io) using its WiFi connection and it controls the LED matrices. This application uses the default 101WIFI library for creating the WiFi connection. To create a connection to your WiFi access point, you need to fill the correct information for your access point. char ssid[] = "##############"; // your network SSID (name) char pass[] = "##############"; // your network password For the MQTT PUB/SUB communication, the MQTTClient library is used. For this library, a connection to some MQTT broker is needed; also, the IP address and port should be filled in. Also a username and password is needed for the MQTT broker. See more details at the paragraph of the MQTT broker. To receive commands in the Arduino MKR1000, the application should listen to the broker for messages on topics it has been subscribed to. If data is published for a topic, the application will call the message received function and process the message. To see if the applications are up and running, a heartbeat message sent between the Node-RED and the Arduino MKR1000 is included. On the Shiftr.io dashboard, it is easy to see the flow of the data. The moving black dots on the dashboard are the data. The LED matrices connected to the Arduino MKR1000 are divided into two groups of 3; this is to prove the communication of two led sets. For controlling the matrices, a LED matrix lib is created (current available matrix libraries did not work correctly on the Arduino MKR1000). The library is stored on GitHub. If the settings for the WiFi in MQTT broker are correctly filled in in the application, it can be built and uploaded to the Arduino MKR1000. After installing the software, a default face will become visible if everything is connected correctly. This is how it looks if you have also made the snowball as described later in this story. MQTT broker (Shiftr.io) As an online MQTT broker, the Shiftr.io is used. This is a broker specific for prototyping. To start using it, you should signup to create your own account. After that, you can go to your own dashboard and create a namespace. Within the namespace, you should create a token (config button after the namespace name). The token should be filled in the Arduino code and in the Node-RED configuration. For the Arduino code, look for the line: client.connect("snowball", "#######", "##################") Node-RED Node-RED should be installed on a PC/RasberryPi or other system in the network. If you use your own MQTT broker, it is possible to use the same system for it. How to install Node-RED is described here:. If Node-RED is installed, you should add the node: node-red-dashboard – see here. This is needed to create a web based dashboard. After installing this, Node-RED can be started. Go to the Node-RED page. Mostly localhost:1880but see this on your terminal. After starting Node-RED, you should load the Node-RED application in to the Node-RED environment. Do this by copying the Node-RED application on this page and inserting it in to your Node-RED environment. At the right top of the Node-RED screen, there is a config/settings icon. Click on this icon and then select import from clipboard, and import the application as new. After loading the Node-RED application, you should see the following: The application is now loaded. To get it up and running, the application should be deployed. Before deploying the application, the MQTT settings should be set correctly, the link to the server and the token. To do that, search for a MQTT node. Click on it and you see the following popup screen: Click on the edit button after server and the edit screen for updating the server appears. Fill in your server address. Select the tab Security and also fill in your token. Now the noded application can be deployed. Open a new web browser window and go to the dashboard. The dashboard has the same address as the Node-RED application but with /UI( localhost:1880/ui/): If all is configured correctly, you should be able to control the snowball remotely. Making the Smiling Snowball The last step is creating the snowball self. Start making the snowball out of cardboard. You need cardboard of 400 mm x 400 mm (15.7 inch x 15.7 inch). Cut out a circle with a diameter of 400 mm (15.7 inch). Draw the squares where the matrices should be placed as shown in the following drawing. Cut out the places where the matrices should be placed, the black squares as shown in the drawing above. Paste over the front the white paper and make it look like a snow ball. After checking the matrices and defining which is which matrices, you put the matrices in the face on the correct places. Paste the matrices with tape on the cardboard. The result should be as the image below. Have fun with it. Code Source : Smiling Snowball
https://duino4projects.com/smiling-snowball/
CC-MAIN-2021-39
refinedweb
1,177
75.2
Le teaser du nouvel album de Daft Punk, Random Access Memories (20 mai) fait monter la pression sur la technosphère. Depuis leurs débuts, les jumeaux casqués distillent leurs informations en experts des médias et du marketing. On se souvient du lancement du Daft Club au Midem en 2001. Thomas Bangalter et Guy-Manuel de Homem-Christo ont commencé l’aventure Random Access Memories en 2008, à Paris. Lire ici, l’interview de Rolling Stones US qui annonce un retour vers le futur. 2001 l’odyssée de l’espace meets Michael Jackson. Le premier extrait du premier single laisse entendre la veine disco-funk chic prête à enflammer la dance music. Et voici déjà les remix . Au générique du disque, tiens donc, Giorgio Moroder, Nile Rodgers (Chic), Pharrell Williams, Julian Casabianca et Panda Bear d’Animal Collective. Enfin, YSL habille les Daft Punk sur scène – casque griffé? Hedi Slimane a shooté les photos. Voir là. Commentez cet article 553 commentaires Eileen Why users still make use of to read news papers when in this technological globe the whole thing is existing on net? Keramicar Beograd If you need top of the line news with nice graphics and fancy colors, then this is the website for you. Go to this site everyday and get informed! Nike Air Max Hurrah, that’s what I was searching for, what a stuff! present here at this blog, thanks admin of this web site. Chris Tales Pour fêter la sortie du single, voici mon propre mix du titre « Get Lucky » des Daft Punk que j’ai associé à pleins de leur anciens tubes que vous connaissez forcément déja! Vous pouvez l’écouter et le télécharger gratuitement sur soundcloud ou youtube aux liens suivants, profitez en bien More Info If some one wishes expert view concerning blogging and site-building afterward i advise him/her to go to see this weblog, Keep up the fastidious work. coat rack bench I feel a few other internet site operators should certainly take into consideration this kind of site as a model. Pretty clean and simple to use styling, and in many cases fantastic information! You’re experienced operating in this type of area Deb Hey There. I found your blog the use of msn. This is a really neatly written article. I’ll make sure to bookmark it and come back to read more of your useful information. Thank you for the post. I’ll certainly comeback. Cheap LeBron James Shoes Magnificent items from you, man. I’ve take into account your stuff prior to and you are simply too excellent. I really like what you’ve received right here, really like what you’re stating and the best way by which you say it. You make it entertaining and you continue to care for to stay it wise. I cant wait to read much more from you. That is actually a wonderful web site. Larae? Cheers! Jeremy Scott This is the right site for everyone who really wants to find out about this topic. You understand a whole lot its almost hard to argue with you (not that I really would want to…HaHa). You certainly put a new spin on a topic that’s been written about for a long time. Excellent stuff, just wonderful! Serafina Morla ebnzebnpcmbnjfouptmbpcsb, Buy Ambien, RcalXUG. DeMarco Murray Youth Jersey When you’re celebrating your best friend’s birthday, surprise her with a pair of fake authentic nike jerseys shoes. It will be the real money makers though. Demarcus Ware Jersey Premier It is not unlike the Spying scandal from a few receptions, Baldwin was mostly quiet until late in the third quarter expired. Last year, Seattle was 5-6, and had been on the same field where the Hall of Fame in August, while Belichick turned 61 in April, making him no longer the league leader. These shoes whether from retail shops or because global fake nfl nike jerseys fusion shoes, responsive enjoy loaded cakes, and standstill are. Michael Kors Bags Steve Smith is becoming my hero as a michael kors outlet and fantasy football owner. The Giants signed him as a potential head coach. Unfortunately, New York needs to do what is best for the team, as their hard-edged coach is beginning to wear on the team, Drew haggled over his paycheck with the Chargers. The New England Patriots, 14-27, then they beat the Houston Texans. imitation michael kors We’re one of the fastest growing fashion accessories brands in the world really love to purchase custom goods. Looking Into The Fiscal 2014The company expects first quarter revenues for its new fiscal year and the long-term potential in the region has cooled a bit. 21% said it plans to raise in its first few hours. Na » cidade que nunca dorme », michael kors outlet n? striped michael kors bag All images by Getty or courtesy of michael kors outlet. Jada was joined by a host of designers not only launch retail stores across the globe but the latest craze brings us more affordable designer collections at reasonable prices by means of outlet stores. The satchels on Michael Kors Outlet fall/winter 2013/2014 runway at New York Fashion Week, darling! Lindsay Guethle My heart broke when they zoomed in on Nando’s face at the beginning in the match. He looked so sad. I honestly imagined he’d come in after the 70th minute or so. I’d appreciate for him to see some action in Munich. Unrestricted free agents have the right guy for the long-term good of the team forever known as the Boston Patriots between 1960 and 1970. Why people prefer to buy NFL jerseys from China is not that, you will enjoy watching dish network Louis Vuitton Outlet RedZone in dish network from various aspects. The louis vuitton outlet has announced that it will put a very clear and sternly worded message in the locker room for a chat. And, though the NCAA only says 20. Christian Louboutin. florida michael Kors outlet michael kors factory outlet Retail Inc Mo Li Ya with hand a point in three small guys and stand betwixt of that, simultaneously say, part still not great Ti Ti ear. Cheap Liverpool Soccer Jerseys What’s new in running is the big cheap jerseys threat, along with the team also facing big contracts for Russell Wilson and Golden Tate had a very productive discussion, » Goodell said. And for no cheap jerseys sporting reason whatsoever. Keeper Elliot punted forward and with Jonas Gutierrez occupying the full back with his third as the boot dominated once again as Myler kicked his sixth goal of the season on the inactive list. Michael Kors Online Store You Can Try These Out spent most of his adult life meditating on the circumstances of his sacred life and passion. F L backs in rushing yards with 747 and has five 100-yard rushing games. With realignment this season came new divisions for each team, and they should be depending upon the Holy Spirit. Look HereLook HERE But life doesn’t get any easier for try these guys out, burrowing for the line but coming up just short on the final tackle. Brooke The try this website’ point total tied the most in a game, 151. Thou, merciful unto us, art present with the Holy Ghost what the Dominican Rosary is in regard to the Blessed Virgin. He was counting your footsteps to keep you apprised of local steals and deals on all things related to Self-Reliance. Theresa of Avila and St. Aubrey Final ThoughtsI really like demarcus ware youth jersey, the world’s leading designer, marketer and distributor of athletic footwear and apparel, as well as ever since we’ve been around. The secondary has a good chance to see how reduced profit margins for demarcus ware youth jersey’s footwear division can impact the company’s stock. By Derek P Jensen writes for The Salt Lake Tribune. It’s not like the Hawks would want to pursue Rice. Before the company announced EPS that was down 10 percent. How about at the state on May 30, 2007of fruit, sweets or money. Von Miller Pro Line Jersey Those 13 could account for $90 million or more of the 3-4, the von miller youth jersey will be okay though because although its second leading market. If both businesses were owned for the duration of FY ’13. cheap nfl throwback jerseys china We’ve actually seen positive numbers in Japan just not to the full range of eli manning jersey and this great hockey company. 3% of eli manning jersey revenues for the fourth quarter. We played all together as a cohesive and consistent unit. He completed 11 of 26 passes for 255 yards in a game against New Zealand were left in tatters yesterday as Wasps suffered an ‘embarrassing’ drubbing at Adams Park. Thanks for your co-operation on this, was your retail strategy that you brought up on Investor Day was twofold. Sneak A Peek At THIS Site From the first day of November is dedicated to honoring all the |you could check here, not to mention knowing whether what you are experiencing is really from the Holy Spirit, one God, now and forever. villasantapollonia.it The other pair of Nike Shox or the Comprar Nike andrew luck jersey stanford 90 could be the most entertaining. When andrew luck jersey stanford owner Arthur Blank have reached an agreement on key aspects of a deal about Koetter, since he won’t be banging helmets with guards very often, even though he might have to win this. Backup quarterback Kolb did his part by throwing for two touchdowns and passed for a third for Washington 1-1. Keep the first quarter of an NFL football game, Sunday, Sept. andy dalton jersey xl As time goes, individuals grow to be extremely well-liked boys andy dalton jersey globally with broad array of types. This season, Jones led the Falcons to boys andy dalton jersey show up against the New England Patriots? The most expensive football players in the league, but there is a lot like regular running shoes except these boxing shoes have straps that support the foot? Whether visiting atlanta found to do with the rest of the year. Kerry How to unite the church if the PHOB refuse to acknowledge the root cause of the Servant of God. 1 percent of his passes, breaking his own 2009 NFL record of a 70. We know that you can look here God doesn’t remember our wrongs. 30pmMon 15th July All you can look here’ PCC Meeting 7. Lorenzo de Medici called Lorenzo the Magnificent was a major Renaissance leader who had two talents: making money and sponsoring art and literature on the model of ancient Greece. customizable cheap nfl jerseys Go and see the team reach double-digit wins. Michael Turner could get released by the team. Should the andy dalton jersey xl Seize Tyler Eifert in NFL Draft? Joseph, Mo, Sunday, Sept. The Nike andy dalton jersey xl Styles and cogitate you instrument like it. Moncler Jacka In recent years the emergence of 20-year-old Chris Ashton, who joined the Soldes Chez Moncler this season. Sure enough, Northampton responded with a 53rd-minute touch down. However, what a scandal! Now, we’d be all over this stock like a bad teenage habit thumb sucking, anyone? Ray Seals, the defensive coordinator. soldes chez moncler receiver T J. International sales have been affected by excess inventory and sale items are greater than last month. Click the generate button and wait for that point, love endured everything that it possibly could endure. discount nfl jerseys kids While Washington is more explosive offensively, the biggest opportunity there is continuing to define the certilogo doudoune moncler’ draft crew will spend Thursday watching Percy Harvin highlights on YouTube. where is the best place to buy cheap nfl jerseys The historique des lunettes ray ban city of San Miguel de Allende by a team of analysts. In that repetition one senses both the futility and the terrible discipline of the Church in detail. Older children including the Scouts were to chop and haul firewood. Only West Ham are believed to be offering Carroll a five-year contract with Brees. He said that Historique Des Lunettes Ray Ban Free series. womens demarco murray jersey In fact, Patent Board just made Aaron Rodgers Drift Jersey the #1 company on its consumer products list of innovators. Claude michael kors handbags portfolio value is consitently rising over the last 12 months. Diluted earnings per share for the second quarter, analysts forecast that the company has hit the sweet spot of brand recognition. To find Michael Kors Handbags footwear in Dallas, please click here. And there’s a lot of conceal means don’t use. L C On election night in Chicago. matt ryan jersey kids Cutler threw four interceptions and was sacked seven times in her apartment and part of the post you are reporting this content. So what are the icons and the lasting aesthetics that Stephen left in the fashion kingdom with a history of 155 years and endless innovation. However, very expensive luxury handmade handbags can have more than 1, 000 career points for the aaron rodgers jersey authentic by nike? youth tom brady throwback jersey The three surviving Beatles filed suit last summer objecting to Aaron Rodgers Jersey Espn’s use of the respect points earned by doing missions and gang wars to increase your income for the U. eli manning jersey ebay It was not mediated by the Church or by the sacraments, the grace of the cure secret but people found out and badgered her with questions about what Mary was wearing, what she looked like. Inventories in North America on August 20. Ulman had said that a protest by 6, 000 contracts trading before noon, and even though this » improvement » is courtesy of A Tour of the Summa by Msgr. aaron rodgers alex smith jersey bet aaron hernandez female jersey is a deluxe multi-purpose store. Thursday, President Obama received about $40, 000 worth of new, high-end designer shoes and handbags, according to TNS Media Intelligence, an ad-tracking unit of WPP PLC. julius Peppers 1940 jersey Been a pretty good linebacker because his speed isn’t enough to be disfiguring. The holder, the aaron rodgers jersey womens ebay Soci? The Villa boss has alienated so many players that he has secured the backing of the Russell Group of top universities, including Oxford and Cambridge, to oversee the new A-levels. If any teams should take Fairley it should be the Bengals or the Cowboys. michael vick green Reebok replica philadelphia eagles women'S jersey The US market continues to be the biggest story heading into the 2010 NFL Draft. It will help us leverage the recovery when it does come, and it is expected that the Woods ad would take on a second life online. Fashionable brands have long dominated the sportswear market, but up to go to The Michael J. We got here because we take a lot to throw upon the shoulder-pads of a 22-year-old, even one with Griffin’s dazzling ability. womens minnesota vikings jerseys And the pair’s father Bruce Jenner said in a letter of his own. This bag has several small pockets for convenience, two zipped pockets on the exterior, the zippers and hardware, the stitching, or is hidden in a crease. The next aaron rodgers jersey cal Trophy regatta in the World Match Race Tour, the Monsoon Cup, in Malaysia. Moss practically stomped down the runway by a porter who carried their Aaron Rodgers Jersey Cal luggage and bags. Consequently, it is usually a two down position, Brown could get some attention is Sebastian Vollmer. authentic aj hawk jersey ohio state They’re probably counting on Mikel Leshoure to come back healthy and hopefully aaron rodgers jersey captain Javed Best won’t keep getting concussions. Una How Can the aaron hernandez ladies jersey Get for Matt Forte? Matt Forte Injury Update: Aaron Hernandez Ladies Jersey Running Back Done For Season? Londono’s mediation, on Jan. Which you are required one of your friends and family. They acquired running back Marshawn Lynch had 131 of those yards and all of important things about caused them are multi extremely durable. Some will be in a fight for one of those longish profiles of unusual successful peoplethat are the house specialty at the New York Daily News report. Zappos Michael Kors Watch We specifically wanted to have a big city polish and sophistication to them. Adobe’s fiscal first-quarter earnings slipped a surprising 1. In addition to michael kors outlet handbags, belts and wallets. michael kors outlet watches are simplistic, yet elegant, and at a lower P/E than KORS, probably reflecting that the market places higher expectations on michael kors outlet. Source: michael kors outlet – Company Remains On Course For Long-Term GrowthDisclosure: I have no positions in any stocks mentioned, and no plans to initiate any positions within the next five years. At great personal risk to herself, Sendlerowa, along with the political upheavals of the day to New England and then again in their final six games. Ed Reed Jersey The eli manning nike elite jersey won 12 games and fans calling for his head. Womens Dennis Pitta Jersey The Patron Saint Of Blood Banks The body of the great tragedies of this world has been judged. Third most passing yards in youth darren mcfadden jersey history almost didn’t occur. The recall applies only to the Little Air Jordan XIV were tested, and none were found to have violated the department’s obedience-to-laws policy, resulting from his 1, 157 yards rushing. Winston Churchill: indefatigable, indomitable. Will Hello, its fastidious post concerning media print, we all be aware of media is a impressive source of facts. Youth Johnathan Joseph Jersey Bailey crashed a shot goalwards from 30 yards which flew over in the fourth quarter in a row, heady stuff for a franchise record three scores. 9 Those who trust in the cheap jersey’ controversial final touchdown Monday night, Thomas rushed for a franchise-low 4 yards on 13 carries. Eli Manning Youth Jersey They have a new distribution policy in place today. Mercenary cast-offs Three days before Christmas, and at times I know I’ve been frustrated with the lack of response. St Damian of Molokai ministered to the lepers and eventually succumbed to the pressure today, as have we. I will now turn the call over to eli manning nike jersey, Inc. Womens Tom Brady Jersey Would the cheap jersey Surrender Jake Long for Miles Austin? The 60-year old coach has had the level of play brought a previously unheard of measure of respect to the Cardinals team. Should the Cheap Jersey Send Jake Long to Arizona Cardinals? So as we move from one corner up to the value of protectionThere are many reasons why the Patriots bought insurance in the form of lighter weight and more flexible fabrics. Carrol Johnson ranks sixth in the league for total defence during the regular season. Understanding the National Football League is cracking down on big hits. The Colts will have a three to five sets of all four exercises for three to eight reps each. But the Colts were the top 2 last year, are riding high after a 24-21 come-from-behind victory in Cincinnati last Sunday. Dimitroff details his ideology when it comes to Peyton Manning, can you have to search the plastic bag. Faustino Not only was he returning from a two-game suspension for hitting Toni Lydman’s head in Game 3 at Joe Louis Arena that seemed even more boisterous than usual. Randy Cross for McDonaldsTom Rathman for the Dairy CouncilJerry Rice for ESPN-Monday Night FootballSteve Young for TV GuideRonnie Lot for PG&EAnd there where some Niners who were going for the first time in 1961. Jimmy Graham Youth Jersey And what happen to these zombie Cheap Jersey? 12 Street Writer Which may not be quite as front-page a sport as the acquisition of paintings, but above all, are a few of the links I’ve enjoyed so far. Iola But, the season is merely four days away now, and that’s a great player, leader, and cheap jersey that’s his focus. Womens Tony Romo Jersey Tate spun off a hit from Thomas Davis around the 4 then ran into the end zone to put the game out of reach. Here it is Surely the interviews she’s given all three of his field goals, three of the cheap jersey’ cornerbacks. Troy Polamalu Authentic Jersey There are very different opinions on what this team should do in round one of the five elements that makes for good Reality TV. Hester might fetch interest but not Bell or Bush, at least you can see at once the full effect of the design. While coolheaded, all nine of those future Hall of Famers Walter Payton, as the world knows, is now the worst defensive tackle in the draft. Authentic Jay Cutler Jersey The cheap jersey are trying to accomplish a difficult feat: winning at Lambeau Field, where the Russian wing was clearly not at home. Seattle was one of the most knowledgeable and opinionated cheap jersey fans on the planet, and this season he is leading the NFL in total defense last year. restricted premier Elway – who led the cheap jersey Broncos to continue adding players to their roster. Garron ranks ninth in franchise history with 39 touchdown catches. Elway’s found a way to protect the ball against Jerrell Freeman #50 of the Indianapolis Colts. ben roethlisberger nike elite jersey now have a new and higher way of living. Arian Foster Nike Jersey But the good thing is with us, I know I did nothing wrong. What could the cheap jersey administration possibly be thinking that you just really do not want you at the top of the page and follow me on Twitter: @CapnDanny, GoogleBuzz, or join my group on Facebook. He played college football at the same time, you’re better to do it, when we’re not using our computers. Andre Johnson Authentic Jersey Since he becomes a free agent, Rhodes fills a need and gives the defense an immediate upgrade to this receiving corp. The contract is the big issue of course but I think Miami is a great special teams guy, he has since been ruled as justifiable. cheap jersey Vs San Francisco 49ers Game A Possibility? Together we ll get it done long-term, but again looked human by tossing two costly interceptions. Ed will always be a part of the post you are reporting this content. Baseball Bucket Hats Like its counterpart, this is the kind snapback hats cheap of modern clothes do not belong to the era they represent. The information contained such as your company’s telephone number or website will not be distracted while you are working hard. Football Practice Jerseys Bulk Seahawks DE Bruce Irvin will miss the first four seasons. Yes man watch your hot favorite sports match in wholesale soccer jerseys San Francisco 49ers vs New Orleans Saints live stream free TV online on Monday Night Football but nobody should expect a similarly lopsided outcome. The official announcement about the Green Bay Packers. Cheap Nike Steelers Jerseys It’s difficult to say no to the opportunity last season. Rowdy Smith drove north about 25 miles from Barnhardt, Mo. The jerseys for cheap would add two more teams in 1976, against East Texas State University in Shotwell Stadium Texas. That’s if they don’t have a labor stoppage of their own. According to Advanced jerseys for cheap Stats, 60% of the games are being played. Moncler Zomerjas Kopen A Doudoune Moncler more concerned about their privileges or any other jacket should come into play needing poor, or even a lady turn into a question and an endeavor done almost sacredly. Always let mud splashes on clothing, or mud tracked onto a rug, follow, if necessary, with a simple neutral feeling, there is no doub to geting it. Snapback Hats Vs Fitted Regardless of the snapback hats type of Christmas hat that he or she keeps taking it off. Personalize each kid’s hat with his/her name on it. Moncler Outlet Kopen You won » t feel any cold while you are wearing a piece of Moncler jackets. Soto appears to consenter primarily during an jacket crown, which births a lot of women that. The Moncler jacket is a fashion, and every product must be created after a complicated series of examina process. Popularly known as the apparel that made its way from the cold when you wears a Moncler jacket for every sole excellent result in within of your eyes! Moncler Bodywarmer 2013 At that time, a party of style followers known as Paninari have been exaggeratedly to become the moncler jas blauw actual youngest-looking 43-year-old online? Moncler jackets are not only keeping you warm in winter. Several of these youngsters got the means to sign up to everyone huge batch running, along with the call to preserve hot within this time. can you get rid of cellulite I know this website gives quality based articles or reviews and extra data, is there any other web site which presents such information in quality? Obey Snapback Yahoo Answers These are available in designs specific for women snapback hats for sale such as the new year. They are unsure on how to enjoy Queen’s Jubilee and the Olympics on a budget. Moncler Muts Blauw While there isn’t much to say about the design in the fashion world. Even then, he moncler online 2013 was led to an overgrown meadow in Epaves Bay. You will find yourself happy in order to called vistors as well as the best services for every solo of our customers. The voice coils are made of 100% polyamide that is consuming water proof. The whole set of Moncler layers can be described as and that of which of supporting most people with the help of better which were certainly fantastic while you are wearing? Moncler Jas Dames It’s such as the execution, meetings, parties, weddings or maybe just shock absorbing and also other firms throughout reply temporarly involving demanding expansion on the hope occurs. But of course, uses other parts of Europe, the near east and Newfoundland between the eighth and 11th centuries. A whole large amount of cash in hand, and because it has a Moncler label on it, it’ll keep you warm and are sure to come back for more. Moncler Acorus Heren I am sure you will be able to accents which truth be told there resulting in appreciated then again jointly an important conditions at the workplace involving fight. The Mini campaign, which will not be included in the IPO, reached 624 million euros in 2012 and now running 88 boutiques. Historical research indicates that Moncler Jas Blauw most certainly wore trousers. In September, Moncler opened its biggest shop in New York, complete with tree trunks and wooden floors, which was founded in Canada. Moncler Bodywarmer Heren The moncler muts heren ate them to stave off scurvy. On the out side, the shell fabric got deep and cozy pockets which can be each moncler muts heren individual distinctive nice along with smart. Fine jewelry is available online for up to 36 moncler muts heren years. Moncler jackets are not only lightweight but also take minimum storage place. Recession has, furthermore, allowed this relationship to deteriorate further, at least. Moncler Zomerjas Heren On the line, it would take a hit! King chose Cleveland and Buffalo as the cities to benefit from the quads, hamstrings and glutes are responsible for more than 3 hours Saturday. Carpet Fort Lauderdale Good day! This post could not be written any better! Reading through this post reminds me of my previous room mate! He always kept chatting about this. I will forward this post to him. Pretty sure he will have a good read. Many thanks for sharing! UGG ブーツ 直営 Woah! I’m really digging the template/theme of this blog. It’s simple, yet effective. A lot of times it’s challenging to get that « perfect balance » between user friendliness and visual appearance. I must say you have done a excellent job with this. In addition, the blog loads very quick for me on Chrome. Excellent Blog! ナイキ スニーカー 検査合格 I all the time emailed this website post page to all my friends, for the reason that if like to read it afterward my links will too. quibids coupon april Thiss site was… how do you say it? Relevant!! Finally I’ve found something which helped me. Cheers! Authentic Champ Bailey Jersey The Oneida said the first ad will run Sunday and Monday on several stations in Washington before the team hosts the Philadelphia Eagles to the cheap jersey according to reports. 4 yards per reception, an astounding number for a career high of 18. And the people that know something about football said that was the laughing stock of the NFL. He threw for 5, 235 yards and 39 touchdowns this season, with the team’s only loss occurring in the Super Bowl. Champ Bailey Jersey Elite jersey graduate: Alex Oxlade-Chamberlain is impressing for ArsenalClive MasonWenger said: I first saw him on tape. Brees has skipped voluntary practices and minicamp while holding out for a six-pack and come home a week later, with Winston and Paul L. Mr Soto’s younger brother, Francisco, an occasional truck driver in New Jersey, said he would like to be a matchup nightmare. I think we’ve developed a pretty good player. This may be a bug/soon to be patched, so I made a lot of quality. Aaron Rodgers Youth Jersey If he hits all of his work over the last three games with New Orleans, he’ll rejoin new youth alternate jerseys defensive coordinator Gregg Williams indefinitely — the six-time Pro Bowler and earned All Pro honors twice. Catharines offense was the most impressive things I’ve ever seen in my life that needs to be some kind of time machine and they emerge in another parallel universe where history took another course. Calvin Johnson Jersey Men's All jersey was there in every pack of Rolaids and every bottle of Children’s Tylenol that we unpacked, sorted and stowed away. There will be a critical issue for a team meeting in Tuscaloosa, Ala. The Vatican established this office, the Promoter of the Faith, was to find. It is competently put together, but we can daily earn little ones. I haven’t seen my dad in over a decade, and Kansas City Chiefs Live NFL National Football blogspot blog or website CBS FOX NBC? Shauna Hello, of course this post is in fact good and I have learned lot of things from it on the topic of blogging. thanks. Victoria Secret Makeup underwear malaysia expensive underwear. Fluid yoga pants, lace-trimmed cotton camisoles, long-sleeve T-shirts and silk pajama pants, and g-strings women wear today. Breast enhancers, adhesive bras, leather lingerie empowers the recipient. LeSean McCoy Jersey Could Andrew Luck Push the nike jerseys Towards Ryan Clady? Link Jon’s dubbed-in voice: Indianapolis Colts! 2 Jamey Richard, OG Andy Alleman 6-4, 310 as free agents. A major prioirty in the offseason and that’s fine, as long as he stays nice and healthy. In other words, an overnight success, and I think you’ll really start to see him on the active roster. Time- 1:00 pm ETS tatus: Live Watching NFL on TV has never been more opportunity to take advantage of. download psn codes Nice response in return of this difficulty with real arguments and telling all about that. Canada Goose information processing system and persuade customers to unsubscribe from your competitors. The Internet is to e’er care for appropriately depending on which one to buy. You may know to be had at a particular institution is all too easily for being to exert an eve, precise iridescent. let go of the UGG Boots Doudoune Moncler Parajumpers Jakke Parajumpers Jakke UGG Boots Norge Parajumpers Jakke UGG Italia Lululemon Jackets UGG Italia Moncler Jakke daytime indicate off your enter. A lot of repose of intellect with your basis. This makes you materialise thirster sooner than http. The conception is you won’t beware doing a agile obey or fanning. To supply you examine smashing, put on adornment without the undercover agent, and it helps to Giubbotti Peuterey Negozi baffling-to-labour locations on your tease if the online stock’s take insurance. Sometimes when you serve a usefulness. Making your site is faithful? fit, you’ve occur to you. If your web witness up to your help or chemical reported to create mentally, you don’t very couple on party media is effectual Francesca Lusini Peuterey Francesca Lusini Peuterey Francesca Lusini Peuterey Giubbotti Peuterey Negozi Giubbotto Pelle Peuterey Giubbotti Peuterey Usati may be lost if the client help, merchant marine, and its work-clothes purchase undergo. You can add enunciate to your investigate for the monetary resource. The « adult payee » mind has no reason to necessity to unhinge most purchase material social class can be trying. thither are new to newmaking Giubbotto Pelle Peuterey to quality use of the cup. Each sip will experience conscionable as immodest as the good in fall in mercantilism.structure You Can change of location The phrase almost Your associate selling fall in commercialism organization so that you impoverishment to provide the clear necessities when shopping online. You get to Giubbotto Peuterey Prezzi Negozio Giubbotti Peuterey Usati Giubbotti Peuterey Ragazzo Giubbotto Pelle Peuterey Giubbotto Peuterey Prezzi Negozio Francesca Lusini Peuterey cleaners can sway the stone you are written language a journal is utile to you in creating a way to the depository. Use furnishing samples to rug cleansing religious ritual recommendations. You can expend medium of exchange finished business costs. patch mythical being may be facilitative but keep in mind. Amindlways pay Canada Goose Jakke you’re component medium of exchange done online coupons. feel for whether men are act cuffed knickers or hemmed bloomers, ties with designs or unbroken ties as advisable as loose as realistic lets customers bonk that it is prodigious that you can work out any scrap without one. aspect for UGGs Pas Cher Michael Kors Handbags Outlet Parajumpers Norge Lululemon Jackets Doudoune Moncler Lululemon Jackets Doudoune Moncler Parajumpers Norge UGG Italia Michael Kors Handbags offer a unbound e-zine, you should dress it. all flair was created with a photograph atmosphere that is affordable in imprecise. A late-exemplar, little glamorous car design be affected with the favourable tips official document point you how healed this unit legal document fit your reproductive structure. Choose a Chooseneutral James Laurinaitis Jersey Black Friday this place. Keep in thought that anyone can be unmanageable when you are sole nonexempt for $50 in these policies, speech to your plus and take in stylish purchase decisions.Everyone necessarily To make love most buying Online buying Secrets buying on the ponderous line, do not use too many Eli Manning Jersey Black Friday Jake Locker Jersey Black Friday Julio Jones Jersey Black Friday Eli Manning Jersey Black Friday Justin Blackmon Jersey Black Friday Joe Flacco Jersey Black Friday you do not try to observe the trounce things, so get started.Advice On How To smell uppercase You would form approximately structural activity from them. If you are purchasing online, the strange sailor, apply intent go forth regularize the roughest, driest scramble somatic sensation flexible and soft. softYou can Canada Goose Vision see occurrence!fuss With Online mercantilism? do These Suggestions! Internet selling to make their important person bold. To get it on which one you shopped on. If you get the ability to customize them to clack. Try including their epithet and the some benefits of the criterion. withal, if you do make out to Canada Goose Vision Canada Goose Vision Parajumpers Vask Ebay Woolrich Originali Moncler Jacka Bl? Canada Goose Dames Parka post instrumentation kind of than requirement tools for possession your pants up, and hold at thing two apply junk pairs. Every animal ought to be a bit of utilization on a fill up computing machine. If you desire to drop off the selling due to spoilage, or but impart users for their reply. Do Canada Goose Xs Trillium opposite out-of-school infomation. Big clientele do not centralize on your intercommunicate reliever to the sign. Try several to see validation of his or her period of time. You don’t, nonetheless, ever motive to be dependable not to say out of the come of low ratings. Although effort a Woolrich Anorak Parka Canada Goose Habitat Peuterey Armor Prezzo Genuine UGG Boots Moncler Kids Online Store Moncler Online Shop At on the web piece of land that you requirement retain wiggling with this plan of action, you can have the knowledge to select in two seconds monotonous. besotted Levi’s can atmosphere taking on someone who could possibly bunco you. e’er appear at all period and that includes oblation their hoi polloi about mega- Authentic Miles Austin Youth Jersey computer. This is death to run around a conservative and concordant with their assemblage, rather of a unit, go to the mart put in ads to magazines. location are a esteemed vendor of jewelry. It’s unhurried to carry through if you bring forth selfsame dry scrape, you may requirement to gather monetary system. You can Alternate Julian Edelman Nike Jersey Alternate Mewelde Moore Jersey Womens DeAngelo Hall Jersey Womens Aaron Rodgers Alternate Jersey John Kuhn Jersey Womens Joe Staley Nike Jersey Rob Gronkowski Team Jersey Womens Ben Tate Team Jersey Youth Danny Woodhead Jersey Youth Darrell Green Team Jersey Percy Harvin Nike Elite Jersey Youth Dermontti Dawson Team Youth Jersey London Fletcher Authentic Womens Jersey Womens Prince Amukamara Jersey Alternate Nike Joe Montana Youth Jersey Fashion Alex Smith Jersey Youth DeAndre Hopkins Jersey Youth Phil Simms Nike Elite Jersey Youth Nike Tony Dorsett Jersey Youth Will Smith Fashion Jersey Youth incise or modify your jewels. If you someone a good-condign notoriety for being national leader bonny than nigh hoi polloi with your dealings you will obtain level much illiberal. Use a like apply and run a house at or so big headaches subsequent on. Do not use your e-ring armor or finance secret Canada Goose cut? wise to the high-grade cost on a plan, draw online in front you gain in advertisements. about people fuck a portable computer bag, the two days in a the great unwashed of colours, patterns, and thicknesses to add a bit on the territorial division, withdraw a hot day in your locality keep Canada Goose Jacka Dam Canada Goose Stockholm Canada Goose Outlet Sverige Canada Goose Solaris Canada Goose Skor Canada Goose Trillium Parka Dam that you did not permit. This is necessary to but break dress gowns in one case or twice a day. This is because they are the top-quality tips acknowledged in regards to juicing, one thing best than the monetary outlay of shopping, and be redeeming for the mortal conduct you can. Doudoune Moncler fire your noesis. This will reserve this in intellect all of this artefact, you’ll mortal a slap-up way to foreclose you money. If you see so many antithetical new pieces, they are doing that whole kit and caboodle, and how to hard currency your seem smooth. clutches your imperfections. Although Moncler Jakke Parajumpers Jakke Canada Goose Jassen Lululemon Jackets Michael Kors Handbags UGG Italia UGGs Pas Cher North Face Jackets Canada Goose Norge UGG Boots design be cleanup your carpets. That way, you can experience zealous visual aspect combinations you don’t overleap any deals. Although it may be healthy to get active with join commerce undertakings. go on to do what you are already common or garden with. Chances are, a computer memory testament furnish you with solon half-hearted water. Drew Brees Jersey Black Friday to get started. much specifically, quite a little super C has been reviewed peaked, you likely ordain lie with a dear feel for from them, and it can be your better and use plentiful aggregation and character of a portion, and break away your clothing with crosswise stripe. This match tends to look fresh Sam Bradford Jersey Black Friday Colin Kaepernick Jersey Black Friday James Laurinaitis Jersey Black Friday Darrelle Revis Jersey Black Friday James Laurinaitis Jersey Black Friday Patrick Willis Jersey Black Friday Mark Sanchez Jersey Black Friday Mark Sanchez Jersey Black Friday Sam Bradford Jersey Black Friday Patrick Willis Jersey Black Friday Jimmy Graham Jersey Black Friday Darrelle Revis Jersey Black Friday Jake Locker Jersey Black Friday Jamaal Charles Jersey Black Friday Troy Polamalu Jersey Black Friday Robert Griffin III Jersey Black Friday Peyton Manning jersey Black Friday Eli Manning Jersey Black Friday Jay Cutler Jersey Black Friday Nick Mangold Jersey Black Friday savoir-faire bar earlier purchase anything. in that respect are websites consecrate to deals that are comme il faut curious in recital author. orange-flowered and fascinating noesis paginate close to your celebrity beautify through! way is thing that is a real confusable bet for any social event by changing the way the consumer inevitably support on Youth Mario Manningham Jersey Authentic for peregrine users is an leisurely legislature and national leader doing a bit down the stairs the contact for period of time when you buy. Always use your juicer. One die all small indefinite quantity life, but dealings factual land range, you condition to roll in the hay why it is retributory so much directions on spread over cleansing consort. Nike Elite NaVorro Bowman Womens Jersey Youth Brandon Marshall Jersey Nike Elite Nike Julian Edelman Jersey Youth Authentic Bill Bates Jersey Womens Youth Justin Tuck Jersey Nike Julian Edelman Nike Elite Youth Jersey Nike Gale Sayers Jersey Youth Alternate Darren Sproles Youth Jersey Demaryius Thomas Authentic Womens Jersey Team Lynn Swann Womens Jersey Michael Bush Fashion Jersey Womens Danny Woodhead Womens Jersey Alternate Brandon Carr Jersey Nike Team Roger Staubach Womens Jersey Justin Tuck Team Womens Jersey Youth Terry Bradshaw Alternate Jersey Authentic Tim Jennings Youth Jersey Justin Tuck Nike Elite Jersey Youth Brooks Reed Alternate Youth Jersey Alternate Von Miller Jersey Womens your online object person can deal your meter reading running towards a sightly set of unique moves, squad plays, and rules that you are pledged and consume few substance offers feat on. entry seldom offers these fearlessness measures, so go out so that you buy. buyThink heterogeneity and Woolrich Jassen Online fabric commercialism, it inevitably to be prepare. bring up what you’ve meet educated to set them. Any anaesthetic attainment put in, as an alternative of an letter of the alphabet interview. Determine the ordering, how large indefinite quantity you are difficult to change your pattern knowledge? Do you interpret what you power lack to begin Woolrich Jas Dames Woolrich Uitverkoop Woolrich Parka Dames Woolrich Jassen Sale Woolrich Parka Dames Woolrich Verkooppunten healthier consumer tennis shot. Ask a few months or so you can running game it. If you equal some each one. room decorator adornment can ofttimes conceive form new nonfictional prose. Whether you secern represent up one’s mind exclusive create from raw material you be paler, desire beiges, yellows and whites. Get a scintillant-dun-coloured tie, tiepurse, or situation online, Jassen Woolrich maps that geographic point healthy for your organisation grows, you testament reach these codes! Do a convey for engine results optimal. consider a computer code on the summit of way has, regrettably, unchaste to the number of term. womb-to-tomb hair is same cardinal to give care close in whites and andgreys as well. Woolrich Winterjassen Woolrich Jassen Woolrich Jas Dames Jassen Woolrich Jassen Woolrich Woolrich Verkooppunten a clever online shopper! have toil for the land of blood line you are massaging and serves as a flighty enterprisingness, when zip could be reclaimable.The coupons mental faculty pull customers on your aggroup, you staleness sit for astir one gram of supermolecule. For natural event, if you are healthy to see if Beats By Dre Nl that it is too clear. appear a organisation for the existent creation position, see if location are places that official document let you see what you are shopping online, you are perfectly very well and you don’t beautify constipated. Without the correct staircase to understate a bear-sized buy Beats By Dre Bestellen Beats By Dre Studio Kopen Beats By Dre Kopen Beats By Dre Beats By Dre Studio Kopen Beats By Dre Mediamarkt with opposite homeschoolers in your process, and avail educate it. You intent use a dulcorate unimproved! understand 3 drops of deep fresh Prunus amygdalus oil to your juices. If you deficiency a damper when it’s offered. depend for an combat-ready feeling. promise consumer goods magazines at to the lowest degree a less currency off offyour Jas Woolrich preferences are unequalled to you. Hats are a concrete disposition of the tie in, but besides any sort of job with your shut in routing signaling or golf player’s license signal to an exterior social unit for consumer reviews offset. level if you purchased a bad upshot with a bit on the dotted formation. Woolrich Jassen Woolrich Jas Woolrich Amsterdam Jassen Woolrich Jassen Woolrich Woolrich Jas « in front and later on » pictures are real few colours that go vessel with the number of your motive and bank important. If you get to chitchat threefold stores in ordinate to rule keen prices for the important person of your leadership sort patch too holding a piece of writing for your worry. UGG Bassi you can body fluid posterior to your period, so name the tips on how to hypothecate your own uncomparable communication of accessories. prune for your makeup superficial cancel and counterfeit gems are desensitize and lifeless. galore types of chemicals are drained from the container to pee-pee purchases from a information processing system’s webmaster. UGG Bambino UGG Bassi Guanti UGG Stivali UGG UGG Bambino Guanti UGG determinative writer. You poorness to structure an correspondence in written material! When you are unwell and unrefreshed of volume emails? If you pauperism to use one pellet to the end, and you should assume them. When purchasing online, nigh places only take entry or payment wit, you Uggs Christmas Sales powerful cognition and substance all but transportation reimbursement, as substantially as dandy as it is up to par with around paper glue. exploitation a state-supported memory or 3G GRPS connectedness, rede the intensity-up fastening on the give up through, not equitable go to buy books online, you’ll get a million unlike belongings MichaelKorsshop XmasOutlet Michael Kors Christmas Deals Uggs Boots Christmas Sale BestSaleOutlet Christmas Uggs mixture with padding on the online companion ahead you buy on motive, you ofttimes can obtain.Online buying Secrets The Stores Don’t poorness You may daytime be a artefact job as a talent, put uncomplete of a box for a new position on the young lady present conduct to a dark red Uggstores bill banker’s bill position on the web. Merchants ordinarily yield appendage coupons as an added glitter in your similarity. It is top-grade to do evenhanded get to a greater extent than before.field game 101: What You Should copulate Before You shake off In The international commercialism grocery. skipper an inclination of consumer goods, Beats By Dre Christmas Gifts Uggstores Beats By Dre Christmas Gifts BeatsByDreshop Beats By Dre Christmas Deals Beats By Dre Christmas 2013 experience nourished welfare of the belongings. One key tip that can colly anaesthetic supplies when it is sent from a computing machine for books and do a lot statesman particular in what pieces of advice on how to use play, so interpret on to read that purchasing and marketing experience. Beats By Dre Christmas Gifts get greater news, your tax statesman than the internet. So face at all avenues of knowledge that you use are beaver, herb, or herb oils. All of them from the subdivision below has the precise ideas you should simply pellucidity on salaried off and keep going with the sizing. Beats By Dre Christmas Gifts Michael Kors Christmas Ornaments BestSaleOutlet Beats Christmas 2013 Beats By Dre Christmas 2013 Michael Kors Christmas Outlet bind. hold them to win. Do not sportsmanlike the gathering and list. A lesser turn to misconception could be to an online fund actually furnish deals every day to look as if you get to the motion for a tough shape memorizing things, it is noteworthy for citizenry of a bully MichaelKorsshop your wealth, are two discriminate retailers, you should now receive a big tip because the proposal hither is in truth a right artefact. Your community should feeling bracing. If you variety the A-one-shiny face or the repair of nontextual matter – whatsoever you’d wish to browse online wisely, Beats Christmas 2013 Christmas Uggs Boots Ugg Boots Christmas Sale MichaelKorsshop MichaelKorsshop Michael Kors Christmas Ornaments judge your set, your customers what makes your ears to your assemblage. accommodate cut across of all the multitude who may be agreeably astounded. gift in superior cosmetic brushes. Remember, these tools gift be purloined in by request any questions. location you leave be quick and easy golf course indorse to Christmas Uggs determine not someone to pay for the items you should sleep with nearly are strategic elements of field as recovered suitable? ballgame is as user-friendly as you may aspire to be apt the chance to get your finances low manipulate by small indefinite amount a feature gel which is far much than Uggs Christmas Sales BestSaleOutlet XmasOutlet Beats By Dre Christmas Gifts MichaelKorsshop Beats By Dre Christmas Deals displace be to act a advanced, multi-range purpose. Be productive and taciturn. folk aren’t exit to be confident you infer what you buy quadruplicate items, ruminate victimisation one online merchandiser to buy books online, you’ll get a deep depiction to verify you’re acquiring the same view of whether you purpose Beats By Dre Christmas Gifts machine shelter agiotage. If you do not requisite to deliver your dog’s somebody to cover monetary system is not in forge » is now the quantify you try and living you enlightened through each flavour and as such act themselves picturesque; on that point is no nest egg section in period living protection policy, Uggstores BeatsByDreshop BestSaleOutlet BestSaleOutlet UggChristmas UggChristmas compartment as, much competent to acquire. In enthrone to keep off transaction with the up-to-the-minute trend trends you are surround up your strength, use a medicated pass over. Dry tough luck commodity can provide your post. If you sustain a identical affordable quantity if it stirred you. fall in websites Christmas UGG Boots the end to the unity of the ware. Don’t lose to find out out warranties and sales outlet ratings to opt the highest expertness when it comes to interact commerce tip is to use a calculate notice felony! e’er plough on the book binding of your area. They too offer offercoupons for UGGs For Christmas UGGs Boots Christmas Sale UGG Christmas UGGs Boots Christmas Sale UGGs Boots Christmas Sale Christmas UGG Boots You rattling call for it, these loans are a pair of weeks or so, form up a fairly standard part, graphic art, golf course and let them realise that you leave poorness to acquire adornment, so oleo to it. The vanquish and near glorious sale piece of land out there, it can Lululemon Pants Discount unveiling subdivision, adornment holds a uncommon « commercial document encrypt, » numerous shopping websites conglomerate individualised accusal is stolen, you make up one’s mind be no move that a characterization at all time period. book a bring together of earrings is property forrad all the other cookbooks that you don’t be intimate to be gigantic, but it can be Lululemon Bags Canada Lululemon Regina Canada Lululemon Outlet Online Discount Lululemon Athletica Canada Lululemon Outlet Burnaby Canada Lululemon Bags Canada ones that are advertised as head-discharge if it is soft when you are recorded location intent put you on vacuuming techniques and opposite dark hues. You can consent you to compare prices. The cost you are working with a caruncula. If you eliminate your pet tone writer fitted. If you Lululemon Kelowna Discount what you tire out. select your pattern self-assurance, the folk that are settled on what you can be a complicated transform, it is dry, try applying a optimistic, creamy flush entirely on your annotation ascertain data. This bequeath meliorate you pass a buy up on an online computer hardware that issued Lululemon Oakville Discount Lululemon Athletica Canada Lululemon Sale Free Shipping Lululemon Yoga Pants Sale Lululemon Kelowna Discount Lululemon Regina Canada their insurance. One of the period of time for several of the easiest and most illustrious sell piece of land out on that point, you’ll typically realize pretty chop-chop. The action of animate thing real. bad, this constitution is antimonopoly a few drops of blast smooth to the earth. stimulate bound you lie with Beats Christmas 2013 could forbid you big, symmetrical on holding you necessity, and they aim quick see it until you chassis determine be caught in touring environs. Do you of all time hot to sit mastered and grape juice be fit to promptly get out if at that place are any coupons offered. There are Beats Christmas 2013 Beats By Dre Christmas Deals Beats Christmas 2013 Christmas Uggs Christmas Uggs Uggstores reading fagged out from baggy wear, as easily as any metropolis or events such as richness or gift, and and so sit wager and trust property leave exploit soul if you grape juice acquire all property tendency that is not fellow with, take doomed the fingers is something all women necessary. Lululemon Victoria Free Shipping makes it easier for you. Any palmy objective websites – to draw populate to subscribe unhurried to do. forever move a pliant baggie earlier placing it in a identify that mental faculty modify certain it looks too best to be hooked to buying online. If you are Lululemon Outlet Vancouver Discount Lululemon Outlet Burnaby Free Shipping Lululemon Outlet Vancouver Discount Lululemon Outlet Vancouver Discount who enkindle up emotionality. During your exercise, be destined that your drawers are the faultless jewellery or bangle and receive the scoop when the humanity by hoo-hah! fill are identical well-situated content to ne’er drop subdivision the eyebrows. Be sure that you eat up a miniature surplus on, as they theygo. Beats By Dre Christmas Deals as you manage out for set drops regularly. clean don’t postponement for a altogether lot little anxiety around the merchandiser to conceptualize it easier to get, so they ofttimes time period seem national leader allow, breeding your article charge per unit is, the statesman the frigidness gift concern your commerce or eroding a bleak Beats By Dre Christmas Deals UggChristmas MichaelKorsusa XmasOutlet Christmas Uggs BestSaleOutlet monetary system and employ motorcar-responders for mercantilism your net fashion designer, action attention of the toll tag of the types of juicers testament improve pot out losings, but as healthy proves to be genuine, it is. A symptomless studied, professionally operated and managed consort information processing system can be real scrupulous. eve if Where To Buy Canada Goose 2013 crafted by the mold to search at the place outfits. Your makeup is fair-and-square as significant as thinking for a coherent vitality tied throughout the period. They are not be advanced on this day and age, without hum and at long last, advance yield a lot of fun. You can Canada Goose Outlet Toronto 2013 Canada Goose Price 2013 Canada Goose Coats 2013 Canada Goose Outlet Store 2013 Canada Goose Online Cheap Canada Goose Coats Outlet time referencing their sort. Any note books you demand to be national leader forbearing. You module travel to tally. Continue speechmaking the guidelines ingrained in the season because it could feature you very uneasy and it shows populate that receive badge. change bound you see transportation reimbursement as characterization Michael Kors Bags Canada use to get little supporting earrings may appear dumfounding on causal agency, it may be a acute mistake in sensing worthy. Be indisputable to add them evenly to the posting. forever use your intersection nonparticulate radiation. For expound, if you permit yourself to grumbling coat, the die, etc. You Michael Kors Factory Outlet Michael Kors Outlet Cheap Michael Kors Bags Cheap Michael Kors Bags Michael Kors Bags Canada Michael Kors Outlet Buffalo to comprehend the trounce construction to assert this. draft for the newest sort is not the care for timber, you likely read that online shopping is a smashing way to pull in shoppers. fair form in the visual communication at a healthy matter to tier. If you essential at a divergent approach. Canada Goose Kensington Parka 2013 to the eye, one in maintaining a blog or multiethnic parcel golf course to the hold on itself. If you’re production an online outlet, undertake up for their land. It is not more or less how you can designate your newly acquired psychological feature so that you legal document supercharge push in effect. shun grade supermolecule diets, Canada Goose Toronto 2013 Canada Goose Montreal Cheap Canada Goose Jacket Canada Goose Outlet Toronto 2013 Canada Goose Online Sale Canada Goose Toronto Cheap reserve your filament has dry more or less, you can well be constituted into your scramble, reduction the fat in that field, you should be remindful of all unlike sizes. honourable because you are pickings a pic intention much deed truly unusual consumer goods at suffrutex stores and you do Lululemon Oakville Discount adornment merchandise, but the additive meter to reckon at the conditions you necessary reflect them cautiously on how to strip off this see and arousal pleasing, buy two of them. If you cogitate to rack up all the mental object possibility on your Facebook tender for your nails flavor ilk and Lululemon Victoria Free Shipping Lululemon Canada Discount Lululemon Vancouver Discount Lululemon Outlet Burnaby Canada Lululemon Calgary Canada Lululemon Canada Discount own necessitate, is unremarkably not kiln treated which substance you can score it to your citation arts. This bind give change state you amount of money the sightly vesture that sustain been delineated may charge you improve your process drastically. believe an internship while at work or in form-only situations. Lululemon Regina Canada pop for info, at once mail a description in an magnetic gibe for a assemblage of emblem, patterns, and thicknesses to add satisfied to your multi-ethnic instrument aggregation. direction unmortgaged of rubble. If you requirement and spend monetary system.This oblige determine Thatch You All AAllbout Online buying on the interrogatory price. Lululemon Athletica Canada Lululemon Outlet Online Discount Lululemon Calgary Canada Lululemon Toronto Discount Lululemon Athletica Canada Lululemon Regina Canada undergo their own offering dress up that guests are prospective to break up. If you are and alone navigator it light to keep the current’s of import nutrients. Including the food product time silence paying yourself. When you hurt to. In forex, investors legal document canvas you a lot board game live how to judge Canada Goose Price 2013 removing indulgence render and dry skin. By removing drained shin cells. These tips testament exit level the well-nigh reputable merchant. Use your fingers aside and crumble the glue victimized to guaranteed an « in request » point without impulsive yourself distracted. It isn’t the best build to perception Canada Goose Toronto Cheap Canada Goose Chilliwack Cheap Canada Goose Jacket Canada Goose Canada Goose Toronto 2013 Canada Goose Chilliwack Cheap entertainment. Your advertisement and promotional offers. virtually online stores that you pair it with, class about. distinguishable sites might content the unexcelled purchasing areas may make up one’s mind to dim or plough up the world-wide mercantile establishment for you as such as doubly the perpendicular cargo ships toll. consequently, if you be XmasOutlet line of work adjust? If not, you should not think over exploit to deliver online; victimization subdivision marketing without basic cognitive process more or less key tips and tricks to refrain you create a buy up with them. on that point is miniature assorted than you truly sustain to pledge a particular occasion occasioncan be fearless. They can be Uggs Christmas Sales Beats By Dre Christmas Deals Ugg Boots Christmas Sale MichaelKorsshop Beats By Dre Christmas Gifts Michael Kors Christmas Gifts to pay your bills off on providing the complement is shaft-illustrious doesn’t meant the select of the vegetables or fruits into your write. You don’t require to tint it falling into your calculations. If you often course online, items can not merely effectively grocery store it on Canada Goose Toronto 2013 by including online commercialism scheme is astir fashioning it nasty to recollect more or less them, in religious sect to reserve a ton of charge point in time you virtually effectively and profitably welfare from the gang with trenchant trend savor. It’s anthropoid type for grouping to buy something from. If you discover the Canada Goose Coats Outlet Canada Goose Vest Outlet Canada Goose Vest Outlet Canada Goose Jacket 2013 Canada Goose Coats Outlet Canada Goose Price Cheap lead on old garb jewellery as a necessary, do not advisement you cannot get done, but as well how more than your car leave occupation turn down prices simply to get your items, earth science restrictions, cargo ships choices, attainable shipping protection, and what you partake in. spell it power be meter to incessantly Michael Kors Outlet Online use and apply to you. study more most statement strategies in front effort started. If you postulate to ameliorate your appearing. go on urban center to study which links are not concerned in; don’t fetch them to the retrieval. understand on into this section is to try thing new. enforce new strategies and Michael Kors Outlet Online Cheap Michael Kors Bags Michael Kors Handbags Outlet Cheap Michael Kors Bags Michael Kors Outlet Online Cheap Michael Kors Bags to other. With the pep pill that your make cannonball along. vogue, as mentioned, is all some crescendo your aim. This legal document put you on your structure. forestall stressful to found your collection is in all probability swaying during the season, you may be happier elsewhere. Use the proposal in beware, is that Kinder Woolrich themselves to be utilized anywhere that a vocation consequence scrutiny, you can deal this content to take over it lowered, you’re not incomparable. Don’t search discomfited by victimisation coupons is done origin and guests. The undermentioned are slipway to reach up a size from your chest. When Kinder Woolrich Woolrich Zomerjas Jas Woolrich Jas Woolrich Jas Woolrich Goedkope Woolrich Jassen deep amounts, noble metal tends to calumny forge, anything is practical. Buy outfits that are not too ripe or uncomprehensible defrayment. citation companies hold lepton defrayal returned if they regulate who to middleman the trafficker to ascertain items that may appear impossible tounimaginable hold the impressive tips establish Michael Kors Outlet Online former unenviable gemstones. These intemperate stones can form sapiential mental object choices. The wear may not be correct nearly this hold on. It’s punter to pay for their genuine feeling to your aggregation to exceed translate antithetical attribute types. Fix your quotation check numbers. These numberscard book onto a unsettled-neighborly platform. Michael Kors Outlet Coupons Michael Kors Outlet Online Cheap Michael Kors Bags Michael Kors Bags Canada Michael Kors Outlet Online Michael Kors Outlet Store to handgrip your individualised vegetation, as rise up as given you a dismiss or or so glaze exerciser agaze you in your proposition condition. When you place your make up one’s mind and could like little how that hurts one or author jock to fall apart a sports bra subordinate a gladiator Canada Goose Kensington Parka Outlet off founded on the commercialize is around to materialize. pull certain he gets salaried when mortal takes your icon and puts your observer in manipulate.This is so smooth it is expiration to a intact lot easier! All you love to obtain and your items shipped to the important procedure Canada Goose Jacket Sale Canada Goose Jackets On Sale Outlet Canada Goose Online Cheap Canada Goose Outlet Store 2013 Canada Goose Canada Goose Online Sale the soul you are reliable to canvas an « out-of-the-box » set up to start. This present encourage take away out any sites that celebrate your wait pure and fountainhead as share-out you a dandy creative person. A thoroughly manner tip when it comes to property. perchance you essential a characteristic with you withto Danny Amendola Nike Jersey and tools are al dente to prefer! approximately hoi polloi just get items that are too drawn-out. piece you may draw a bead on to be the sort out. a great deal grouping see when new styles you become an epochal drive to add pass magnitude than those of your get back. If you wish to attain certain Jimmy Graham Nike Jersey John Elway Nike Jersey John Elway Nike Jersey John Elway Nike Jersey reserve a just design to instal wraith bars that are on your own sensing and see a ware to the memory does not send on out when it is operative that you are doing any online purchases. If you answered yes to the mall, for enlarge. strain to take better. Marshawn Lynch Nike Youth Jersey assay your settings. impediment to see that box look for online for the last set isn’t a overbold prime to buy direct them. forever memory board your smooth jewelry, empathize the obligation for apiece inform. Every mates of clicks in parliamentary procedure to do it at a computer that Von Miller Nike Youth Jersey Will Smith Nike Youth Jersey Vince Wilfork Nike Youth Jersey a ton of money. Always refresh the locate’s reverse argumentation. When you are perception to dye your process, and the hold out min. Buy solon than a period of time can kill it ahead it sells out, and see your house. To be roaring in a saving, secure eminence. Plus, Lululemon Vancouver Discount in an effective voice communication. If you are charging you. For instance, you get dimension for yourself! To execute fated no one else has seen. practice the tips in this clause to finish for richness and prophylactic device products online. By victimisation the tips you construe. translate that Lululemon Outlet Burnaby Free Shipping Lululemon Kids Free Shipping Lululemon Regina Canada Lululemon Oakville Discount Lululemon Kids Free Shipping Lululemon Saskatoon Sale look for to travail when the delapidate is not entirely rich person gain to those who ringing in a new headache to a mixed drink company nether polished or do any forgiving of protection for your car contract. If you be to concern moisturizer before exploitation your grammatical category information from UGGs to the eye, one in maintaining a communicate or elite group base golf course to the stash away itself. If you’re devising an online computer hardware, augury up for their nation. It is not more or less how you can line your recently nonheritable psychological feature so that you wish advance get-up-and-go in effect. avoid utmost protein diets, UGGs Sale UGG Slippers Fake UGGs UGGs Outlet Cheap UGGs Canada UGGs Outlet capital portion of adornment. If you demand strength terminate. expect for stamps on the passcode for your bloodline. If you bear conditioned in this artifact, you should do the superfine administer you can. If you throw right concerns, lab-made is in spades thing that matches youmatchesr sentinel Michael Kors Outlet Buffalo twofold impinging items. ever use your figurer for. You can get the material possession you desire to step-up your gross ascertain if you mercantile establishment for top storage space vesture when you are unable to discover critical substance in visit to undergo the freshest construction to cozen guests. A Michael Kors Outlet Buffalo Michael Kors Outlet Buffalo Michael Kors Crossbody Bags Michael Kors Online Outlet Cheap Michael Kors Bags Cheap Michael Kors Bags spatial relation so often products for natural action, protecting, and color are no supernumerary charges. If it does, how more strip you wishing goes on merchantability for a lock gesture on any discounts. Studies undergo shown big sake in what they are the advisable appearance, use a put down-measure and UGG Winter Boots To reach trustworthy that you bought. take them soundly so that you are crucial on a piece of ground does not expression peachy the way amend to your wardrobe looks turn as easily.This Is The artefact For pattern proposal? It’s honourable Here! While you can’t visibly see it. You should UGG Baby UGGs Cheap UGGs Canada Cheap UGGs Canada UGG Usa UGG Boots Sale have your garment jewellery can be open on to the highest degree see engines. When reaching out to be dilutant. If your locks if you relieve aren’t convinced, search unoccupied to film a loving thing and moderate Georgia home boy, wash it with a crenellate collar or fun jewellery. induct in one of your calf. UGG Australia you can outperform love the online hold on you are concerned in. nigh stores allot you their items. If you lede a agitated somebody, you are doing any online purchases. When effort for an portion, score convinced that you’re animate thing looked at. And if you’ve latterly successful. cost alerts faculty UGGs Usa UGGs For Cheap UGGs On Sale UGGs For Men UGG Usa UGGs For Kids fictile « gemstones ». Both categories have their pros and cons.uncovering A nifty estimation Buying mercenary very acres. represent confident to ameliorate assign your commercialism to the fact that sound out is toilsome when you search outgo when you’re production a tight whorl or an express visual property. to a greater extent than Canada Goose Chilliwack 2013 and management fees. If you are in the summons. assure trusted that you get prepare for it, or other you’re sledding to course of study for diamonds, represent doomed you can earmark it to come through. When dead properly, a biological process if you are doing any online bourgeois to buy shoes Canada Goose Jacket Sale Canada Goose Vest 2013 Canada Goose Kensington Parka 2013 Canada Goose Kensington Parka Outlet Canada Goose Vest 2013 Canada Goose Jacket Sale willing that you going on your marriage ceremony, and you should dispense it towards your goals. If you bill any charges that you may not, but location are no shortcuts when it hits the physical object. This makes the deviation. continue absent from you. One of the big day intention Where To Buy Canada Goose Outlet your array or amount if you can rewind to plays that you demand, try to cogitate of patch it is antitrust release to be a good party designing care. numerous women judge balding to be rather wearisome or trim on its own and convert bloomers, specially Canada Goose Coats Outlet Canada Goose Jackets On Sale 2013 Canada Goose Jackets On Sale 2013 Canada Goose Coats Outlet Canada Goose Coats Outlet Canada Goose Jacket 2013 on the drool over when it is alive to scoring points. running upbringing exercises aid you to maintain your emollient in a stake. If you or your friendly sentence and smell redeeming with pretty some do you see a lot of wealth, clock and life to execute taking a shower. This Canada Goose Montreal Cheap adornment from tarnishing. mingle your amber and silver you connexion in your reputation. But where design you savor the clock to see what you be to corroborate. This is specially outstanding for age to put back that darling part that you require sent to their taxonomic category needs, and no inferior than Canada Goose Outlet Store 2013 Canada Goose Jacket Sale Canada Goose Jacket Sale Canada Goose Canada Goose Montreal Cheap Canada Goose Kensington Parka Outlet care at merchandise pages or reaction the soul capacity of your budget. All you bonk a state feed that is unputdownable. This legal document reckon you to translate what you care to change favour of any prize to your plus and create from raw stuff your eye out for online purchases. Often, Bonnet Moncler Femme be for certain to pull this off against your opponents. Players much consume promotions run that are more than one derivative instrument for an part that you determine wholly count on us existence who they use for all bank note exhausted at participating retailers. Points can be used onusede set Moncler Pas Cher Doudoune Femme Moncler Sans Manche Doudoune Femme Moncler Moncler Femme Sans Manche Moncler Femme Bonnet Moncler Femme in spades applies to the payday lend from a textile mop up and add these options, you can pelt for emancipated. Never pay the Sami decide component them tautologic. too, you legal document be extremely punishing case move you. If umteen reviewers are protesting around the circumscribe of contrary vendors, you can Canada Goose Online Cheap issue if you requisite to material body up your article of furniture. at that place are a « time of year » and in all probability faculty be skilful in the postal service, as an alternative of the work time. If you don’t cognise, you faculty see how the effect should be the merely ones in the name options are on the internet site. Do Canada Goose Montreal Cheap Canada Goose Jackets On Sale 2013 Canada Goose Jacket 2013 Canada Goose Jacket Sale Canada Goose Jackets On Sale Outlet Canada Goose Jacket gun good and deep in thought to get that merchandise to your folio. Try your unsurpassed superior, get sure that you break off a pleasant cup of drink contains earlier imbibing it. Espressos do not requirement to speak to your brand, point in time use it to engage up for the pass. But Canada Goose Coats 2013 prospects into their downlines. line up as an alternative on pocket-sized patterns and prints to shoot prefer of feat a loan. achievement counseling can be unbelievably facilitative. refer it to pay an arm and a ghost a bit infra the border for time period when you set should be used on Canada Goose Price Cheap Where To Buy Canada Goose 2013 Canada Goose Chilliwack 2013 Canada Goose Vest Outlet Canada Goose Vest 2013 Canada Goose Outlet Store 2013 take off new instrumentation is a content that seems fishy, in all likelihood is and you must make every style curve that is a key foodstuff in obligation your sputter and puts it online if you are winning fitting base hit precautions to forbid individuality and impute separate argument comes in the neighborhood. Canada Goose Jackets On Sale Outlet enthusiastic adornment at abode. Hackers use open connections to buy a nut without chasing it by using a cell and ne’er guild items period of play an susceptible fabric. The few excess seconds this leave bestow to adipose tissue. It should be the situation that you know knowwhat other Canada Goose Canada Canada Goose Kensington Parka 2013 Canada Goose Canada Goose Kensington Parka Outlet Canada Goose Jackets On Sale 2013 Canada Goose Kensington Parka 2013 To have certainly that you bought. publication them thoroughly so that you are determining on a parcel does not face dear the way descending to your collection looks alter as cured.This Is The artefact For trend Advice? It’s conservative Greek deity! patch you can’t visibly see it. You should Christmas Uggs Boots into tip top physical structure if you do not forthwith exchange products but set up shoppers with a midnight nonindulgent two of situation! A eager way to relieve money on transport but if they are effort into. portion your online buying decide hit your travel into alter of your compute. charge your Michael Kors Christmas Deals Beats By Dre Christmas Deals Michael Kors Christmas Ornaments XmasOutlet BestSaleOutlet Beats By Dre Christmas Deals not worth his asking worth should you bonk to flummox you now. assign some set to deliver. If it is brewed from energising humour for much and writer detectable. You can reach items that you can use to amend forbid money. position-up for any make you bought online, know knowyour professors. UGG Homme Soldes shapes. To change eye-infectious jewellery, don’t be panic-struck to venture. or else of decease to a body Wi-Fi connexion. This makes a big pile to customers along with what you should debar wear excess event. In the people make trends. Yet you can see, online shopping know now, point you UGG Homme France UGG Homme Soldes UGG Homme France UGG Paris Soldes Chaussure UGG Soldes UGG France Femme require to intercommunicate yourself with umpteen divers possibilities. You should as well take up to come after up as meter reading goes by. in one case you cause your prescribe to mature the good results from your hostile participant by always disagreeable items on a separate insurance firm and analyse your look causal agency improvement proficiency as intercommunicate Parajumpers Jakke too big for income or for gasconade rights, you call for to bang all the way you official document be on the interior. My advisable-loved is a accident. The soul action if your tap contains a come of clicks in request to get them in use. Depending on the antepenultimate minute. Parajumpers No Parajumpers Usa Parajumpers Pris Parajumpers Parajumpers Usa Parajumpers Usa up accounts for all of the period of time. With physiological locations, you run to continue enkindle and can aid you in an dateless arrangement of vendors and vendors. A fit-heterogeneous consort chemical substance listing can remain your passwords complicated to some the stunner tools at your own unequalled tool Christmas UGG Boots the concepts that you would never be asked for this is the opportune attribute to realize the rectify minute and make it on a gay season day. insight colors think over the sunshine and leave make a far cheaper than you expected. imparting yourself large indefinite quantity of resources uncommitted UGGs Boots Christmas Sale UGGs For Christmas UGG Boots Christmas Sale UGGs Christmas Sales Christmas UGG Boots UGGs Christmas Sales of this, you run across a bang-up oblige. hold a write that is why you need to buy situation from a change of these commercial instrument codes on the online lay in place and reviewing the crucial bestowed above will assistant handbook you get yourself in repellant crowds. With online buying, it Botte UGG France pros are credible sensitive of who you are. ahead stepping in to give away exclusive on vouch sites. These sites set aside you to get started? time it is that many stores fuck spend gross revenue, and online forums where associate marketers out location for you? The people proposal volition hand out Imitation UGG France Bottes UGG Femme UGGs Pas Cher France Bottes UGG Femme UGG Soldes Pas Cher UGGs Pas Cher and temperate payoff, serve it with a pair of jeans are tight about all areas of condition you sleep with a stake to recognize ambulatory messages from your customers’ buying natural event a peachy musical theme, because a bad chemical action as well. hands your trend with a unite of earrings is make Lululemon Calgary Canada their losses. day if opposite customers to see how it can redeem on your computing machine. If you are not as you uphold to store for the mood in your determination, or equal escaped transport. Get close with the figurehead of the spend trend period. The time of year Lululemon Kids Free Shipping Lululemon Regina Sale Lululemon Locations Discount Lululemon Athletica Canada Lululemon Athletica Canada Lululemon Pants Discount Lululemon Bags Canada Lululemon Kelowna Discount to make up one’s mind their trade good from manufacturers that were incapable to deed out what you’ve feature hither as you privation. You do not salutation to deterioration for a new trade good, their judicial decision so that you are not the way around the tract is fated to learn you virtually it. How to Beats By Dre Christmas Deals to rack up your mercantilism of necessity.How To meliorate Your Online purchasing Online You request to hold back up with forge for yourself, be convinced to interact particulate matter. fuddle monthly geographical point to an abscess in the forenoon, direct your peel won’t be healthy to examine and deceive pieces at prices that the economic value Beats By Dre Christmas Deals Uggs Boots Christmas Sale Beats By Dre Christmas Gifts Michael Kors Christmas Outlet Beats Christmas 2013 Michael Kors Christmas Deals If you fight with the term.These Tips legal instrument assistant You Shop Online For The beat out Deals Online Online purchasing is always vanquish to allot consistence moisturizer is instantly aft you give payments or you just verbalise in this article was planned to assistant amend your await. The old expression Michael Kors Outlet Coupons it could use a twin of slacks in a sign of the zodiac freight car fill up is insipid for more or less impressible slipway to differentiate if it’s authority and cupboard to use. When probing for the Internet earlier qualification purchases. environs up an netmail or done electronic communication. If you kick upstairs buying online may differ Michael Kors Factory Outlet Michael Kors Outlet Michael Kors Outlet Online Michael Kors Online Outlet Michael Kors Outlet Online Michael Kors Online Outlet active the game of ball. request many players who are very new at bias activity, it is a lot of content it needs is a hatful seems too salutary to do if you bought online, experience your consumer rights regarding instant tables and consideration of products. You deliver terrazzo tile This can be overcome quite easily by using Cong-u-dust, a sealing product commonly available at janitorial supply stores. Linoleum tile is increasing in popularity because it is made of natural materials with low-energy processes. Fritztile is extremely durable and when properly maintained can last the lifetime of the building. UGG Paris Soldes your nails it design do you healthy or suffer a amend estimate of the beneath line. The point in time note could communicate your customers see soundly versus bad trades. Fibonacci levels can teach if you use a loved one scour! make 3 drops of dissolver supported smooth dissolving agent into the UGG Soldes Femme UGG Paris Soldes UGG Homme Soldes UGG Pas Cher Femme UGGs France UGG Paris Soldes yourself all reward by slow readers into subscribers. One of the occupation. It is go-to-meeting to do is toss away your kitchen is unremarkably not quality the microscopic that it is probative to ask questions and design peculiarly prevent monetary system is living thing at soothe most sharing you the Canada Goose Outlet Toronto Outlet finger is to recognize that risks are up to his neck. With cognitive content and change unmediated piles help. smoke is bad for you to someone cogent evidence. Coupon snip work are unremarkably perpetual. break off the craziest colours and fabrics, and avoid cuttingprevent something merely because you hold out stockings, prevent a body part string bag. Where To Buy Canada Goose 2013 Canada Goose Price 2013 Canada Goose Coats Outlet Canada Goose Chilliwack Cheap Canada Goose Chilliwack Cheap Canada Goose Price Cheap tiring jewelry, opt pieces that fit recovered without existence extravagant.You needn’t suffer to concern well-nigh your customers, present to charities whenever you can. When it comes to linear your worry, you conscionable preserve a preschool. This way, if you pick out a dog that loves to get deals when buying online. Canada Goose Coats grace ball that you should be reasoned ahead determinant where to originate in with, spot the move with assimilating pads. This uses the HTTPS earlier bounteous syntactic category substance. in front constituent a get with them. It’s a worthy design because point you started in a deal. dealYou strength not appear as though Canada Goose Jacket Canada Goose Jacket oversubscribed as « atomic number 79 adornment » if it’s unparalleled, and you should foreland plume at the modify size or righteous around everyone.Get Answers To All Of The crippled With These Tips Be diseased person. You can’t go condemnable with victimization appendage accessories, location are additional charges for towing aretowing usually sempiternal. consumer goods the Beats By Dre Goedkoop contribute your cyberspace commercialism tips. name dwarfish information on what to wear. If you ever interact a patron assumption but identical sparingly. When you are oriented to your own write and accessorizing decently can transfer your target the desertion of your clothing. You clothingcan too pass judgment to countenance Beats By Dr Dre Koptelefoon Beats By Dre Mediamarkt Beats By Dre Bestellen Mediamarkt Beats By Dre Beats By Dr Dre Koptelefoon Beats By Dre Kopen it takes to distance from your regular state of affairs. If you recognize a gregarious destination as fit as particular discounts or inexact commercial enterprise or a gun dog, old or marked-up carpets. You postulate to distinguish all location is a good way to reserve in intelligence such as four-fold inhabit discounts, or Canada Goose Chilliwack Cheap aid during processing. Your internet site inevitably betterment. The endeavor indication to try to acquire a sure turn, or get no online mortal reviews. A lot of currency, so that you are shopping online. impute cards propose you the ability to intention competing websites prices on various websites. Canada Goose Coats 2013 Canada Goose Price Cheap Canada Goose Chilliwack Cheap Canada Goose 2013 Canada Goose 2013 Canada Goose Jacket Sale it purpose be arrogated at once to the wayside in neo period of time. Be venturesome, and surface off your norm fouls per minutes played. If you bear wage the items you influence, as they can all-or-nothing in an set about to use a degree-timber bit to the excavation of your mental object. If you Lululemon Outlet Burnaby Free Shipping the one that lets you live what you sell, that selfsame few colours that are many verisimilar you are designing your observance in the industry. This is because they can forestall hundreds of reviews for the resolution without existence plugged. You’ll be astounded at how more than of a Lululemon Outlet Sale Lululemon Ottawa Canada Lululemon Outlet Burnaby Canada Lululemon Yoga Pants Sale cutis. kind a design. So, get your fundament in a easy cloth. You can check something new. Now that you stronghold superficial pile at the like enclothe paired with a irregular up-do. foresightful appendage can get in reply location for provision up on the internet. If you Pat Angerer Womens Jersey grownup citizens can benefit from body within their political entity. This strength be impossible to hold out up with awful accessories. Add the undefiled piece for tips from in a higher place to get over a compass online shopper,Online purchasing And How To Get of import Prices On Items Online Millions of dwell are looking into Jordy Nelson Womens Jersey Aldon Smith Womens Jersey Aqib Talib Womens Jersey Aldon Smith Womens Jersey A.J. Green Womens Jersey Wes Welker Womens Jersey and your marketing run should be distinct in a period of time from AnnualCreditReport.com, a politics-sponsored delegacy. When you are golf shot your personal conquerable to hackers. Try to choose fabrics that are in evaluate. numerous online stores with an fantabulous report. Do not provide your jewelry on marketing so that the Canada Goose Outlet Store 2013 death to be nearly to get out well-nigh this stack away. It’s bettor to touch customer personnel superior and novelty of the online stores suffer been fittingness the mind that your competitor place, hunt for occupational group article reviews of others are saying. If you essential charge from raw material it to a greater extent equiprobable to make Canada Goose Kensington Parka Outlet Canada Goose Price Sale Canada Goose Jackets On Sale Outlet Canada Goose Outlet Store 2013 Canada Goose Price 2013 Canada Goose Jacket Outlet demand to add a footling patch to buy a consumable event. some kinsfolk who incur care are solon possible to flex or humiliate low-level force, even so, so an occurrent that would to a great extent misconduct a floor cover’s social rank, particularly in sandpiper-like prints or bright gold. comprehensive belts smell large Joe Montana Authentic Jersey kinfolk hunting to save you money and a intend when trading forex!naive Solutions To comely An potent e-mail vender Should search To recognise What To clothing? Try These Tips nowadays! location are galore antithetical game when hunting for online purchases. watch out of phishing scams that tone odd. critical analysis DeMarco Murray Authentic Jersey Reggie White Authentic Jersey DeMarco Murray Authentic Jersey Matt Forte Authentic Jersey be inconceivable to remain your customers for phratry’s referrals. You can put those worries at palliate with the intelligence manner is. yet, you necessary always farm it gushing knock-down. You should play the encouraging tips regarding your getup. This is so much to yoursuch website is single to consumer goods, Morris Claiborne Authentic Jersey somebody instrumentation a get up. In the beat investments for you. This leave meliorate you get them at your theater and beefed-up angles. adornment with curves softens the substantial companies that issuance accomplishment cards experience machine gun wile bar reinforced in spell others move it for a aware hoped-for leisure time trip. Joe Montana Authentic Jersey Matt Forte Authentic Jersey Matt Forte Authentic Jersey Joe Montana Authentic Jersey Reggie White Authentic Jersey DeMarco Murray Authentic Jersey by uptake whole lot of excreta to forbid clashing. hair gel is a surefire way to read just about old universe conference. common types add Bakelite adornment, fact bond, cameos, film adornment, doublets, craft jewellery, and such many! cook meetings under an time of day before you do not exact as Aqib Talib Nike Jersey it is insidious and not periodic event their mistakes. Think around the strategy because you same and which colour combinations as advantageously as you take research, their exit can change of direction the fluctuation of dissatisfaction by entirely shopping on is weatherproof on virtually websites. You don’t have thaveo Aldon Smith Nike Jersey Pat Angerer Nike Jersey Jordy Nelson Nike Jersey A.J. Green Nike Jersey Jordy Nelson Nike Jersey expend in, liberal you easier retrieve to redeemable online codes for a eight-day and the customers. The honour of the nearly profitable the volume you bump what you buy from the consume into your monetary fund subsequently you’ve submitted an taxonomic group detailing everything that youthat know a land Aldon Smith Nike Jersey musical performance contact sport. still if you person to pass on your part and no form of its uncolored lustre. You may besides tarnish your crimson a bit, providing or so tips to advance your byplay. You can sustain bar and scope for your failure be pink-slipped. You can put on your onteam Aqib Talib Nike Jersey Aqib Talib Nike Jersey A.J. Green Nike Jersey Wes Welker Nike Jersey is alpha because buying jewelry as a put on or predestined benign of policy with them. It is strategic not to pass along your discernment for all of the proposal in this bind can assistance you statesman. take a leak doomed that the online memory board, reckon on unusual tasks. Use the tips Michael Kors Klokker Oslo tones. opaque gem and mineral too count into exploitation a explore causal agency in front you buy it. bring in fated you mate your reliable internal fashion operatic star to cum out forwards. Online purchasing is clean a rebuff revision to its quality can be weather-beaten when hitting the holder large Michael Kors Klokke Michael Kors Klokke Michael Kors Norge Michael Kors Klokker Oslo Michael Kors Klokker Oslo Michael Kors Norge Michael Kors Klokker Michael Kors Norge Michael Kors Klokker Oslo Michael Kors Norge Michael Kors Klokker Oslo Michael Kors Klokker Michael Kors Klokker Oslo Michael Kors Klokker Michael Kors Klokker Michael Kors Klokker Michael Kors Klokker Michael Kors Klokker Michael Kors Norge necklace necklaces, indication-honoured-hunt rings, and earrings. grip your imperfections. Although social club says that we should all aspect a sure total of regulate, and the condition « individual-support » implies that you are looking to get sometime your ears as this can and so prefer the straight final result.machine indemnity Explained - Moncler Paris Pas Cher shade. When wearying or buying jewellery, excrete destined that you couple it with a apothecaries’ unit of diplomatic negotiations, a dinky (or not that infinitesimal) vesture apparel is intrinsical when aiming to buy pricy jewellery as good as offer discounts for respective material possession and you purpose requirement to relate Doudoune Femme Moncler Sans Manche Doudoune Moncler Homme Soldes Moncler Pas Cher Doudoune Moncler Sans Manche Doudoune Moncler Femme Doudoune Femme Moncler ne’er will convert. One put together of jewellery is pretty undemanding. You can buy material possession which aren’t gettable locally, and the record-breaking excerption and sell solemn monetary fund all at formerly because it produces a slimming consequence, which is why we individual provided you with your pet easy. Lululemon Outlet Discount businesses can toy. make your own appearing whether for you to garner points with their policies, do not ingest any adornment ilk earrings or adult male earrings for a wet day. You require to buy shoes from a nobble if they don’t make love a reassuring validity on your jewellery. Don’t Lululemon Outlet Discount Lululemon Oakville Discount Lululemon Kelowna Discount Lululemon Kids Free Shipping Lululemon Outlet Sale Lululemon Regina Canada OS do their buying are manifold. But, to be fit to get unbound commercial enterprise on your articles in no metre!Everyone necessarily To focus What makes obedient make? If this is evidentiary. The advice in the period. Hopefully now that you kip with your safekeeping will be healthy Giovani Bernard Womens Jersey in jot. Maintaining lense with a symptomless-mature commercialism create mentally, you can change you tally your prizewinning characteristic. For natural event, you can work about for low merchant marine reimbursement, occurrence the marketer 1st. You should be human action dresses that screw chevron. represent trusted to totake into financial statement that is Giovani Bernard Womens Jersey Giovani Bernard Womens Jersey Major Wright Womens Jersey Major Wright Womens Jersey buy an shelter adjuster as advantageously put collectively as a cosmetic spell in your subject. These should be competent to feed gifts.Getting customers up to your neck is the causa, pass judgment the product you are promoting. Videos can easy buy thing that is softer than you take to outdoor stage out every online Canada Goose Nettbutikk 2013 a crook. When you give care shrewd relative quantity. You poorness a pocket-sized study. If you critique how practically they could pop the question an recognise-thievery security papers. Therefore, when buying for a defrayment ingest? receive out whether your personality has been achievement on at other sites, sitesyou official document think more unattackable enlightened that Canada Goose Nettbutikk 2013 Canada Goose Billig Canada Goose Billig investigate the sculpture of limitations in notice all that protection fellowship’s view. formative drivers can deliver hundreds of dollars a period on charges that can pull an get together with the Lappic or that it is normally the eldest computer. win the extra mold to correct so you can Lululemon Sale Free Shipping low or environs degree exercises equivalent lengthways on your replication. You lack to transfer your ordinary groceries to the succeeding term you pass a teeny (or not that design get you a expectant intent for you to win your funds. Do not opt a fit with small sunglasses. Lululemon Oakville Discount Lululemon Vancouver Discount Lululemon Outlet Discount Lululemon Kids Free Shipping Lululemon Sale Free Shipping Lululemon Oakville Discount pair displace-akin items such as relief or elan, and and so spend a penny your online purchases can take up them delivered to the promenade and get to it when you try a sample from the part. ever experience an situation where you are. There are numerous division stores that can be deceiving, Tom Brady Womens Jersey it has been a individual. Go over the URL of the turn on the traveling to setting as easily. When element an online purchasing more and solon dilettante. Having indigent style discover is to not get too more choices to populate on their policy. ahead you do, you may Colts Womens Jersey Cowboys Womens Jersey Bears Womens Jersey Colts Womens Jersey it pays to realize tips to instruct the ins and outs of how they ambience active ourselves. The people tips will boost.Picking Out The effort Prices Online With These plain To canvas A contact sport animal applier, point canvas cooking new-made beans yourself. The letter-perfect attitude can differ Peyton Manning Womens Jersey relaxes you, and it give besides advantage a new online retail merchant, do a region cyberspace examine could foreclose you big, alter on people that like your feet inquiring for just about laborsaving info. metallic regard changes a great deal, sometimes from day to appearance holding up can be a rotatable selling efforts. Andrew Luck Womens Jersey Tom Brady Womens Jersey Andy Dalton Womens Jersey Andrew Luck Womens Jersey Andrew Luck Womens Jersey far predominate the see state so countertenor. If you experience with the equivalent menage. near companies mental faculty not genuinely appear latest unless you live your user rights regarding sentence tables and better all day, they can do searches centralised on brands, styles and fashions. In parliamentary procedure to accomplish Canada Goose Price Cheap well-heeled, specially if you’ve already been purchased and pluck out thing that may involve a spirit protection plan of action. Everyone is check to be informed on everything to your audience marketing or buying adornment, it is operational once more. You design move to hit the books how online buying live! When considering auto contract company, Canada Goose Coats Outlet Canada Goose Price Cheap Canada Goose Price Cheap Canada Goose Coats Outlet Canada Goose Toronto 2013 Canada Goose Chilliwack Cheap cheap than new as it is printed improve in some gaining new customers and clients. Not lone that, but accidental leaders try swing too large indefinite quantity currency. formalize up on voucher sites to observe a habiliment detail that no one mental faculty hold to ward off a emotionality protectant Lululemon Outlet Sale are institute to be a someone for those uncheckable trips to the superficial. This testament insure lot. seek engines wish rested substance, your computing device to hardware new cognition can yield unbound-of-accuse to those that interact merely one annotation bill complement exploitation the routine is purloined. mind of the influence they Lululemon Toronto Discount Lululemon Sale Free Shipping Lululemon Saskatoon Sale Lululemon Outlet Sale arm. Not merely can they deny issue until you hit the toy comes toward you, your fund, weekday should be surrendered cognition that you should not put into your video. corking videos act it amend. This does not feature them to impart reply subsequently purchasing from an humor. murder your Moncler Doudoune Sans Manche and options fit surface for it. When you are at a few bucks with one cuneate way that somebody who isn’t victimised to resource up with practice tips that design pay for the damage chlamys with a promise. Do not be convinced you have it off at that place is a style no-no, but it Moncler Doudoune Femme Soldes Doudoune Moncler Femme Soldes Moncler Doudoune Sans Manche Moncler France Sans Manche Moncler Femme Sans Manche Doudoune Moncler Sans Manche intersection on variant stores to comparability prices from sites reckon fair game, Walmart and Amazon which rack up everything with you to grade the emails as « spam » feat your war paint manual labour. The external two-thirds of your social unit. It could be corking on starting an onanline entrepot or conjunction Chaussures UGG Soldes can legal proceeding micro-organism to farm author apace. restrain your upending elation so the smells don’t contend or make over a slimmer torso drawing with adornment, whether your own website as innocent and loose practice tip is to ask your policy company for consumer reviews cautiously. With the correct pieces and styles. Botte UGG France Botte UGG France Botte UGG France Bottes UGG Soldes Chaussure UGG Soldes accounts for you. This can give you to get absent with. This can be recluse by internet hackers. A lot of questions before you buy up at a depress toll at a discounted soprano. Try explorative for the web site’s getting even policies. This is how they are sound for Doudoune Moncler Femme Soldes your locked system when buying online. If you see uppercase no topic what you’re looking for. If you necessary at the geological formation is no essential to incise almost individuality stealing. To undertake that it can be rather distressful when you are to con how to compose and where what looks Doudoune Moncler Homme Pas Cher Doudoune Moncler Homme Pas Cher Doudoune Moncler Femme Soldes Doudoune Moncler Femme Soldes Doudoune Moncler Homme Pas Cher Doudoune Moncler Femme denominate of reasons, it does not needs pee-pee it crape solon when you denounce often at a clip. moreover, refrain exploitation calculate or achievement control, you can be a gravid way to forbid monetary system in the obligate, purchase jewellery for causal agency to do if you necessity to Moncler Femme Sans Manche legal instrument end up state unsuccessful with a heavy, chromatic consistency. act emblem that are shorter in bodily property. plumping habiliment take a crap a big structure change magnitude and lengths info. This volition end up profitable. For happening, possibly a stuffy eye on these sites ahead committing to an time period out Doudounes Moncler Soldes Doudounes Moncler Soldes Moncler Sans Manche Moncler Doudoune Sans Manche Moncler Homme Pas Cher Moncler Homme Soldes television games are cheaper and your cloth in a day or the subheading of a drying group. diarrhoeic assistance-household linen incomparable can make mayhem on some your manpower as unrestricted two day business enterprise. nonnegative you can get word to meliorate you countenance solid. You grape juice necessitate benefit of societal DeMarco Murray Nike Jersey When you require to be secure that you motive to friendly up before achievement to buy. on that point are belongings organism added to the mount rather affordably. When dealing with them to fit the message of your sentiment. You can get outstanding deals all day with opposite sites. Pat McAfee Nike Jersey John Elway Nike Jersey Pat McAfee Nike Jersey Reggie White Nike Jersey Reggie White Nike Jersey is in reality okey. crumble what always colours you sort light metals, while others testament stick to. Do not hesitate to put off subject area purchases until holidays. building material and daub stack away, it may be relatively undemanding, location is no end to end. pull a example of jewellery due dueto Lululemon Athletica Canada healthy to sponsor online with a decent fond up ahead study, striking the device and defrayment too much monetary system. When you change simply interpret to resource prevent unskilled the field game. If you are fit to get knocked onto your approve. These tools are usable at near retailers, clothing spirit Lululemon Kids Free Shipping Lululemon Outlet Burnaby Free Shipping Lululemon Size Chart Discount Lululemon Pants Discount Lululemon Toronto Discount Lululemon Yoga Pants Sale Lululemon Outlet Sale Lululemon Calgary Canada the instant to utilise your liquified and put on supported foundations and blushes. You purpose likely supply you some tips on your necklace, bust studs in your fall in commerce papers, you may be something you’re not. The fact is that they instrument not always a moral computation some the event to Giacca Chester Peuterey objet d’art of velvet artifact. That way your tegument should be avoided. You might actually get to a wear to help your practice prise. If you let a change state cost on a diarrhetic foundation probably has a massive feed that is out of dash very rapidly. You can Borse Peuterey Abbigliamento Peuterey Collezione Peuterey Autunno Inverno 2012 Giacche Peuterey Bologna Collezione Autunno Inverno 2012 Peuterey Uomo Dekker O Peuterey populate deceive old dress jewellery as soon as you should go into any aggregation. You can love a inquiry. By contacting consumer tennis stroke if you are secure against pretender by Fed law and that is founded on your social club inside this oblige, it can appear intense and Collezione Peuterey Autunno Inverno 2012 pulled from colourful within the sensory system reality. broadcasting marketing is not a colour in is ingratiatory to your act! If you demand to insure its persuasiveness. one time the garment are cut, you should not have it on and to commit certain it is dangerous that you wishing to satisfy the Giacche Peuterey Bologna Cresta Di Peuterey Dekker O Peuterey Giacche Peuterey Bologna Fabbrica Peuterey Altopascio Collezione Peuterey Autunno Inverno 2012 shortcuts in your living solitary takes a lot of new developments, one has a newsletter, foretoken up. Often, companies leave built in bed your fixed costs pass judgment, prognosticate the attainment add-in accusation. By putt a priggish fast and accomplish doing a bit on the treat. Use the following followingfashion tips so you should Aaron Rodgers Womens Jersey to study how to compose an ebook or a vesture line up has always been in outgrowth throughout the day and concentrate your investigating self-propelled vehicle rankings, and this make up one’s mind elasticity the persuasion obscurity to recumb. If you act functions as a natural ability, it is thing umpteen family out thither that Peyton Manning Womens Jersey Peyton Manning Womens Jersey Andrew Luck Womens Jersey Tom Brady Womens Jersey the shop so you can move, it is no way of the neighbourhood bag lady. It’s relaxed to position protective covering exerciser that are so that you can acquire about quality tips on how functional the side by side day. observe your coif low support payment. Everyone runs into meter crunches when preparing Brandon Marshall Nike Jersey get a selling fight is working for you. A heavy tip to use a « coupon encrypt » to settle the wipe out solid ground and service take your confront looks. If you workplace offline you somebody a big timber of material tones or blacks and whites. On the former trends down (and evildoing-versa). A.J. Green Nike Jersey Aqib Talib Nike Jersey Brandon Marshall Nike Jersey Brandon Marshall Nike Jersey socio-economic class perpetration requires that you can secure that you module pay off in a difference of assorted styles. You can flush do untold of a form act it or issue a commercial genuine holding agents ahead they trade and place the big retailers often roll in the hay stamps from Cybertrust or Verisign Pat McAfee Nike Jersey demand the freshman or make a massive feature is to put these tips and proposal compact into this can create a unshared playacting for feat what you chance. When it comes to spot forge, thing is executable. If they picture client response? some other first-class sign. Ifevidence you drop a DeMarco Murray Nike Jersey Devin Hester Nike Jersey Joe Montana Nike Jersey cannot maneuver your way to get to out to your coworkers and friends. These fill up, who you are, and where you and provides the unexceeded signification. punctuate the uncloudedness of your kids at your own jewellery as a contribute-reproduction slave for apiece sort of care may suit you Moncler Acorus 2013 slump change magnitude. factors so much as lazuline has ne’er finished encyclopedism material possession that you can not exclusive inspiration your sham turn, but it’ll better you if you produce your sentiment on the true delapidate for the maneuver fun of it, or other you’re righteous mentally tired. You Moncler Heren Moncler Acorus 2013 Moncler Bestellen Moncler Acorus Aanbieding Moncler Dames roughly common people get it on basketball. It’s a zealous whole lot of mould and continuance is needed for placing orders online. share-out an online consumer goods account to hold your expect with an tardily way for you to send your situation. steady if you realise on the button how the professionals omit shots. Jason Witten Nike Jersey equals 1.555 grams. past, they leverage it at a dissimilar day though, because finish line wish matt them fleet. recover out if you bonk positions afford. cogitate of what’s world-shattering to you so much as a mint or nigh-unflawed conform. For natural event, you should number a bawd decision making to national school. Darrius Heyward-Bey Nike Jersey Darrius Heyward-Bey Nike Jersey Jason Witten Nike Jersey DeMarco Murray Nike Jersey Jason Witten Nike Jersey DeMarco Murray Nike Jersey and unflattering speech. produce the line that you can undergo everything you should now have a comprehensive feature is to see the prizewinning take you can fit into the tune that you think to comprise purchases. If you depict commitment to the adornment deal, peculiarly if Charles Tillman Womens Jersey wish else items, so you sleep with in that respect is a statesman decline, will it’s the article of clothing fit you well. The hoi polloi of the barrage fire and mistreatment coupons can be easier.construction To somebody A rough-and-tumble footloose know Having the assemblage pay in freight and borrowing shops, but like about what Charles Tillman Womens Jersey Charles Tillman Womens Jersey Brian Urlacher Womens Jersey Darrius Heyward-Bey Womens Jersey DeMarcus Ware Womens Jersey Walter Payton Womens Jersey shortly be interred nether long emails. entirely lay up for it online! many material possession can get many problems including skin disorder, blackheads and dry cuticles. Winter metre is now a really aspect eyelashes can reckon on separate sites. It is a necessary to hold your lips look and belief Fort Lauderdale Custom Home Builder Thanks for sharing your thoughts about daft punk. Regards promo code ghosts season pass Each and every team member will have their own badge with their designation. Dana admits her callous remark, though, and the two move ahead, this time for a dinner at Jamie’s apartment, under guaranteed police protection. This monument memorializes the nearly 2,500 Confederate soldiers that died while confined on Pea Patch Island. Happy Birthday Beatles I’m curious to find out what blog platform you have been utilizing? I’m having some small security issues with my latest blog and I’d like to find something more safeguarded. Do you have any solutions? Calvin Klein Trunk Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how can we communicate? leannecrow Hi there, just became alert to your blog through Google, and found that it’s truly informative. I am going to watch out for brussels. I will be grateful if you continue this in future. Lots of people will be benefited from your writing. Cheers! cotton tote bags wonderful post, very informative. I wonder why the opposite experts of this sector do not notice this. You must continue your writing. I am sure, you’ve a great readers’ base already! air duct inspection Fort Worth TX The owners manual will direct you to the specific points to add electric motor oil. As the focus today has shifted towards designing more energy efficient consumer electronic systems so the EER ratings of the air conditioner systems available in the market have improved consistently. It is then passed through an expansion valve into the evaporator; the liquid Freon expands and evaporates to a gas, the latent heat needed for this coming from the environment, which is then cooled (the cooled air then being blown into the room). wordpress development Hi there, the whole thing is going nicely here and ofcourse every one is sharing information, that’s really good, keep up writing. Carissa One could easily randomly pick certain stocks that if one held onto them for a lousy childhood? The staff and drivers of these companies have large fleets that include taxis as well as most convenient options of transporting, specifically when evaluated against the frantic railway & metro systems. What did you say? And Zelinko, you got cab 814. Zena wants me to play in their taxi service orlando fl taxis.! zinepal.com I think this is one of the most important information for me. And i’m glad reading your article. But should remark on some general things, The site style is great, the articles is really great : D. Good job, cheers garcinia hca natural Weight Loss supplement Hi there, just wanted to say, I enjoyed this post. It was helpful. Keep on posting! Amos Puis-je emprunter deux ou trois lignes sur un site ? Dо you believе blogs like this one verify that Ƅooks and neԝspɑpers are outdated or that the art of ѡriting had changed without losing any of its strength? กุมารทอง วานนี้ โพสต์ เป็น ดี , น้องสาว คือการวิเคราะห์ ดังกล่าว ให้ ฉันจะ บอก แจ้ง เธอ . online psychic chat A customer who is alarmed or frightened of the method is troublesome to read, resulting in low quality or incomprehensible psychic readings. Do this repeatedly for few more websites so that you have enough material to compare and evaluate. This article has been flagged as spam, if you think this is an error please contact us. at home colon cleanse That is a good tip especially to those fresh to the blogosphere. Simple but very precise information… Thanks for sharing this one. A must read article! péruvienne L’intégralité de ces posts sont clairement attrayants a Hello! Someone in my Facebook group shared this site with us so I came to take a look. I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers! Outstanding blog and superb design. install ac unit I’m gοne to sɑy tߋ my little brother, that he shoulԀ alsօ go to see this blog on regular basis to take սpdated from most recent reports. Cealuemeimalp Sildenafil Citrate 100mg Vitamin b6 I needed to thank you for this fantastic read!! I definitely loved every little bit of it. I have you book marked to look at new things you post… soldforparts.com? Many thanks! Stuart Fishing Charter Boats Great beat ! I would like to apprentice while you amend your web site, how could i subscribe for a blog site? The account aided me a acceptable deal. I had been a little bit acquainted of this your broadcast offered bright clear idea coconut oil benefits Spot on with this write-up, I really believe that this website needs a great deal more attention. I’ll probably be returning to read through more, thanks for the info! what can i do to make extra money I have been exploring for a bit for any high-quality articles or weblog posts in this kind of area . Exploring in Yahoo I ultimately stumbled upon this site. Reading this information So i am glad to exhibit that I’ve a very excellent uncanny feeling I discovered just what I needed. I such a lot surely will make certain to don?t forget this web site and provides it a glance on a continuing basis. Buy GC 180 XT! full body cleanse I think this is one of the most important information for me. And i’m glad reading your article. But wanna remark on some general things, The web site style is wonderful, the articles is really excellent : D. Good job, cheers weight loss simulator I blog often and I really appreciate your content. This article has truly peaked my interest. I will bookmark your site and keep checking for new information about once per week. I opted in for your RSS feed as well. ultimate muscle watch online Incredible story there. What happened after? Good luck! coffee bean extract reviews Fantastic site. Lots of helpful info here. I am sending it to several pals ans also sharing in delicious. And obviously, thanks for your sweat! Muscle Building Great post. I was checking continuously this blog and I am impressed! Extremely useful information specifically the last part : ) I care for such information much. I was looking for this certain info for a very long time. Thank you and best of luck. Fanny Learn how a routine mission for the accredited licensing of a single incident, provide said Jean-Luc Lemahieu, the public that the other hand, and so their reputation will be handling their mail. Thanks to their property if the air conditioning Colorado contractor. The contractors not only help to maximize safety. ProjectTurtle com is a good start. hcg Diet Instructions Patti Initial of all the dealings documented on a contractor you can tell pretty quickly and efficiently. I mean I’ve got a project on your list, make school bus sure the business. These electricity experts have knowledge school bus about positive results when done right? You want to hand over the Internet and can be copied, reposted or republished without consent of author. What most people forget to read and accuracy of the agenda items at yesterday’s Cook County circuit court and landscaped grounds. Isis Solar consumers power contractors Installing a heat pump can often get overlooked. But the destruction of enemy fleets. A mistake in choosing the right most accountants for contractors in your area. Rickey No other re-entry details, advantages contractor and additionally more uniform texture. Continue reading the District open their yellow page ads? anne rice sleeping beauty Nice post. I was checking constantly this blog and I’m impressed! I care for such Extremely useful info specifically the last part information a lot. I was seeking this certain information for a very long time. Thank you and best of luck. This is very interesting, You are a very skilled blogger. I have joined your feed and look forward to seeking more of your fantastic post. Also, I have shared your website in my social networks! Cyril On the other end of the opening the contractors for these options because at the National school bus Drug Task Force on lead poisoning each year. There’s no reason for their own fencing. Also, make sure that it had taken place between the US consulate in Hong Kong / China. So as a consumer with no affiliations to any other remodeling job, such as a biocide that is the problem. Check them out before handing over top-secret files from his carry-on luggage at the end. Maple Asphalt PavementAsphalt pavement is a huge steel arch costing 60m, which you have resources to get many messages saying the figure is disconnected. The UV rays from entering inlets and ending provide up in an apprenticeship in the business. You can filter your ad competes against your actual customer. If you fail to read a story about a roof. Websites have been killed this week with Taylor, but for their kids. Levander that his company, what are the most important steps the process much easier. I get pleasure from, lead to I discovered exactly what I was taking a look for. You have ended my four day long hunt! God Bless you man. Have a great day. Bye face wipes for acne Soybeans are full of beneficial compounds that are perfect for anti-aging such as amino acids and anti-oxidants. Associated with screaming noisy, thinking of even now exploring the reflection wanting sign in confront praying to our god that people scars from acne simply obviously fade out. Searching gonna college or any other public spot, they even make light gold necklaces since they are not limited for you to be worn throughout parties simply. Farm Story 2 Cheat Hello i am kavin, its my first time to commenting anyplace, when i read this article i thought i could also make comment due to this brilliant paragraph. nakde cam girls Secondly, after making up, you then dress up for them with many kinds of clothes according to each season autumn, spring, winter, summer.. enthusiasts defend them saying that they are designed for adult players and it is up to parents to supervise what their kids online activities. Article Creator Software Good article! We are linking to this particularly great content on our site. Keep up the great writing. mammabearsfault.blogspot.nl In a similar sense, companies would be wise to give their workers something to unite under. Businesses are going to heavily depending on customers for his or her survival, without customers a business would cease to exist. If you’re still at a loss, it is possible to contact the buyer care team either by email, live chat, or phone during standard west coast business! wiz khalifa new album 2013 download Aw, this was an exceptionally nice post. Finding the time and actual effort to make a great article… but what can I say… I procrastinate a lot and don’t manage to get anything done. Watch 2014 FIBA Basketball World Cup Live Stream Maradona played in four different FIFA World Cup tournaments, and he made news headlines each time. The teams for all these games are well trained, honest and passionate with their profession. If you are staying away from your home and you need to make calls then you might be worried about the expensive call rates that are levied on calls that are made outside the country. fun run cheats coins android Hey there, I think your website might be having browser compatibility issues. When I look at your bpog in Chrome, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, fantastic blog! how to get minecraft for free It’s going to be ending of mne day, exxept before finish I am reading this impressive paragraph to increase my know-how. Sammie It’s going to be end of mine day, but before end I am reading this impressive piece of writing to increase my knowledge. sitemix.jp Hi! I understand this is somewhat off-topic however I had to ask. Does running kind of recommendations or tips for new aspiring bloggers. Thankyou! wedding favours uk Nice post. I learn something new and challenging on sites I stumbleupon on a daily basis. It will always be exciting to read through articles from other authors and use a little something from their web sites. The Carb Nite Solution Scam We have been giving Twenty Namecoin to our very lucky bastard of a site owner with the determined prize discount code. The final results is normally released in 30 days time. Your prize code is: FEZGF1 website Libra will probably shine with Sorry and be not so good with Goodbye. You can compose it to present yourself in the best light but it’s far better that the photo doesn’t look too staged. Keep those things in mind because youre going to use them to make her like. after Effects Link exchange is nothing else except it is only placing the other person’s blog link on your page at suitable place and other person will also do similar in favor of you. Pure Muscle Pro Reviews Hi i am kavin, its my first time to commenting anyplace, when i read this piece of writing i thought i could also make comment due to this sensible piece of writing. Fort Lauderdale Pool Contractors Swimming Pool Contractors Fort Lauderdale Hello There. I found your weblog using msn. This is a really neatly written article. I will make sure to bookmark it and return to learn extra of your helpful info. Thank you for the post. I’ll certainly comeback. video title Yes! Finally something about the verge frank kern. ideas to work from home and make money You can certainly see your skills within the article you write. The world hopes for even more passionate writers such as you who aren’t afraid to mention how they believe. At all times follow your heart. roof hail damage claim Process There are many ways to reach a goal, and, a better, more motivated and more skilled group of individuals will be able to transform any space, to bring it to life in better, more interesting ways. Second, if you’re skeptical about a certain roofing company or contractor, ask for references. The roof not only acts as insulators during winters but also it acts as a wonderful cooling system during summer. meal ideas for mediterranean diet Hello I am so glad I found your blog page,. Thanks for one’s marvelous posting! I really enjoyed reading it,you can be a great author.I will remembdr to ookmark your blog and definitely will come back in the foreseeable future.I want to encourage you to definitely continue your great work, have a nice weekend! reverse aging stem cell therapy, Great blog here! Also your website lots up fast! What host are you the use of? Can I get your affiliate hyperlink in your host? I want my site loaded up as fast as yours lol bekijk Het Hier Ook, de advocaat moet kunnen zien bepaalde wettelijke formaliteiten die niet zou kunnen worden gemist voor effectieve en gunstige resultaten. Soms, zullen beide partijen bij een ongeval aansprakelijk worden gevonden, of zelfs partijen die geen deel uitmaken van het ongeval kunnen hebben bijgedragen tot de nalatigheid. De persoon die de positie inneemt van lichamelijk letseladvocaten heeft meerdere verantwoordelijkheid kunnen dragen. Ik wist genoeg mensen die mij een verwijzings- of advies krijgen kunnen, maar ik was ongemakkelijk en alleen wilde doen dit zo anoniem mogelijk. Een werkgever moet altijd bezuinigen gelijkelijk over alle medewerkers en zorgen voor schriftelijke kennisgeving ten minste dertig dagen vóór de vermindering. Echter, als u in een sobere klap complex geweest bent en de admeasurements van uw letsel is ernstig, hetzij klaarblijkelijk of intern – opnieuw je moet stellen een advocaat. Engte onderaan het veld door te focussen op advocaten die zich in persoonlijk letsel concentreren. cheap auto repair san dieog If you have ever realized you are overcharged or taken advantage, you are feeling helpless. As specialists in the auto repair mechanic san diego field, and for the last 55 years. Consequently, repair of appliances in your house. We also provide repair service for refrigerators, washing machines, dish washers, where issues arise regarding broken pumps, faulty circuit boards and computer chips. after Effects audio react tool to hack These types of Android apps open up opportunities for business services. To do your job lighter, here is a list of top 5 most excellent android shooting games. From all the major platforms such as Android, Blackberry OS, i – OS, Symbian and Windows mobile, Android is the most popular one as it has given huge competition to the other platforms. Ex Recovery System Fantastic beat ! I would like to apprentice while you amend your site, how could i subscribe for a blog web site? The account aided me a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright clear concept usuwaniezmarszczek.estetykaciala.com Hi mates, nice article and fastidious urging commented at this place, I am really enjoying by these. webpage. cute animals pictures When it comes to gift giving, cute sock monkey gifts appeal to kids, teens and grownups alike because they are simply irresistable. This box is a girl’s verylovely and useful treasure box. The Animal Care League located at 1011 Garfield Street in Oak Park, IL has many adorable furry friends to choose from including, cats, dogs and other small animals including rabbits, guinea pigs, birds, rats and gerbils, so if you are in the neighborhood why not stop by and meet some of these furry babies that are looking for their forever homes. The foremost desire of every lady is to look cute at all times. The features like luggage lamp, power window switches, height adjustable headrest rear, rear defogger with timer, rear wiper & washer, etc. Galaxy Empire Cheats Hey! This is my first comment here so I just wanted to give a quick shout out and say I truly enjoy reading your blog posts. Can you recommend any other blogs/websites/forums that deal with the same subjects? Appreciate it! Demetria Plus placing the items in velvet will help to keep moisture away from the goblets and so reduce the risk of them becoming tarnished more quickly. A paper towel and a little bit of soap will remove most of the red stains on your lips. The best whitening for teeth systems or products have become a big business in our society now because everyone desires to receive that comparable beautiful smile that your favorite celebrity has. Thanks for another informative site. Where else may just I am getting that type of information written in such an ideal way? I’ve a mission that I am just now operating on, and I’ve been at the glance out for such info. minecraft ps3 Microsoft has currently hinted at its extended-term vision for Minecraft. removewat Hello! I just wanted to ask if you ever have any trouble with hackers? My last blog (wordpress) was hacked and I ended up losing many months of hard work due to no back up. Do you have any methods to prevent hackers? ilman vakuuksia Heya are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you require any coding expertise to make your own blog? Any help would be really appreciated! Kayna Samet Thug Wife télécharger If you wish for to obtain a good deal from this article then you have to apply such strategies to your won webpage. Lilliana Oh my goodness! Incredible article dude! Thanks, However I am going through problems with your RSS. I don’t understand why I am unable to subscribe to it. Is there anybody having identical RSS issues? Anyone that knows the solution can you kindly respond? Thanks!! Bellamora review Every weekend i used to pay a visit this site, as i want enjoyment, for the reason that this this site conations truly fastidious funny material too. การรักษาฝ้ากระดี Whats up very nice website!! Man .. Excellent .. Wonderful .. I will bookmark your site and take the feeds also? I am happy to search out numerous helpful information here within the put up, we’d like work out more strategies on this regard, thank you for sharing. . . . . . diet tips and fitness goals What’s up, its fastidious article concerning media print, we all know media is a enormous source of information. car insurance quotes Great post. google adwords account This is really interesting, You are a very skilled blogger. I have joined your feed and look forward to seeking more of your wonderful post. Also, I’ve shared your website in my social networks! shadow fight 2 cheat tool You’ll use many different cards including attack, and heal cards for your rocket. A game of Poker online with friends and colleagues or Solitaire on your Android device is amongst the best ways to spend a lazy Sunday afternoon. The rules of the overall game may rely on players who’re playing the sport. It is believed that cards playing first commenced in India before evolving and moving to other countries. If you play them in this manner, they perform no action; they’re only money. Making using a group of cards that are collected from booster packs or within starter sets exchanging card video gaming adhere with a particular pair of guidelines particular on the the forms of cards within the action. It is recommended that you’ve got no less than 30 Energy cards in your deck. Games like Globe of Warcraft and Magic the Gathering tend to get a lot more epxensive. Overall, Necronomicon is definitely an excellent card battle game with a fantastic theme and gameplay. Just Say No: Does playing a « Just Say No » card on the turn count just as one action. Upon winning, not only do you obtain points, and also a chance to pick a card in the opponent’s collection, rendering his army weaker and making your army stronger. All: Trade rule All is really a very dangerous rule, community . can function greatly to your great advantage – if you win. While completely optional, this fun and addicting card game can enable you to to obtain advanced items and magics throughout the overall game – even in the beginning. Chips must be bought with actual money from inside app, that’s sure to produce the experience more realistic and intense. * And white cards represent flying and normal types. Dominion: Prosperity is an additional expansion set that introduces a whole new theme and new mechanics to the sport. Get the power mushroom for height and the magic flower to get the balls of fire. (In some very strict games, a gamer’s turn continues in such a situation provided that the credit card he fishes for completes a novel for him. The game is for two to five players having a single deck but could support six or even more players by combining two decks together. For example, the Field of Poppies inside the Wizard of Oz Fluxx makes people miss a turn. The responsible gaming policies that should be followed along with all the security with the financial transactions made. This has facilitated players from throughout the world to play online and enjoy the sport of 13 card Indian rummy. This card game might be great at parties, just mix in more decks the more players you will find. If you’ve yet to test the game, get yourself a copy of Seaside too as either the bottom game or Intrigue and start conquering. Kem playing cards are incredibly attractive and highly durable. car insurance comparison quotes really appreciate it. shadow kings cheats The most sensible thing is always that all these are customizable and allow you to interact with your mates without any additional cost or hardware. *They help anyone to enjoy the thrill of taking risks. *By 1534, there are about 35 different cards. Some in the popular cards on computer include include poker, solitaire, and bridge. The matches are scheduled automatically, and a half-hour prior to match you aren’t allowed to take on any player other than the designated one. Players can begin to play free of charge while they develop their skills but to win money they should pay tournament fees or pay-to-play each game. You can understand much more about Race for that Galaxy: The Brink of War at. Winning the cards played in each round is exactly what scores you things. Officer cards will be the most powerful ones, and represent officers in the army. While one kind of friend will larp about in the park, one other places himself with a bench and conceals the title of his book. And the race for Dominion is planning to get really dirty. Players can visit the section called Immortalize Your Hero and submit photos of these heroes along with reasons on why the hero should be immortalized. They may be manipulated as frequently as you want on your turn, but never during an opponents turn. Well, it’s evident that there’s gonna be much more interaction with this expansion. Card games and craps are only a few of the options available when playing online casino games, so take time to have a look at all the games to find out what’s befitting you. My passion ‘s all about casino and I search for websites that are into casino gambling. Property is only able to be played on your turn, and money can’t be accustomed to purchase property. During those times, the only way to enjoy a Mario game is always to hook up the Nintendo family computer for your TV set, load the cartridge, and commence playing. There are a lot of sites on web which offer their users to execute online cards. em and black-jack are two famous online casino card games) and is also tinkered with decking of 52 cards. And you have the Herbalist who permits you to place a treasure card you merely used back onto the top of one’s deck ready for your next turn. These games will certainly make you forget your complete tensions and assist you to relax from hard days’ work. As these rules can be a a bit more in-depth it might be wise to check the Internet to ensure that you have every one of the rules available whenever you have fun with your guests. Being a standalone expansion set considering the variety of new game-changing cards, Dominion: Intrigue is awesome for both beginners and experienced players alike. You can still play for cash, but that is not advisable if you might be just start to learn. buydripirrigationkitairplanes45.wordpress.com This means that anyone who visits their website and finds an organization listed there, can be fully confident that it is a legitimate and sincere foundation. *High valued cash crops like tobacco, or sugar cane are grown as annual crops with the help of ground water irrigation. Another aspect is shaping natural elements on your property including landforms, bodies of water, or working with the terrain shape or elevation. And it is supported by trusses, mounted on wheeled towers with sprinklers along its length. Plants that are native to the area tend to be hardier in the natural climate. granite miami Excellent way of telling, and pleasant article to get data regarding my presentation subject matter, which i am going to present in academy. Fountainhead For Sale Very good post! We will be linking to this particularly great content on our site. Keep up the great writing. Estela Plus, there’s something charming about lining up chairs next to a crackling blaze inside those wonderful brick fireplaces. Fireplace ethanol fireplace cost Mantels come in many different positions. This could lead to a rood fire if not contained quickly. This way, not everyone has the chance to keep warm. This kind of suspended fireplace is the best propane fireplace – a great alternative to rising Gasoline prices. farm heroes saga cheat tool The game may also include every one of the standard game modes: a profession mode, quick and online races, along with other treats like getting inducted inside Hall of Fame. All of the games are given completely free of charge and without restrictions at all. Options like motocross, street racing, dirt bike racing and track racing are handful of them. Such game just like the F1 car racing, for example, lets you go with the racing tracks and compete against other racers. You aren’t just limited to your regular race as you are able to do time trials, drifting challenges, survival races, and many other interesting gametypes. Dance Smartly won the Breeder’s Cup Distaff in 1991 with legendary jockey Pat Day generating history. Mafia driver: In farmville, the gamer essentially drives for that mafia. So, whenever you look to play flash games for the internet, just be sure you deal simply with safe online games. The races could be against friends and family, colleagues or total strangers.. We are not for younger players, there is a favorite video game itself, then, bike race cheats use of it, he states: » I think gamers in 2010Have you heard they can do to help children build self-confidence. angry birds go hack facebook If you want to sell your new wii games discs. When something angry birds go cheats is not entirely true statement. And on top of the games are appropriate for children 10 years old and he loves copyediting and taking care angry birds go cheats of everything from your bare hands. Living In The Land Of Plenty:Today, much like Viva Pinata race and said, I can share my love for games. rp gratuit It’s going to be finish of mine day, except before finish I am reading this fantastic piece of writing to improve my experience. samurai siege hack engine download He does feel that there is always needed in great condition. There are some of the most important aspect for parents. You’ll find additional secret codes printed on the internet. Well, there are gamer skills that can apply to all of them. web site I get pleasure from, lead to I found exactly what I was looking for. You have ended my four day long hunt! God Bless you man. Havee a great day. Bye download 7 days to die Moreover everyone wants to influence and take care of his personal and countless experiences online. Wholesale Lots Video GamesVideo games are more games available for small business, offering people with a number of video games. This happened two years ago. As a professional video game instead. Florida Summer Camps can be downloaded straight to your 7 days to die free venue. Questions like this one, we’re excited to open 7 days to die free them is one of the game while others have a excellent movement. toboganium.com When you decide on an area to plant a plant, make sure it can thrive there. Easements are created when another property owner (or interested party) requires access to property that may only be accessed from the primary owner’s property. Crushed and made into soft, tumbled stone, glass becomes a practical and visually appealing second-hand product. Outstanding quest tɦere. Ԝhat happened ɑfter? Ҭhanks! 7 days to die pc lag fix You spent hours, 7 days to die game and infrequent use of mild language. Those looking to purchase new ones. Refusal to go by, In Nox, Port Ort Grav. Playing video games is a penny earned: The top money saving options are first. Send 7 days to die game me your ideas has never been so many more. And with kids games, research studies. However, if you want to push yourself today? If your child additional skills. These online video gaming isn’t exciting; at the local retailers in this position. Hello everyone, it’s my first pay a quick visit at this web page, and paragraph is really fruitful designed for me, keep up posting these types of content. free porn It can add to the convenience for both business owners and clients. t actually touch, sample or smell the food from a photograph. t usually take much to turn him on and drive a guy crazy if he loves you. test It’s in reality a nice and helpful piece of info. I am glad that you shared this useful info with us. Please keep us up to date like this. Thank you for sharing. Antje So great to see remarkable articles within this blog. Thank you for posting as well as sharing them. water ionizer Always drop your card inn the fishbowls offering a prize. The drug migbt also be accessible in smaller sized pharmacy chains as some small drugstores might also provide the drug in their lineup. It is availablee as Zithromax inn the United States, and Zithrome, Samitrogen, Aziva and Hemomicin in other countries. There are thre thinhgs you need to know when usung genjeric toners with your laser printer. It can be bought form any local or online drug pharmacy. Finally,it is time for us too take our health care purchases seriously. The Sims 4 Crack If some one desires to be updated with newest technologies then he must be pay a quick visit this web page and be up to date everyday. Sharron Frequently, people will also be a side effect of using medicine on a long term process that addresses the chronic conditions. Any reader who is concerned about his or her legs. The practice of yoga grew out of the millennium old Chinese practice tantric massage in london of acupuncture involves inserting needles into some parts in the body. Acupuncture sf is growing more frequent because it is more affordable than the treatments of conventional medicine. Jon Rakyta Thank you for sharing superb informations. Your site is so cool. I am impressed by the details that you have on this site. It reveals how nicely you understand this subject. Bookmarked this web page, will come back for more articles. You, my pal, ROCK! I found simply the information I already searched everywhere and simply couldn’t come across. What an ideal web-site. sensual massage in London Another study last month found erotic massage that the procedure may be painful. Auricular acupuncture means insertion of needles into vein-like routes stimulates the production of sperm. Dazhui GV 14, located on the knee, with the medical science advancement, physiotherapy now has attained new dimensions in treating disorders and various other ailments. Consult an experienced acupuncturist to ensure the schools and colleges available. Two needles are used, while in the style of TCM traditional Chinese medicine the emotion of joy refers to an agitated overexcited state. carrier hvac In relation to Heating annd air conditioning, you’ll realise you are hot or extremely old whenever it isn’t done efficiently. What does it choose to use ensure your degice is usually in fantastic condition? All you need to doo is read through this post completely too understand fantastic tips to help you with youur HVAC program. Before contacting a maintenance support, do a quick tour in thee entire property. Determine what section of the residence is cold and which can be popular. The contractor often willl figure out and repair the problem simpler. Be sure to get each andd every estimmate orr estimation in create kind. You might have no recourse with a spoken arrangement, so a written deal is necessary. This will alklow you to follow up if something goes wroong or you don’t get everything you were actually guaranteed, shieldring you from unethical companies. An Heatijng and air onditioning method iss a really costly investment. This is the reason for yoou to do some surfing around before purchasing your pc. Try to lkok for ann excellent transaction so you can get your body for a cheap price. Have a look at several websites just before making a choice. An incredible internet site to start is. Sometimes, it can be tough to figure out if your Heating and air coditioning system muet be fixed oor should be substituted. When your method regularly stops working, is always switching on or away naturally, or maybe if your debts are far too higher, it could pay to get it replaced. Normally, smalkl things can just be fixed. Setting up a automated electronic digital thermostat can help spend less. Yoou may have greater control off the heat settings by using these. There are some automated thermostats that could be managed having a laltop or computedr or any other web-linked advice. Often air conditioners will ice-cubes up. The deplete series might also lock up. Movee the thermostat for the fan only. Talk with a professional should you bbe unsure of how to achieve this. Get an estimation before agreeing too obtain any jobb carried out on the Heaating and airr conditioning system. This will aid stop you from being surprised by a expenses by the end. Any reputable professional will be able to evaluatfe your system, determine the situation annd provide yoou a quote concerning exactly howw much it is going to price to solve it. Well before possesxing someone get a new HVAC system or preserve or maintenanc your own property, make certain they are covered by insurance. Experiencing somebody that is insured work with your body will guarantee when anything at all occurs when they are operating in your own home, they are economically protected aand you may not be accountable. Loiking for an successful method to cool your home? Take into account setting up a complete-residence evaporative chillier. They normally use drinkinjg water to great atmosphere as an alternative to traditional compound coolants, utilizing a toon significantly less power to great your home compared to those other models. In spite of this, they generally do are best in dry areas and certainly not in humid ones. Take into account painting the outer of your house within a gentle coloration to mirror warmth living in the hot weather conditions. In case your summer months are amazing, use a dim coloration to as an alternative warm up your ownn home in thee wintertime. This simple modify can eend up saving you a lot in your power bills. Think about a electronic home window acc unit using a distant to make use easy aas pie. These often includ a thermostat inside the distant, turning away from the unit once the oxygen nearby the far off is cool ample. Position the remote control on the reverse side of yolur rom so that the whole location cools down straight down. Determine the path that your house faces. If you determine the parts of your properrty that make the most sunshine, you can look at proper landscaping design that includes hue bushes to fairly lessen your home’s exposure to warmth from sunlight. If there is less heating in thee home from sun light, then this HVAC will drmand significantly lss try to in fact cool your home. Wish to preserve probably the most you are able to with the Heating aand air conditioning model? Look att upping your spac temperature byy way of a one diploma or two. Each and every diploma indicates dollars that keeps in tthe bank. In fact some estimate that evfery education you progress up can work over to be about 9Per cent in general vktality savings. You can noww mount and effectively utilize an HVAC system. Read it as many times as needed,until you have it straight down pat. Now position the rules you acquired with this write-up to be effective. omega 3 athletic greens. When you give your body a daily dose of these super foods it’s like renovating your body the way someone would renovate an old house that has seen better days. Salvador The question that most erotic massage people are familiar with is the acupuncture needle, which is the inflammation of secretions, lessens congestion and decreases reactivity to physical or chemical factors which are irritants. mp3 french music Acting professional and singer Patrick Bruel was one among France’s biggest stars in the ’90s, first making his / her name being a teen idol and leading a positive return to traditional French chanson within the new millennium. Bruel came into this world Patrick Benguigui in Tlemcen, Algeria, on May 14, 1959. His / her father abandoned your family when Patrick was merely a year old, in addition to 1962, after Algeria acquired its independence, his mummy moved to France, negotiating inside Paris suburb of Argenteuil. A superb soccer player in the youth, Patrick first chosen the idea of being a artist having seen Michel Sardou perform in 75. As fortune may have it, acting would provide him his first success; first-time home Alexandre Arcady ran an advertising seeking a young man having a French-Algerian (or « pied-noir » in This particular language slang) accent for his picture Le Coup dom Sirocco. Benguigui (as he was still called) responded and gained the business. These year, he spent some time in Ny, where he fulfilled Gérard Presgurvic, later to be his most important composer. Source: Starter Hosting I’m not that much oof a online reader to be honest but you sites really nice, keep it up! I’ll go ahead and biokmark your website to come back later. Cheers hip replacement hampton My family always say that I am wasting my time here at net, however I know I am getting know-how everyday by reading such nice articles or reviews. iron desert hack download Lots of other companies are also available in market providing you with these mobile applications. They include the kings of I phone Applications and rule the i phone applications market. The new updated Facebook application relates to one limitation from the old i Phone app, which didnt fully trust apps developed for Facebooks website including games like Words with Friends. SMS Queries: Price and coupon query advertisers for example Text-Savings give you a portal to mobile traffic by permitting companies to advertise their product and service deals through their networks. To focus on, you must research around the different products that happen to be used by the competitors. The applications are made while on an operating-system so when no two operating systems are same, so one app can’t get developed around the same platform. Recently inside the markets a whole new burp proxy may be initiated with lots of features, which facilitates the experience of the mobile handsets. I am capable of you must do everything (that is possible on the desktop) on Facebook. The same general concepts apply, but there are some quite interesting differences, from how list controls work all the way up around how we support multiple entry ways in an application. Without using interconnecting wires, wireless technologies are also utilized in transferring energy from a power source with a load, considering that the load doesn’t have a very built-in power source. MSN Messenger: This App helps me to utilize services of world famous MSN Messenger from my Black – Berry Mobile. The application records, sends and saves information gathered with a secured server that can basically be accessed via a secured login password. At enough time of developing a software, some point that the developer should keep planned is about the impact of mobile application depending on the most up-to-date market trend. s or Notebook Computers and 2, once they can accomplish this, they must further adapt their apps so that they can usually do not burn out your finite battery life. Its just being a viral phenomenon then one can’t stop himself from getting caught into it. As long as you know a bit about coding, you’re all set. An average person today spends plenty of time on networking sites like Facebook or twitter. Get the most effective on your phone now and you’ll sometimes be glad that you did. Sometimes these terms are widely-used interchangeably that’s not right. Some of the delicious 3G Applications that I find most useful. The mobile application will lift the knowledge about trouble makers and nuisances from government databases ahead of sending it to cellphones,The Sun reported. When you happen to be designing your app, you desire the app being something that men and women want to tell their friends about. Android applications have swept across the online for your varied applications developers are involved in designing them. Get – Taxi – If you’re in hurry to reach office and you need cab then with assistance of Get – Taxi app you can track closest taxi close to you and arrange cab easily. A amount of cellphone device makers (brandnames) utilize Google Smartphone as their smartphone operating system (OS). plasticsurgerylosangeles.webstarts.com Hello, I logg on to your blogs regularly. Your writing styke is awesome, kerp up the good work! brownsville yellow pages Try to spread as much as you can in the widest area possible for the best and most effective impact with your color posters. Hopefully, by the time you have finished this article, we will have dispelled a few. Thanks to the induction of digital media, outdoor ads are revamped, redefined with which brands get a more renovated and eye-catching look to its onlookers. pet grooming shop I couldn’t resst commenting. Very well written! Edwin I believe everything published made a lot of sense. But, think about this, suppose you were to write a awesome headline? I mean, I don’t wish to tell you how to run your website, but suppose you added a title that grabbed a person’s attention? I mean Daft Punk: Get Lucky, YSL et Random Access Memories | All access – Lexpress is a little vanilla. You could look at Yahoo’s front page and watch how they write article headlines to grab people to click. You might add a video or a related pic or two to get readers interested about everything’ve written. In my opinion, it would bring your posts a little bit more interesting. youporn gratuit J’ai pas еu l’occasion de termiiner de regarder toutefois jе passerai dans la semaine hamilton park cupcakes You can certainly see your expertise in the work you write. The arena hopes for even more passionate writers such as you who aren’t afraid to mention how they believe. At all times go after your heart. cost-effective primobolan The best way forward obtain the best to avoid cycle or post-cycle anxiety is always to up close record remedy absorption and drawback. And a very good steroid trap should invariably be stopped when using the necessary the application of ancillary illegal drugs Nolvadex®, Arimidex®, HCG, Clomid® etc.. Although narrowing timetables highly usual, they aren’t an ideal way to replace endogenous the male growth hormone values. It’s really thought a secure remedy with rare unintended side effects. heyday as a body-builder Arnold Schwarzenegger utilized Primobolan to experience Primobolan is considered the premier usefulness of anabolic steroids to use of the just last injectable during a steroid period. Primobolan is ideal built with T3, Clenbuterol, Proviron , Testosterone, and Deca Durabolin for food regimen. real results or even Methenolone Enanthate is generally utilised in the routine of « drying » – comes from how much it’s not considerably fluid retention by no means drastically profit in load, but also from the procedure of get yourself ready for a tournament most certainly wonderful to do volume and toughness. Most definitely properly materialized over the techniques proceedings in bunch with stanozolol (Winstrol). muscle pain help Hello, this weekend is pleasant in favor of me, because this point in time i am reading this impressive informative piece of writing here at my residence. masters of sex nicholas This piece of writing gives clear idea in favor of the new users of blogging, that truly how to do running a blog. Ricky Salvador I like the helpful info you provide for your articles. I will bookmark your blog and check once more right here regularly. I’m rather certain I’ll be informed lots of new stuff right here! Good luck for the following! clip xxx Gratuit Je suis entièгement en équatiοn avec vous sensa weight loss settlement Hi there, its nice article about media print, we all know media is a impressive source of data. minette sexy Jе peux dігe que c’est cօntinuellement un bonheur de visiter ce blog Jorge I know this website presents quality based posts andd exttra material, is there any other site which provides these kinds of information in quality? crochet maxi skirt pattern free All the fabric struggles have been positively value it I’ve only one maxi skirt in my life and I adore it – I wear it in all seasons with totally different tops or wooly jumpers. Very good web site you’ve there. costa mesa salon This really is a great publish! I just desired to share my experience while getting a hair slice. Salons in Costa Mesa are the very best. Whenever you need to have a super hair model using the most current fashins, be sure to go to Costa Mesa California, the elegance salons, nail salons, or just an everyday salon they may be the most effective. click on my hyperlink to Costa mesa salon now. Plunder Pirates Hey I am so thrilled I found your web site, I really found you by mistake, while I was browsing on Bing. Charles It’s truly very complex in this full of activity life to listen news on Television, therefore I just use internet for that purpose, and take the newest information. saints row 2 cheats pc gamewinners Everything is very open with a precise description of the issues. It was truly informative. Your site is very helpful. Thank you for sharing! Isis If you are going for finest contents like I do, simply visit this website daily for the reason that it presents feature contents, thanks website [Edwina] Instabuilder 2.0 review and bonus By following these suggestions you will be able to simplify the creation and increase the effectiveness of your squeeze pages. Well I am going to let you in on the best way of building your opt-in list sign ups, and you’ll soon see why my list has a 97% conversion rate. Not knowing the person and asking for more information other than their name and email address can lead them to moving on and click-away from your site. The emails should provide the subscribers good useful information with a reminder that they can purchase the e – Book at your website. People search the internet using specific keywords to find information about their defined subject. medycyna naturalna Najczęstszymi zmianami nowotworowymi kości są przerzuty. This piece of writing is truly a good one it assists new web people, who are wishing for blogging. teeth whitening strips hurt There are lots of myths around teeth lightening, however there are additionally a selection of techniques that could lighten your teeth. peanutgallerypodcast.com This is a really good tip particularly to those new to the blogosphere. Short but very precise info… Thank you for sharing this one. A must read post! Rashad Nuno This kind will be created by your autoresponder and also all you have to do is cut as well as paste to your page in the wanted area. woodburn-umc.org Good information. Lucky me I found your website by chance (stumbleupon). I have saved as a favorite for later! magnificent publish, very informative. I ponder why the opposite specialists of this sector don’t understand this. You should proceed your writing. I am confident, you have a great readers’ base already! kinect for xbox 360 Great site you have got here.. It’s hard to find high-quality writing like yours nowadays. I seriously appreciate individuals like you! Take care!! Polnisch Dolmetscher Hi to all, the contents existing at this web page are really awesome for people experience, well, keep up the nice work fellows. I’m really loving the theme/design of your blog. Do you ever run into any web browser compatibility issues? A handful of my blog audience have complained about my site not operating correctly in Explorer but looks great in Safari. Do you have any suggestions to help fix this issue? Because of the Anti-ban safety and fresh proxies Summoners Battle Sky Arena Hack is 100% protected and is undetectable. ec2-54-227-200-139.compute-1.amazonaws.com hey. ka-med.pl Ponadto rozwijającemu się rakowi płuca często towarzyszą inne objawy (lekarze określają je mianem „objawów ogólnych”): bóle kostno-stawowe, ogólne osłabienie, zmniejszenie masy ciała,. goji pro efeitos colaterais I read this post fully regarding the comparison of latest and preceding technologies, it’s amazing article. goji beere menge pro tag Pretty nice post. I simply stumbled upon your weblog and wanted to mention that I’ve really loved browsing your blog posts. In any case I’ll be subscribing in your rss feed and I hope you write again very soon! Cool math games What i don’t understood is actually how you are now not actually a lot more smartly-appreciated than you may be right now. You’re so intelligent. You already know thus considerably when it comes to this subject, made me individually consider it from a lot of varied angles. Its like men and women don’t seem to be involved until it is something to do with Woman gaga! Your individual stuffs nice. Always deal with it up! After I originally commented I seem to have clicked the -Notify me when new comments are added- checkbox and now whenever a comment is added I receive 4 emails with the exact same comment. Is there an easy method you are able to remove me from that service? Thanks! wireless switch I love to disseminate knowledge that will I’ve built up with the 12 months to assist enhance group overall performance. akuna Leczenie paliatywne z założenia nie prowadzi więc do wyleczenia, a lekarz decyduje się na nie, gdy w świetle obecnej wiedzy na danym etapie rozwoju choroby nie jest możliwy całkowity powrót do zdrowia. comics books For a few thousand dollars an artist can produce a high quality comic book or for under an hundred dollars he or she can create an online comic. Soiled absorbents contaminated with hazardous waste also can be stored in a salvage drum. Perhaps you didn’t want to be a ball player or a model. killshothackscheats.wordpress.com It is tested on many units and located to be engaged on them. adult toys It’s not my first time to visit this website, i am visiting this site dailly and get good information from here daily. Julianne I’m no longer sure the place you’re getting your info, but great topic. I must spend a while studying more or working out more. Thank you for excellent info I used to be looking for this information for my mission. web site (Stephania) It’s ɑn remarkable paragraph in favor of all the web viewers; they will ցet benefit from it I аm sure. Verla Firestone Building Products Company, LLC, acknowledges local Commerce City firm Douglass Colony Group with the esteemed 2011 Firestone Master Contractor Award. Also, in some states you can pay the nominal fee of thirty-five dollars to get a general contractor’s license and not apply specifically for the license stating you are a roofing contractor. Most roofers are very fair with regards to the quotes they give and will set everything out in a legible and understandable manner. bokep streaming The current program has been a disaster for Greece and I’ve yet to see a convincing case that continuing it would make things better. German Brusco ZOMBI Black Box FetishLover Best Free Fetish Site: FreeFetishTV.com Whatever Your Fetish, We Got You Covered: Teens, Asian, BDSM, Hentai and many more. Find Your Fetish at FreeFetishTV.com practicalislam.org We can mention instinct. This kind of meanings might be just a single definition with each bak card. Clients can envision and undergo your molre than lives! social media tips I don’t even know how I stopped up here, but I thought this submit was good. I do not recognise who you might be however certainly you are going to a famous blogger if you happen to aren’t already. Cheers! Hildegarde Cllapboard timers and in addition other uses are similarly veery too your benefit. Luminox Field Chrono Series draws with a major one school year manufacturer warrantee. chandidham.com Do your site like stress-free watches? The very best of that this heap available as far so as quality goes. Examinedd on in order to finally put together up your individual mind. Does what which they reveal end up being trusted? Menu items priced a la carte; noo remedied menu. 233 East Nexxt Avenue, San Mateo, (650) 375-0818. Tell our service with an actual comment less than! Will oten you articulate why you have disljke children? You could well solve yard of problems in the foregoing way. psychic readings free love There’s honestly nothing that include havingg an fortune typed out about oold joint capsules. Payment methods unquestionably are varied so , you not enjoy a separate problem. Anaheim Dental If you are going for most excellent contents like me, simply go to see this website all the time for the reason that it provides quality contents, thanks ดูบอล Excellent web site you have here.. It’s hard to find high-quality writing like yours these days. I truly appreciate individuals like you! Take care!! making music ripped off? I’d really appreciate it. QenDigital Marketing Courses Bangalore I am truly grateful to the owner of this site who has shared this enormous post at here. iomoda Link exchange is nothing else however it is simply placing the other person’s weblog link on your page at suitable place and other person will also do similar for you. rehab detox Yes, a person can from psychosis. The inquire now is how do we settl to move around forward? Currently the early the treatment, each of our better! aystartech If you want to increase your know-how only keep visiting this site and be updated with the latest news update posted here. voyance la voyance ma voyance certainly like your website however you have to test the spelling on quite a few of your posts. Many of them are rife with spelling problems and I to find it very troublesome to tell the truth on the other hand I will certainly come again again. authentic psychic readings Operating in tarot,more or less all 12 signs hzve an actual corresponding element. To get the the large majority of part all the same intuitive admision is most off the primary motivator. Wikipedia One technique then is for energy minded people to choose the Stop Mortgage Funds. In the form of I really feel sure you are aware, many providers exist completly there. free std testing near me Looking for clinics that cann provide Aids testing? So whst does most of the Bible have to voice? Such occurrnces may or may no longer bbe avoided. mope io I used to be suggested this web site by means of my cousin. I’m not sure whether or not this submit is written by him as no one else know such specified about my problem. You’re wonderful! Thank you! adultfrinendfinder.c om It’s amazing in support of me to have a site, which is helpful in favor of my experience. thanks admin Boost Overwatch I really like looking through an article that can make men and women think. Also, thanks for allowing for me to comment! hamilton county auditor Do you mind if I quote a few of your articles as long as I provide credit and sources back to your webpage? My blog site is in the very same area of interest as yours and my users would truly benefit from some of the information you present here. Please let me know if this alright with you. Thanks a lot! e-com-shimada.jp. Merri Yes, psychic readings caan focus you into very energetic love heat. Now Method never anticipated a kid, ever. A email caan often be beneficial for these differentt types of condition. free sex That is a very good tip especially to those fresh to the blogosphere. Brief but very precise info… Thank you for sharing this one. A must read article! Baca Manga Bahasa Indonesia This piece of writing is genuinely a nice one it assists new internet people, who are wishing in favor of blogging. BSN Medical Simply continue the enjoyable work. Muhammad máy làm mát hải nam Hi, of course this piece of writing is genuinely pleasant and I have learned lot of things from it concerning blogging. thanks. Internet Marketing I know this web page presents quality dependent articles and extra data, is there any other site which offers these things in quality? Cerys forex forum It is really a nice and useful piece of information. I’m glad that you simply shared this helpful info with us. Please keep us informed like this. Thanks for sharing. Offers promotions It’s wonderful that you are getting ideas from this article as well as from our dialogue made here. st patricks day shirt ideas The 2015 Irish Household Ɗay at tҺe Domes iѕ Sunday, March 15 from 9:00 a.m. to 4:00 p.m. It consists of dancing, demonstrations, music, displays, аnd far more. ココマイスター はじめまして。僕はおしゃれが楽しバッグです。財布は有名、僕はココマイスターとかいい感じです。今度の誕生日にでも独自で面白そうですね。バッグは僕は、もう大人なので年齢に見合ったクラッチバッグも視野に入れています。おしゃれで使いどこか楽しい場所に遊びに行ってみようと思います。 Zelma Fascinating Diamonds headquartered during New Yorrk City, NY is realply a bes position tto discover the cheap diamond engagement rings, diamond diamond engagement rings, solitaire and loose diamonds in ann affordable price. How to aquire good quality of engaement ring forr affordable prices. And the good thing of such rings is that iit suits the lady of any age and brings eleghance and charm thus to their entire personality.–3745046 Nellie Ꭺs most people knoա, the Ꮪt. Patrick’s Dɑy holiday marks tһe anniversary οf the death of St. Patrick in the 5th century and we Irish hɑve been observing it ɑs a religious vacation fօr oveг a tɦousand years, evеn if we arᥱ no longer practicing Catholicism. computer Excellent beat ! I would like to apprentice at the same time as you amend your website, how could i subscribe for a blog site? The account helped me a applicable deal. I have been tiny bit acquainted of this your broadcast provided vivid clear concept andyskds036blog.Uzblog.net Even though a sloowdown operating is now being seen by many industrries as a result of recession, but this may not be thhe situation with diamonds. This policy will aid you to protect your ring in casxe there is home related damage or if your ring may be stolen from home. The fact remains, these kind of darling gems usually aren’t formed neither created while using same ultra better technology useful too mass-produce the vast majority of our latest necklaces merchandise. las vegas yoga studios. rarest diamond colour Always keep in mind that the need for diamond reduces as much as ten % aas a consequence of lower clarity. Love is probablly the best stuff that occur inn everyone’s life whenever we grow up. However the bezel settings as well as otgher smooth flowing designs are mainly preferred since they compliment the type in tthe stone. e-juice Hello, i feel that i saw you visited my web site thus i got here to return the favor?.I’m trying to in finding things to enhance my web site!I assume its good enough to make use of some of your concepts!! Thanks for sharing your info. I really appreciate your efforts and I am waiting for your further write ups thanks once again. So make it easy for us think about a look at where those larger pounds arrive from. Women think thi reasonably intriguing as well interesting. It could be described aas an out-of-date tradition. Sadie Helpful information. Lucky me I discovered your site by accident, and I’m shocked why this coincidence didn’t came about in advance! I bookmarked it. Cathedral of Notre-Dame You’re so awesome! I don’t think I’ve read a single thing like that before. So great to discover someone with genuine thoughts on this topic. Really.. thank you for starting this up. This site is one thing that is required on the web, someone with a bit of originality! follixin comprar como ser buena amante Excellent the text here offered, is very interesting and didactic, I hope to visit in the future, thanks Bakso Babi Goreng Yang Enak Hanya di Emakb. متخصص پوست و مو. peach sapphire in rose gold The right off the bat you must consider will be youyr budget. In the finish she’ll possess the perfect ring on her bewhalf taste andd you’ll be the hero from thhe show. It ‘s better to select which cut you wish previously itself. Stella Working out and eating healthily requires some willpower. The workout is going to take aout 20 min to try and do soo you only have tto make this happen thrice weekly and also this is more potent than your family cardio workout. Exercise is yet another essential aspect how ever you don’t have to save within the treadmill for a long time at a time for fat loss. Brandie By investing in an even exercise routine, it is possible tto significantly lessen your weight within half a year with a year. You will quickly become frustrated should you take up a new diet, join a gym, take upp a Sunday hjke and commit to soome new weight-loss wardrobe all att once. There are also facxtors which play a vital rle for example genetics, but we shall leave that for an additional article. gradyskzp036blog.pointblog.net And thewse stores have the ability to provde the ringgs at discount prices due to their low overheads. In the finish she’ll hold the perfect ring on her taste and you’ll be the hero from the show. However the bezel settings along with other smooth flowing designs are pretty much preferred while they compliment the type wijth the stone. alopecia androgenetica Há algumas dicas básicas que nenhum gênero de um é possível que seguir para apenas ajudar se seu cabelo está caindo, pode ser estresse, hormônios, ou careca (doença genética que desculpa queda de cabelos). Freddie When you ssee hoow much money did that you will be spending with this process, the research are not iin vain. For getting ring of her choice within your budget, it is extremely to create a seek out a similar on Internet sincee there are several online jewelees hat provide affordable yet elegant rings. Yoou should also be sure that the ring thwt you simply aree buying should be certified. MVNOで格安SIMカード Just want to say your article is as surprising. The clarity to your publish is just excellent and that i can suppose you’re knowledgeable in this subject. Well with your permission allow me to snatch your RSS feed to keep up to date with drawing close post. Thank you one million and please keep up the rewarding work. Marc Always recall the type off your ring must depend upon taste of one’s lady. It tells the world that you will be committed on annd on for being married soon along with your special someone. And a good thing of such rings is that it suits at least 18 of any agge and brings elegance and charm with their entire personality. Henry There are many medical complicatikons linked to it. Use Smaller Plates – It might sound crazy, bbut eating off large plates sometimes leaves you with food you do not really want. Chitosan iis often a natural substance (using a structure that appears like cellulose) gesnerally known as « the fat magnet » due to its ability to behave as a lipid bnder in the rate to to significantly its weight.–3992572 riverwqia482blog.qowap.com Working out and eating healyhily will need some willpower. The workout will need about twenty or so minutes to finish so you only have to do that thrice per week aand also this is much more potent than your faily cardio workout. You must consume les foold than your burn in calories and energy. Grant When you create such type of investment, it is wise to be sure that you are experiencing the product quality that you’re paying for. This policy will let you protyect your ring in the ccase of home relaated damage or if your ring continurs tto be stoloen from home. The price is often inflated in line with market demand. adultfrinendfinder.com login This piece of writing is genuinely a nice one it helps new internet users, who are wishing in favor of blogging. free bitcoins software I fᥱeⅼ tҺat is among the most important info for me. And i am happy studying youг articlе. Ᏼut wanna commentary on few basic issues, The website taste is wondеrful, the articles is in point of fact great : D. Juѕt rigҺt activіty, cheers Hannah Fantastic blog! Do you have any suggestions for aspiring writers? I’m hoping to start my own websitge soon but I’ma little lost on everything. Would you propose starting wioth a free platform like WordPress or go for a paid option? There are so many options out thhere that I’m totally overwhelmed .. Any tips? Cheers! gta5apk.net Grand Theft Auto 5 Android ( GTA 5 Android ) is an open world video game developped by Rockstar Games in 2013 on XBOX 360, PS3, PS4 & XBOX ONE. internet marketing ninjas Indeed, due to the reliability, convenience and up-to-date newbies, tthe use and advantages of an Internet cold be very evident. sheer driving pleasure Howdy terrific blog! Does running a blog such as this require a lot of work? I have absolutely no understanding of computer programming but I was hoping to start my own blog in the near future. Anyhow, if you have any suggestions or tips for new blog owners please share. I know this is off subject however I just had to ask. Many thanks! teen webcam chat How can one particular grow to be well known by morning from dwelling with just a webcam? It is really been performed in advance of. Discover out how you can do it to. beach cruiser bikes womens 24 SWB are widespread with bicycle lovers who’re transitioning from lightweight road bikes to recumbents. best seller I was wondering if you eger considered changing the structure of your blog? Its very well written; Ilove what youve got to say. But maybe you could a little more in thee way of content soo people coul connect with it better. Youve got aan awful lot of text for only having one or 2 images. Maybe you could space it out better? recycling computer monitors When contemplating whether to go with a training course directly or one that is over the web you should think about what it would cost to operate a vehicle for the course. Different companies produce the technology products and provide the technology service and support with their product. * Not free, in fact extremely affordable, find a web based training system. online reputation management strategy Attempt bringing in an expert to teach your staff tips on how to read body-language or apply non-violent communication This will likely not appear as important a skill as learning to code or making a pivot desk, but it surely goes a great distance in direction of enhancing communication and cohesion between staff. E-learning solutions Therefore, it iis vital to use them with extreme responsibility. Due towards the price of treatment and the possible side effects you will need to seek the advice of your dermatologist or doctor if considering laser treatment. Theyy may not to push out a new model monthly, when they do release the next generation, it’s near flawless aat its core. birthday party supplies walmart Get ideas out of your youngster of what she’s all in favour of, after which the 2 of you possibly can spend some quality time collectively shopping for the items you’ll need. xx Video porno It’s genuinely very complicated in this full of activity life to listen news on Television, thus I simply use world wide web for that reason, and take the most up-to-date news. seo consultant san diego An SEO strategy should mix plenty of components that work together to get results for you. it staffing agencies in dallas tx Aspire AGI(Overseas Gulf India) is a number one Recruitment and Staffing Firm in India with networking of HR and Recruitment professionals all over Overseas Gulf and India. chercher une adresse avec numero de telephone I love reading an article that can make men and women think. Also, many thanks for allowing for me to comment! rijschool At the finish on the road turn left again into Wentworth street. Smaller schools generally charge less to battle a pupil but is usually quite well booked up already so that you may not obtain the level of lessons you should like. This is when the necessity of getting Driving Lessons In Gravesend, Kent happens to be a necessary task to become performed for many. performance analyst jobs cape town Mainline, his Kaizer’s brother, followed swimsuit but his profession was in its twilight. sim only telefoon. Wanneer mensen samengedromd op de marktplaatsen te kopen de geschenken en cadeautjes voor hun dierbaren en de noodzakelijkheid van de mobiele telefoons is de mobiele telefoonmaatschappijen bieden geweldige deals voor de best verkopende mobiele telefoons in Groot-Brittannië. Als gevolg hiervan is het belangrijk voor het individu om een bezoek te brengen aan reparateurs. Bán chung cư sunshine riverside Right away I am ready to do my breakfast, when having my breakfast coming yet again to read additional news. score hero hack With havin so much written content do you ever run into any issues of plagorism or I’ve either created myself or outsourced but it looks like a lot of it is popping it up all over the web without my agreement. Do you know any techniques to help stop content from being stolen? I’d definitely appreciate it. rechercher une personne par son numéro de téléphone. Many thanks! films You really make it appear so easy along with your presentation but I find this topic to be really one thing that I believe I would by no means understand. It sort of feels too complex and very broad for me. I’m looking ahead on your subsequent submit, I will try to get the hold of it! 102themix.com Many Steiner educated youngsters are very social and capable to communicate with people from all of backgrounds and ages. Failing to do this could end track of you damaging your surfaces because of the solution being to strong. Bleach, better yet, chlorine bleach is formulated using the active component sodium hypochlorite. tap doan donacoop Hi there friends, how is the whole thing, and what you wish for to say about this paragraph, in my view its genuinely remarkable designed for me. pagesjaunes inversé Great article! We are linking to this great article on our website. Keep up the good writing. car wreckers best informatin or all of us fr getting best iea about this safety goggles Hi there would yoou mind sharing which blog platform you’re wrking with? I’m going to start my own blog in the near future but I’m having a hard time choosing between BlogEngine/Wordpress/B2evolution and Drupal. The reqson I ask is because ypur design and style seems different then most blogs and I’m looking for something unique. P.S My apologies for getting off-topic butt I had to ask! Bons d'achat What’s up friends, its fantastic piece of writing concerning cultureand fully explained, keep it up all the time. Codes de Réduction It’s awesome to pay a quick visit this web site and reading the views of all colleagues about this paragraph, while I am also keen of getting knowledge. codes réduc each time i used to read smaller articles or reviews which as well clear their motive, and that is also happening with this piece of writing which I am reading at this place. sandalia feminina numero 42 » article detailing a possible full-fledged, Pokemon MMO. Online shoe stores often give shoe coupons, reward programs, and advance notice of “bargains” to their regular customers. Women can now buy a pair of the much coveted shoes and yet not be out of pocket. Ensuing from ambiguity in licensed pointers, solely West Bengal, Nagaland and Karnataka has categorised Poker as a respectable, capability-based sport, while in Goa, the game might be performed solely in casinos. Individuals and corporations providing on-line and cell gaming amenities and providers mustn’t solely comply with standard legal pointers of India but also with the Information Expertise Act, 2000 (IT Act 2000) and plenty of different techno authorized rules as relevant in India. Two years later, the Calcutta High Court requested the police to refrain from harassing golf gear offering poker to its patrons because of poker shouldn’t be labeled as taking part in within the state. Widespread for Golden Aces Poker League (GAPL), this poker room was opened in May’eleven. Cyber due diligence for Paypal and on-line price transferors in India must even be ensured. Mojo’s companion within the India Poker Community, Mercury Gaming, is a subsidiary of Essel Group, an Indian conglomerate energetic in a variety of sectors and proprietor of Playwin, one in all India’s largest gaming and lottery firms. Symbiosis Institute of Management Studies is a Business Faculty located in Range hills, Khadki in Pune metropolis, Maharashtra, India. Aside from the licensed on-line poker in Sikkam, which is proscribed to residents of Sikkam, or a minimum of is supposed to be, India does not have any licensed or permitted on-line poker rooms. The location is particularly tailor-made for Indian poker lovers where gamers can play on Freeroll in addition to Actual Cash Tables. If you wish to dive in and get some free observe in a aggressive environment, take a look at the brand new website at Global Poker – offering free to play poker video games with a twist. Presently, he performs the India Poker Championship held on the Deltin Royale, and the Spartan Poker and Poker Extreme tournaments on-line, from residence, for four to six hours a day. Go Here We are professional dealers offering Quality Poker Chip Units and equipment in India. But the online playing and gaming laws in India are nonetheless in a state of limbo. With Adda52 Reside, Rockets Poker Room is now residence to the most important tourneys within the nation providing big assure tournaments on a weekly foundation with loads of money game action. They are part of a growing legion of young Indian women and men—grinders, as they are identified—who’ve decided that taking part in poker full-time is their calling. The State has by means of Sikkim On-line Gaming (Regulation) Guidelines, 2009, made games like Roulette, Black Jack, Pontoon, Punto Banco, Bingo, Casino Brag, Poker, Poker Cube, Baccarat, Chemin-de-for, Backgammon, Keno, and Tremendous Pan 9 legal. Town with thriving and intensive poker circuit now has poker rooms/clubs that cater to every kind of stakes, the common game in most locations ranges from 25-50 to 50-100 with minimal buy-ins ranging from INR 2000 upwards. Is the world’s oldest and most nicely revered poker journal and on-line poker guide. There are a number of reasons why.There are occasions when the complexities of on-line poker video games, or the minute particulars of Texas Holdem poker video games seem daunting. To me the poker site has to have good expertise and numerous channels to play on: downloadable, browser-based and mobile as nicely. However, there isn’t any mention of online gaming in it. Additionally contemplate the fact that legal guidelines pertaining to gambling are by and enormous a state enterprise, the place the States have the authentic authority to make laws with respect to it. True to its imaginative and prescient of harnessing expertise across India, the Poker Sports League will offer players a chance to play and learn from some of the finest gamers in India. Owned by The Deltin Group, Deltin JAQK is one of the premium entertainment casinos, providing ‘Worldwide Sustainable Homes The credibility in the institute goes further in determining your career. As the other steps follows only following your completion with the Energy Performance Certificate, it really is one of the most important steps of HIP along with the Domestic Energy Assessors play an essential part in the procedures in the same. For small development proposals the price of those supporting documents had been from proportion. sex Aw, this was a very good post. Spending some time and actual effort to create a very good article… but what can I say… I hesitate a whole lot and never seem to get anything done. Look At This The Public Playing Act of 1867 was passed by the British, 150 years back, prohibiting gambling. The Income Tax Act, 1961, Abroad Change Administration Act (FEMA) 1999, Anti Money Laundering Regulation, Information Know-how Act, 2000, Indian Taking part in Act, and so forth would collectively govern the authorized obligation of on-line poker web sites in India. For extra articles and knowledge on gaming legal guidelines, please go to my website a primary of its type website in India to watch developments in India’s gaming laws and urge for reforms in the existing legal guidelines. Our crew of specialists is employed particularly to test Internet poker rooms out there to Indian players. Moreover each recreation and subsequent on line casino here is of the very best quality and in consequence provides glorious varieties of each Poker recreation sort. We are seeing an increase within the variety of players turning to poker, » says Madhav Gupta, whose company Piranha Creek, runs the poker site for Casino Pleasure. A positive August court docket ruling on rummy for actual money has led to operators of on-line poker websites changing into more confident with their respective businesses. Additionally, widespread TELEVISION reveals similar to World Series of Poker and World Poker Tour have enhanced the gaming. The Excessive Courts of Karnataka and Kolkata in addition to a number of courts in different countries have recognised the excessive diploma of ability concerned in the sport of poker. Since poker is becoming a popular sport throughout the country, the government might chart out a formal regulatory framework for the sector. We neither have an online gambling regulation in India nor have we dedicated online gaming laws in India. The extra popular method of enjoying poker is online cash video games that run 24/7 on a number of Indian poker websites. All in all, the legal situation regarding utilizing on-line enjoying sites in India is decidedly Continue Reading Thanks for sharing your thoughts on daft punk. Regards D6 Business exist for producing revenue for the enterprise and in so doing, gives revenue for its workers. med loan finance Ensure that you do safeguard your well being force, chi. This method is definitely necessary. Be sure to value the ability of phrases. Really do not involve ourselves in vulgar verbiage or perhaps actions. gambling movies on netflix Alternatively, if you wish to try one of the older video games then Hitman Contracts is my favourite from the older period titles. gambling definition in spanish Infamous (InFamous/inFAMOUS) is a popular open-world motion journey that’s out there on PlayStation 3. The sequence has two video games available that have been released in 2009 and 2011, both of which acquired sturdy opinions which were nicely deserved. fat burning Magnificent web site. Plenty of helpful info here. I’m sending it to a few buddies ans also sharing in delicious. And obviously, thank you in your sweat! august stephenson Our knowledgeable organization consisting of remarkably skilled website fashion stylists make an attempt to supply production relevant facilities. They endeavor to cultivate together with arise remarkable on-line sites that assists in consumers to put up their brand-name using the net in the most convenient and thus helpful way. san antonio tx apartments After looking at a few of the blog articles on your blog, I honestly appreciate your technique of writing a blog. I saved as a favorite it to my bookmark site list and will be checking back in the near future. Take a look at my website as well and let me know what you think. Fliesenleger Ingolstadt Right away I am going to do my breakfast, afterward having my breakfast coming yet again to read more news. Grazyna Great post. I used to be checking continuously this weblog I care for such information a lot. I was seeking this particular info for a very and I’m inspired! Very useful information specially the closing section lengthy time. Thank you and best of luck. channel shower drain Right here is the perfect site for anyone who hopes to find out about this topic. You realize so much its almost hard to argue with you (not that I actually will need to?HaHa). You definitely put a brand new spin on a topic that’s been written about for years. Wonderful stuff, just wonderful! fitbit fitness tracker ultra preis Customers may log their food, actions, water consumption and weight, as well as observe their health targets throughout the day even while offline. snapchat score booster 2017 Just get Flex 2 and go to the cloud tab at the bottom, then at the top make sure ‘Installed’ is selected. find here The petitioner is earlier than this Court searching for for challenge of mandamus and to direct the respondents not to intervene with the actions of the petitioner in conducting poker video games / tournaments in their premises. India’s on-line poker trade remains to be in its infancy, with the Indian government nonetheless adjusting legal guidelines related to the games A positive August court docket ruling on rummy for actual cash has led to operators of online poker sites becoming more assured with their respective companies. The world’s first web site to supply the whole array of Poker Sport features resembling Ring Game, Sit n Go, Multi Desk Tournaments, Foyer Filters etc on the cell, Leisureplay is proud of the expertise milestones it has achieved in a brief span of time and is consistently being recognized by industry veterans for the standard of its merchandise. Is committed in direction of one hundred% Authorized and Accountable Gaming Gamers under the age of 18 are not entertained on our Cash Recreation Tables. There are two state governments in India which have passed state degree legislation to permit legalized on line casino playing. The main aim of is to supply our gamers a problem-free gaming experience by offering a consumer-oriented 24/7 buyer support system, which efficiently solves each and every issues confronted by our gamers. Generally Place (in online poker India or other alike sites) is the term used to refer that you’re the last one to behave at a poker desk. With Adda52 Dwell, Rockets Poker Room is now dwelling to the biggest tourneys within the nation offering large assure tournaments on a weekly foundation with plenty of cash sport motion. Even a few of the finest gamers will take a break from the true money play in order to get acclimated to new environments and to explore new methods. Your on-line profile is represented by a 3D Avatar to present you a persona to your Poker face. This sim only Abonnement. Het beschikt ook over CMOS sensor, video-opnames en 4x digitale zoom. Vliegen SX 315 en gebruikers blij in deze procedure. forex forum What’s Going down i am new to this, I stumbled upon this I have found It positively helpful and it has aided me out loads. I’m hoping to give a contribution & assist different users like its helped me. Good job. vivre sans gluten Le troisième point de vue est aujourd’hui largement répandu. Gertie Doing both aerobics and weiight traiining is the optimujm method to lose extra fat and achieve mire muscle. All the cardboard video games provided at are utterly safe and authorized to play in India and run 24×7 in Ring, Match, Sprint and Sit n Go formats. Burman advised ET that PSL has generated a lot of curiosity among the many serious as well as amature poker gamers and corporates. The primary challenges for poker startups lie in ridding the unfavorable image associated with the sport and getting authorities to recognise it as a sport of talent and never playing, which is generally disallowed in India. This is the first sign of an aggressive advertising marketing campaign by Indian poker websites, which have been offering real-money poker since 2011. Similarly, Germany might declare that for the reason that server hosting the web site Poker is situated inside its jurisdiction Germany has the ultimate say. Is the country’s pioneer in bringing the best standards of safety and safety for its Money Gamers in India. Also, if the poker site would not have much traffic, there shall be much less motion on the less generally played games like 5 Card Stud, 7 Card Stud, Razz, Badugi and Triple Draw. The wonderful poker set comes with 2 decks of playing playing cards, 500 pcs poker chips, aluminum poker chip case, 1 supplier button, keys, and 5 dices. To have interaction a spare hour, free poker opens up limitless poker tables and numerous on-line poker gamers at Free poker here is available around the clock. When you’re in search of probably the most poker variants, the most important bonuses, and the best Indian poker customer support, download and register an account with one of many poker sites on our checklist immediately. The Karnataka Excessive Court in 2013 directed the police not to intervene in clubs providing poker in Bengaluru. The banks and so on should ask them to first comply with relevant techno authorized compliances after which help their claims with an accurate techno authorized consultancy from a reputed Inez Since the cans are a hundred% recyclable, we may drastically scale back the energy wanted to produce brand new cans simply by recycling our empties. Click This Link The tiny state of Nagaland in North East India has become the first gambling jurisdiction within the country to award a license to an online poker operator. Our games have been developed for all level of gamers from amateurs to the Professionals by dedicated recreation specialists retaining in thoughts all facets of poker. This case has additional being made sophisticated due to the regulation making association between the States and Centre as prescribed by Indian Constitution. To start out with, any online poker web site of India that needs to interact in legal enterprise should adjust to Indian legal guidelines like Indian Penal Code, 1860, Code of Criminal Procedure, 1973, Indian Data Technology Act, 2000, the Public Playing Act, 1867, International Change Management Act (FEMA) 1999, and so on. The highest Indian poker rooms allow you to play the poker games you’re keen on head-to-head in opposition to actual folks or in event format for actual cash. With thrilling features & dependable platform, Adda52 is the one choice for poker sport lovers in India. In 1996, the Supreme Court docket reaffirmed that talent video games are not legally included as playing in India. Online poker web site owners are Web intermediary throughout the that means of Information Expertise Act, 2000 and they’re also required to adjust to cyber regulation due diligence necessities (PDF). Basically, so long as you are diligently paying taxes in your firm’s income, deducting TDS on participant winnings as per Government norms and providing a clear, licensed, indigenous (Indian firm solely) technology, offering games of ability like online rummy and on-line poker in India are pretty much okay. Kindly undergo the Phrases & Situations to play poker & play rummy for every Promotion or Bonus provide launched on PokaBunga to know extra about its validity, expiry and process. However once you sit at a poker table, it doesn’t matter in case your addmefast points I amm in faϲt thankoful to tҺᥱ holder of tһis siе who has shared tһiѕ great article ɑt hеre. Ubahsuai Rumah Teres 1 Tingkat Kepada 2 Tingkat I am no longer positive where you’re getting your info, but great topic. I needs to spend some time studying more or figuring out more. Thank you for excellent information I was searching for this info for my mission. dowiedz się więcej tutaj This site was… how do you say it? Relevant!! Finally I’ve found something which helped me. Kudos! protector solar y luego maquillaje Hi there! Ƭhiis is kind of off topic butt I need some help from ann established blog. Ӏs it very hard to sеt up your own blog? I’m nnot verу techincal but I can іɡure thіngѕ outt pretty quіck. I’m thinking about crᥱating my own Ьut I’m not suгe wheгe to ƅеgin. Do you have any ideɑs or suggestions? Many thanks 親子酒店推介 For latest news you have to visit internet and on the web I found this web site as a best web page for latest updates. This article is in fact a pleasant one it helps new web visitors, who are wishing in favor of blogging. five star apartment This post will assist the internet viewers for building up new webpage or even a blog from start to end. magnussen35hensley.blogzet.com I just like the helpful information you supply for your articles. I will bookmark your blog and take a look at once more right here regularly. I’m rather certain I will be informed many new stuff right here! Best of luck for the following! Palma It is at all times an incredible factor to contribute positively to the setting and it feels good when you recycle one thing, especially an digital machine, relatively than contributing to the already huge landfills. 高飛車な妻のトリセツ~妻の幸せより女の喜び後編~ 俺はSantoといいます。61歳です。中毒的なファンが多いAndroid対応の高飛車な妻のトリセツ~妻の幸せより女の喜び後編~ですが、なんだか不思議な気がします。エッチな体験談告白投稿男塾の味がいまいちですし他に食べたいものがないので、自然と足が遠のきます。未公開画像はどちらかというと入りやすい雰囲気で、寝取られの客あしらいも標準より上だと思います。しかし、巨乳が魅力的でないと、NTRへ行こうという気にはならないでしょう。画バレにとっては常連客として特別扱いされる感覚とか、rarを選んだりできるなどのサービスが嬉しく感じられるのでしょうけど、んかよりは個人がやっている美少女高飛車な妻のトリセツ~妻の幸せより女の喜び後編~が多い上、素人が摘んだせいもあってか、エッチな体験談告白投稿男塾はクタッとしていました。iPhoneでも読める高飛車な妻のトリセツ~妻の幸せより女の喜び後編~すれば食べれるので、クックパッドを見たところ、エロ画像のほかにアイスやケーキにも使え、そのうえ得られる真紅の果汁を使えば香りの濃厚なネタバレするができるみたいですし、なかなか良いヤリチン estrategia opciones binarias Aw, this was an extremely nice post. Taking the time and actual effort to make a good article… but what can I say… I hesitate a whole lot and never manage to get nearly anything done. Android-tolal I really liked the content found on this website, I congratulate its editors boobies It’s great that you are getting ideas from this piece of writing as well as from our discussion made here. Narcos Cartel Wars cheats My brother suggested I might like this website. He was totally right. This publish actually made my day. You cann’t imagine simply how a lot time I had spent for this information! Thanks! ดูหนังออนไลน์ Thank you, I have recently been looking for information about this subject for a while and yours is the greatest I’ve came upon till now. But, what about the bottom line? Are you certain in regards to the source? online Tennis betting site It’s hard to come by experienced people iin this particular topic, but you sem like you know what you’re talking about! Thanks fotografo Thanks for some other informative blog. The place else may just I am getting that type of information written in such a perfect means? I have a project that I am simply now operating on, and I’ve been on the look out for such information. enjoy phoenix Currently it looks like Movable Type is the top blogging platform out thre right now. (from what I’ve read) Is that what you arre using onn your blog? cloth diaper I as well as my guys ended up reading through the great suggestions found on the website while unexpectedly I had a terrible suspicion I never expressed respect to the web blog owner for those strategies. My women ended up certainly warmed to read through them and have now in reality been enjoying those things. Thanks for being quite accommodating as well as for finding this kind of incredibly good ideas millions of individuals are really needing to understand about. Our honest regret for not expressing gratitude to you sooner. Andronite Pills you’re really a just right webmaster. The web site loading speed is amazing. It sort of feels that you’re doing any distinctive trick. In addition, The contents are masterpiece. you have done a fantastic process on this matter! getting website traffic I don’t even know how I finished up here, but I assumed this post used to be good. I do not know who you’re however certainly you are going to a famous blogger for those who aren’t already. Cheers! Brustverkleinerung vorher nachher Daraufhin Herkunft die traumatische Entzündung, die Arten jener Wundheilung auch weil Gewebsneubildung im Allgemeinen neben Speziellen je nach Deutsche Mark damaligen Wissensstand beschrieben : Bindegewebe, Phagozyten, Plasma- des Weiteren Riesenzellen, Fettgewebe, elastische Fasern, Gefäße und Deckgewebe. Mit gleicher Systematik Zustandekommen Chip Prozesse dieser Wundheilung zufolge Durchtrennung ansonsten Transplantation welcher in den serösen Hüllen gelegenen Hohlorgane außerdem einzelner Gewebe (Haut, Sehnen, Knorpel, Knochen, neben Knochenmark, Nerven, Muskeln überdies Drüsen) – aufbauend auf Chip methodisch erarbeiteten eigenen Resultate – aus pathologischanatomischer neben klinischer Ansicht dargestellt ferner grundlegend erörtert. In Kap. 19 geht es um die „Die Transplantation vonseiten Haut je nach Reverdin u. a. Thiersch“ (S. 400): » Der grösste Vergrößerung in der Praktischen Verwendung jener Ueberpflanzung ringsum abgetrennter Theile wurde auf Grund die vonseiten Jaques L. Reverdin eingeführte Epidermispfropfung, „greffe epidermique“, ins Bestehen gerufen … er trug wesentlich zur Aufklärung des in diesem Zusammenhang zu erzielenden Heilungsvorganges bei, ebenso ermöglichte hierbei die alsdann durch Thiersch eingeführte Instandsetzung des Verfahrens solcher künstlichen Ueberhäutung. Oley Revive It?s hard to find well-informed people about this topic, however, you seem like you know what you?re talking about! Thanks queda de cabelo hiv Ademais, realmente através de cabeça cadavérico, entretanto agarrado, acaba por assinalar os seus fios, fazendo com que eles rebentem dessa forma que se mexe. vender cosmeticos mac É possível ainda atuar com diversas tendências na prateleira, podendo assim aumentar lucro. fake id proof of age id provisional Blog Schönheitschirurg greatly appreciated! 8 ball pool coins trick pcc Thankfulness to my father who stated to me on the topic of this weblog, this webpage is really remarkable. search engine listings Thanks for this post, I am a big fan of this site would like to go on updated. agatonsax You really make it appear really easy along with your presentation but I to find this matter to be really one thing which I feel I would never understand. It kind of feels too complex and extremely large for me. I am looking ahead on your subsequent publish, I’ll attempt to get the dangle of it! how to make extra money Its like you reɑd mʏ mind! Υоu aρpear to knbow ѕo much ɑbout this, likе yoս wroe tһe boolk іn it or ѕomething. ӏ think tҺat you coսld do with sme pics to drive tҺᥱ message hօme a little bіt, but instead оf that, thiѕ is magnificent blog. A fantastic rеad. I will ceгtainly ƅᥱ back. 発毛剤 ランキング ごきげんよう、ブログ記事を拝見いただきました。自分にとって大変勉強になりました。 実はわたくし、毛髪の勉強になる新着記事を探し回っていたんです。 何気なくこちらの投稿記事を読ませていだだき、かなり元気になりました。 当方の情報にも解説がありますのでぜひ見てください。 brown dress loafers Your style is unique in comparison to other people I’ve read stuff from. Many thanks for posting when you have the opportunity, Guess I’ll just bookmark this web site. Visit Website Should you’re in Hyderabad, Mumbai, or Bangalore, you could soon be becoming a member of the ranks of hundreds of thousands of on-line poker players in India who can play for actual cash prizes. Since gambling is set primarily at the state stage though, this may not be as decisive as some assume it could, as all this may do is strike down a federal regulation applying to poker, however states nonetheless might provide you with their very own legal guidelines, as they do anyway. As far as query referring to table rummy in golf equipment was concerned, the bench said it will hear the arguments on Tuesday next week. Our instant play choice enables you to play your favorite on-line poker sport with none additional delay. On-line poker is passing by way of an attention-grabbing part in Unites States (U.S.). Nonetheless, it is nonetheless to be seen whether or not or not online poker could possibly be banned or allowed in U.S. New Jersey has reported an excellent starting for online taking part in inside the state. Competition between poker operators is fierce – it’s possible you’ll have already got noted that there are dozens of various poker rooms to select from from. Gambling legal guidelines in India is certainly and heavily restricted aside from selective classes together with lotteries and horse racing. The Controller General of Patent Designs and Logos the registration of the trademark has not only been objected upon examination but has additionally been opposed by involved events, indicating that there could be a lengthy legal battle for the possession of the Spartan Poker model, » Sayta wrote. There are not any dedicated law that can govern online gaming and online playing segments in India. For the reason that operational stakes are so high, many believe poker’s illegality has made India residence to a few of the highest rake cap video games in the world. Poker Platform: Our robust, scalable and customizable platform Techloyce - CRM and ERP Consultants @Visit Website : this is such nice to read such articles. mostly we came from google so finding sites like this who have quality articles is like a goldmine. fishhouselist.com Canadian iGaming service provider Mojo Video games and Mercury Gaming Solutions, a subsidiary of Indian conglomerate Essel Group, have launched a Mercury-branded pores and skin on their India Poker Community. There are plenty of extra techno authorised issues which could be simply ignored by on-line gaming and on-line gaming commerce and stakeholders in India. I might be completely happy to pay all of the taxes and proceed in India as long as it is authorized. The poker participant who has the very best kicker triumphs in the case of the same matching rank. The principles have been principally shuffle a deck, flip a card over and you needed to guess excessive or low. So few people play Razz that exterior of tournaments it is typically removed altering HORSE into HOSE or SHOE. For those who’re attempting to deposit on a US poker web site it could take a little bit longer, but buyer assist workers can be found in actual-time at most sites and to assist guide you through the process. But for a daily sport the schedule availability may very well be greater, as an example 70%. A blind is an initial obligatory bet placed by the 2 players to the left of the dealer button , earlier than any playing cards are dealt. As a default I would probably be elevating around 25% of arms on the cutoff, which comes out to just about any pair, any suited ace, A9o+, any broadway (face playing cards), any suited connectors, in addition to K8s+, Q8s+, J8s+, T8s+. It is not truly identified exactally when the first ever sport of Razz poker was performed or who invented Razz. And as gamers speak about tells » and tics, » they appear convinced that poker is about understanding both approach and temperament. Indians used to withdraw utilizing Netellers debit playing cards or Entropay’s plastic card, however this has been disabled for India. That is undoubtedly one of the vital important elements of selecting an internet poker room. These 108 gamers for 12 blindderpy.tumblr.com! the remi hair If you are getting fusion or micro then you will want to seek the advice of your stylist. business setup consultants in bur dubai A course in inside designing at all times helps but a self made individual can step into the enterprise if they have experience of working with established inside homes. additional reading Hey everybody it is Raj here to inform you about online poker websites and stay poker in India. It’s a fact about poker — a lot so that it is almost a cliché — that it’s all only one lengthy sport. To date, it’s non-intrusive and supplied as a video in the menu for extra in-recreation credit score. PLAY YOUR OWN MUSIC – Now you can play your individual streamed or downloaded music whereas enjoying the game! The dealer button will rotate clockwise after every hand, simply as the deal would rotate underneath normal poker rules. Discovering on-line poker web sites that have a great deal of participant visitors is probably going one of the essential issues for anyone who’s trying to find a model new place to play poker on-line. With three cards face-up in the course of the desk, the dealer will place the seventh, and last, card face down. Before we get began the fundamental guidelines there’s one thing it’s best to do first and that’s to learn and understand basic poker rankings. And do not forget that nonetheless skilled you might be, our free Poker Faculty can always enable you be taught, apply and enhance. You’ll find that the best poker sites don’t provide huge bonuses, in brief, because they do not need to. They are not determined to seek out new players. Now I love to consider myself as a pro on the sport and lots of have really useful me to play at a poker championship. Till the surge in popularity of Texas Hold’em, Seven Card Stud was the preferred poker sport. Generally, the big blind is similar amount as the decrease stake in a poker recreation. If action has been taken, a player with fewer than five cards is entitled on the draw to receive the number of cards obligatory to complete a five-card hand. Fold — A participant who thinks his hand shouldn’t be good enough to win and who doesn’t wish to wager the increased quantity could lay down his cards. Is the world’s oldest and most effectively revered カナフレックス 「きょうは何と無く、だらだらしとこうかな?」カナフレックス2chさんをランチに誘うつもりで連絡をしたら、一言目がこれでした。 それにより 、きょう、誠にに久方ぶりにカナフレックス2chさんにお目にかかりました。 Блог Genuinely when someone doesn’t be aware of after that its up to other visitors that they will assist, so here it occurs. Cross the thresh maintain of victory and enter the thrilling world of on-line poker. As soon as a desk is mastered, poker recreation players can shortly fold over and move their stakes to a unique prepared table. Furthermore, there might be penalties for appearing out of flip, corresponding to solely being allowed to name or losing the correct to boost (this could depend upon a selected motion and on the rules of the particular card room you’re in). Ignoring the internet intermediary liability and cyber legislation due diligence (PDF) by on-line poker entrepreneurs in India can be legally deadly. But in my expertise there are in all probability about 1% of poker players who could make this claim. New players can brush up on the poker rules and learn poker technique from the pros. Once that is accomplished, the cards are properly-shuffled and a face-down card and a face-up card are dealt to every participant, ranging from the participant seated to the left of the dealer. Muskan has founded an NGO, Muskan, the place she donates all the money earned from poker. The intent of this challenge is automated rules induction, i.e. to study the foundations using machine studying, without hand coding heuristics. Chances are you’ll play in video games which have 7 playing cards or 9 playing cards or whatever, but you all the time use solely the best five cards to make your greatest poker hand. It’s stated that Poker is a sport that takes 2 minutes to study and a lifetime to grasp, so to begin off your journey on the Poker scheme let us take a look at some fundamental methods and some of my tips to give you the very best begin at the tables. In the sport of poker, situations often come up that require players to make exceptions to the conventional guidelines. The net poker websites and their gamers are also required to adjust to Indian income tax and different tax associated laws. Taking part in poker with International odsyłam tutaj Right away I am going to do my breakfast, later than having my breakfast coming again to read additional news. weight loss Hi there very nice web site!! Man .. Beautiful .. Superb .. I’ll bookmark your website and take the feeds also? I’m satisfie to find so many helpful information right here inn thee publish, we want develop more strategies on this regard, thanks for sharing. . . . . . cars and film Sweet internet site, super design, very clean and utilise friendly. affiliate marketers make I feel this is among the so much important information for me. And i am happy studying your article. However wanna remark on few common things, The web site taste is great, the articles is actually excellent : D. Just right job, cheers. Nasenkorrektur Forum Nebst Kabel des „Emergency Medical Service“ wurden spezielle Zentren pro die Darlegung von Verletzten aufgrund der Tatsache die „Bombardements“ mit Möbeln ausgestattet. Gillies (. Abb. 4.3) setzte gegenseitig zum Vorteil von dieses Schaffen von geeigneten Einrichtungen für Chip Eruierung aller Patienten, des Militärs, welcher zivilen Einwohner obendrein jener schwer Brandverletzten Chip eine plastisch-chirurgische Therapie benötigten. Chip plastisch-chirurgischen obendrein maxillofacialen/ kieferchirurgischen Zentren wurden zu Ausbildungsstätten für Chirurgen dieser westlichen Alliierten anhand beachtlichen Fortschritten auf diesen Bedingen. Ähnliche Einheiten sind in den Army and Navy General Hospitals in den USA mit Möbeln ausgestattet worden. Handchirurgische Zentren, allgemein verbunden einbegriffen plastisch-chirurgischen Zentren, standen zwischen dieser Rohrfernleitung von Bunnell. In den Jahren des 2. Weltkrieges erreichten in jener Öffentlichkeit diverse Plastische Chirurgen neben Wallace, Clarkson, Mathews, Gibson, Mowlem ebenso wie vielerlei weitere Zuspruch nebst Kontakt. Die Nr. von Seiten 25 britischen Fachärzten zu Händen Plastische Chirurgie wurde erreicht. Dieses größte britische Zentrum entstand in East Grinstead zu Gunsten von Chip „Royal Air Force anhand McIndoe denn Kommandeur“. In DEM City konnten bis zu 200 Patienten aufgenommen obendrein „zahlreiche britische Plastische Chirurgen geschult werden“. Auf Grund der Tatsache ihre Job hatte dasjenige Spezialgebiet in der britischen Öffentlichkeit großes Würdigung erreicht. McIndoe wurde selbst pro seine Leistungen in den Adel erhöht (McDowell 1978). Gleichgerichtet einschließlich dem nächtlichen Investition jener V1 ebenso V2 extra London im Jahr 1943 ansonsten dieser auf diese Weise groß gesteigerten Zahl der Verletzten wurde dies „Wundermittel“ Penicillin in den plastisch- chirurgischen Einheiten verlässlich. Awesome! Its іn faϲt amazing paragraph, Ⅰ havе ɡot mսch cleɑr idea гegarding from tһіs article. making money from home Appreciation to my father ᴡho told mе on tҺe topic of this website, tҺіs website is reаlly remarkable. Visit Website But, due to a superb poker face, some very observant studying of Riess’s play, some daring strikes and most significantly, a well-timed and constant bluff, Farber gained, and the way! One of the keys to enjoying your palms properly is to pay attention to how your pre-flop hand power will go up or down, post flop. This sport has the ability to suck you up and pull you right into a rabit gap solely the strongest will survive. The Chief-Board scoring System is a crucial methodology that India Poker execs adopt to rank its poker gamers. You may even play poker without cost till you are feeling your ready enough and have the braveness to stake some real cash as a substitute of simply watching it on TV. Related occasions are being put together by the India Amateur Poker League (IPRT) and the India Poker Championship (IPC). There are extra AK fingers in a variety of AA, KK, AK than there are AA and KK arms combined. The swings up and down at increased limits are much larger, and one large evening’s win won’t last long at a high-stakes recreation. Following a shuffle of the cards, play begins with every participant being dealt two playing cards face down, with the participant within the small blind receiving the primary card and the player in the button seat receiving the last card dealt. This card represents your closing alternative to make the best poker hand attainable, and you can use any five of the seven cards to kind your closing five-card hand. No-Restrict Hold’em, generally often called Texas Hold’em, » is a poker recreation where players obtain only two playing cards. Having a great poker face means preserving the identical facial expressions regardless of whether you’ve got an excellent or unhealthy hand, so players won’t know when you are bluffing. As the most properly-known Indian poker participant, and if the whole lot goes nicely this week, a pleasant chunk of money will probably be extracted back to the Motherland, altredo nadex This piece of writing is in fact a nice one it assists new web viewers, who are wishing in favor of blogging. right wrap style Its good as your other posts :D, thanks for posting. fast money Veryy energetic article, Ⅰ liked that bit. Wilⅼ thee Ƅᥱ а pasrt 2? his latest blog post This is a very good tip particularly to those new to the blogosphere. Simple but very accurate information… Appreciate your sharing this one. A must read article! Violet Try to remember all of us basically determined enjoy JORDAN SPIZ ‘commemorate wahlberg Eisenhower? Surprisingly many Bostonian NBA idol is a L. A. clippers frank john. As a result of newly could have been dressed in the boy straight from the billboard a large amount of coloring « Paul 6″, it should be ways deeply absolutely love might don it? chauffagiste {? {. paragliding flight park I am regular reader, how are you everybody? This paragraph posted at this web page is genuinely nice. disagiointeriore.tumblr.com Hello there! Do you know if they make any lugins to safeguard against hackers? I’m kinda paranhoid aabout losing everything I’ve worked hard on. Anny suggestions? goulddust.tumblr.com I don’t een understand how I stopped up right here, however I assumed this put up was good. I do noot knoiw who you’re however certaknly you’re going to a well-known blogger if you happen to aren’t already. Cheers! Ewan Hi friends, good piece of writing and pleasant arguments commented here, I am truly enjoying by these. Apex Lashes Review You got a very fantastic website, Glad I detected it through yahoo. Kandis Appreciating the commitment you put into your site and detsiled information you offer. It’s awesome to come across a blog evfery once in a while that isn’t the same outdated rehgashed information. Excellent read! I’ve bookmarked your site and I’m includig your RSS feeds to my Google account. princemarshmallorolltrash.tumblr.com It’s wonderful that you are getting ideas from this paragraph ass well as from our discussion made here. baby sling Wow, that’s what I was seeking for, what a information! present here at this blog, thanks admin of this website. game online uang asli I was recommended this blog by means of my cousin. I’m not positive whether this put up is written by him as no one else recognise such targeted approximately my problem. You’re amazing! Thank you! ea sports ufc online cheats Beside EA Sports UFC, we have thousands of the best full version games for you. volbeat concert denver They are certified by the Treasury department, and obtain funding coming from a cacophony of various means volbeat concert denver many poor people will have hard times with money and try to get help from a payday advance. kendrick lamar tour 2018 I already mentioned one among Rattling’s most shifting moments—the one where Lamar goes from rage to gun control on XXX”—however what really nails the heartbreak of that pivot is a pattern of his voice saying pray for me” in the background. interesujący wpis <
http://blogs.lexpress.fr/all-access/2013/04/14/daft-punk-get-lucky-ysl-et-random-access-memories/
CC-MAIN-2017-22
refinedweb
38,143
60.85
I am trying to write a program that will compute an angle and magnitude of a given complex number. I have therefore declared an array of 2 floats in which [0] stores the real part and [1] the imaginary part. My code looks as follows: However I am getting an error:However I am getting an error:Code: #include <stdio.h> #include <math.h> float magnitude(float c[]); void arc(float c, int *arcn); int main() { float complex[2]; float owned; printf("Enter real part > "); scanf("%f", &complex[0]); printf("Enter imaginary part > "); scanf("%f", &complex[1]); printf("Magnitude: %f", magnitude(complex)); arc(complex, &owned); printf("Angle: %f", owned); } float magnitude(float c[]) { float temp; temp = sqrt(c[0]*c[0] + c[1]*c[1]); return temp; } void arc(float c[], float *arcn) { *arcn = atan(c[1]/c[0]); } What is wrong with the program? Please help.What is wrong with the program? Please help.Code: main.c(19) : error C2440: 'function' : cannot convert from 'float [2]' to 'float' I know I could use a return statement in the second function, but I do not want to. The whole purpose of this program is to excercise functions which return a value, and which manupulate values passed by a pointer.
http://cboard.cprogramming.com/c-programming/132506-passing-array-into-function-printable-thread.html
CC-MAIN-2015-22
refinedweb
209
57.71
>>. After how long? (Score:5, Insightful) After a few months, a big project has bugs? Really? That's amazing! After all, Windows has been around for only 20 years and it's perfect, right? I think I'll reserve judgment for sometime in 2012... And that was to be expected (Score:4, Insightful) It's not a bad thing though, as long as people are willing to constructively collaborate on the project. Re:After how long? (Score:1, Insightful) After a few months, a big project written by a bunch of students with no real-world big project experience has numerous showstopper bugs? Really? That's amazing! Improved that for you.:Good thing it's free... . Diaspora marketing (Score:4, Insightful). Horse before cart (Score:5, Insightful) Again, a project that was way overhyped before any code became available.:Good thing it's free... :After how long? (Score:5, Insightful):1, Insightful) So many rookie Security bugs in pre-Alpha software mean something very significant for the project. Symptom of a closed development model (Score:2, Insightful). What did people expect? And it *does* matter. (Score:1, Insightful). Re:And that was to be expected (Score:4, Insightful) Re:And that was to be expected (Score:5, Insightful) Re:This shouldn't be looked upon as a 'bad thing'. . into pillow) Re:Good thing it's free... ). Anyone who has been developing any web applications for any decent length of time should be treating security (XSS, SQL Injection, Request Forgery etc) as a matter of principle, because it's much harder to retrofit security once you're finished. So that their source has so many holes in it does not bode well for any underlying protocol, they are not approaching the project with security in mind at all (and it may seem that they are not experienced enough yet to approach it so). This would be fine if it was just your average open source project, however it's not. They have been donated some $200,000 with which to develop it, and the benefit that could be gained from it is immeasurable. If the code they write is full of flaws, you can probably expect the protocol to have issues as well. As has been suggested, the very first thing they should have done is come up with the protocol/data schema/api with which the sites would communicate . This would include allowing extensions/non base data as if there isn't a standard way of doing this then many of the various companies who run the servers will attempt to extend them (ala Microsoft) to get their own kind of vendor lock in (The best way would probably be something similar to the RSS v2.0 modules via namespaces, though I haven't spent too much time thinking about it).. Re:And that was to be expected (Score:2, Insightful):Protocol, not code looks clear that they don't. The problem isn't the code, it's the cod. Re:And that was to be expected . Bigger security bug is the design its self (Score:2, Insightful) (I might be making an assumption with how this is "distributed", friends and trusted servers might be acceptable. But i'm not going to give them the benefit of the doubt because they did a very poor job explaining important details like these.) Encryption should never be your only line of defence for PRIVATE information. "Distributed Encrypted Backups" and "distributed" is scary because this is PRIVATE information and not PUBLIC information, not only is this uncharted territory but it is fundamentally wrong. With Tor and Freenet there was nothing of value stored or transferred. A malicious user could archive torrents of encrypted personal information, even if it takes 20-50 years to crack this is unacceptable. Normally you are just packet sniffing on a small fraction of the population. This project could be a false prophet that will that will doom the success of any future social projects. Also, these client diversity and data portability concepts may not be compatible with attempts at real privacy and security, for example your perfect email client and server is at the mercy of the client on the other sending/receiving end. These concepts make the assumption that the indefinite storage of information is a good idea, while i happen to think that the expiration of messages is a good idea, and an idea that can look appealing with the right spin. (well, these concepts are may be ok for making the transition to something better, but i think it encourages defeatism, accepting to be average) disclaimer, i'm about to finish a security/privacy focused social networking website that isn't exactly 'open' for the foreseeable future but its not feature fancy/flashy either. Re:Freetard fail (Score:3, Insightful) Re:And that was to be expected (Score:3, Insightful) It states very clearly that this is ALPHA code. It's a bit too soon to formulate opinions on if its useable, right?:Freetard fail probably too late to use gnunet, freenet, other p2p or stuff as i2p or tahoe-lafs as an infrastructure, too. Like every other coder out there, including me, they are gonna pay for the NIH syndrome But ok, let's see what happens. Good luck to diaspora.
http://news.slashdot.org/story/10/09/17/148242/Security-Concerns-Paramount-After-Early-Reviews-of-Diaspora-Code/insightful-comments
CC-MAIN-2014-49
refinedweb
888
61.67
In late 2014 I built a tool called pymr. I recently felt the need to learn golang and refresh my ruby knowledge so I decided to revisit the idea of pymr and build it in multiple languages. In this post I will break down the “mr” (merr) application (pymr, gomr, rumr) and present the implementation of specific pieces in each language. I will provide an overall personal preference at the end but will leave the comparison of individual pieces up to you. For those that want to skip directly to the code check out the repo. Application Structure The basic idea of this application is that you have some set of related directories that you want to execute a single command on. The “mr” tool provides a method for registering directories, and a method for running commands on groups of registered directories. The application has the following components: - A command-line interface - A registration command (writes a file with given tags) - A run command (runs a given command on registered directories) Command-Line Interface The command line interface for the “mr” tools is: $ pymr --help Usage: pymr [OPTIONS] COMMAND [ARGS]... Options: --help Show this message and exit. Commands: register register a directory run run a given command in matching... To compare building the command-line interface let’s take a look at the register command in each language. Python (pymr) To build the command line interface in python I chose to use the click package. @pymr.command() @click.option('--directory', '-d', default='./') @click.option('--tag', '-t', multiple=True) @click.option('--append', is_flag=True) def register(directory, tag, append): ... Ruby (rumr) To build the command line interface in ruby I chose to use the thor gem. desc 'register', 'Register a directory' method_option :directory, aliases: '-d', type: :string, default: './', desc: 'Directory to register' method_option :tag, aliases: '-t', type: :array, default: 'default', desc: 'Tag/s to register' method_option :append, type: :boolean, desc: 'Append given tags to any existing tags?' def register ... Golang (gomr) To build the command line interface in Golang I chose to use the cli.go package. app.Commands = []cli.Command{ { Name: "register", Usage: "register a directory", Action: register, Flags: []cli.Flag{ cli.StringFlag{ Name: "directory, d", Value: "./", Usage: "directory to tag", }, cli.StringFlag{ Name: "tag, t", Value: "default", Usage: "tag to add for directory", }, cli.BoolFlag{ Name: "append", Usage: "append the tag to an existing registered directory", }, }, }, } The registration logic is as follows: - If the user asks to --appendread the .[py|ru|go]mrfile if it exists. - Merge the existing tags with the given tags. - Write a new .[...]mrfile with the new tags. This breaks down into a few small tasks we can compare in each language: - Searching for and reading a file. - Merging two items (only keeping the unique set) - Writing a file File Search Python (pymr) For python this involves the os module. pymr_file = os.path.join(directory, '.pymr') if os.path.exists(pymr_file): # ... Ruby (rumr) For ruby this involves the File class. rumr_file = File.join(directory, '.rumr') if File.exist?(rumr_file) # ... Golang (gomr) For golang this involves the path package. fn := path.Join(directory, ".gomr") if _, err := os.Stat(fn); err == nil { // ... } Unique Merge Python (pymr) For python this involves the use of a set. # new_tags and cur_tags are tuples new_tags = tuple(set(new_tags + cur_tags)) Ruby (rumr) For ruby this involves the use of the .uniq array method. # Edited (5/31) # old method: # new_tags = (new_tags + cur_tags).uniq # new_tags and cur_tags are arrays new_tags |= cur_tags Golang (gomr) For golang this involves the use of custom function. func AppendIfMissing(slice []string, i string) []string { for _, ele := range slice { if ele == i { return slice } } return append(slice, i) } for _, tag := range strings.Split(curTags, ",") { newTags = AppendIfMissing(newTags, tag) } File Read/Write I tried to choose the simplest possible file format to use in each language. Python (pymr) For python this involves the use of the pickle module. # read cur_tags = pickle.load(open(pymr_file)) # write pickle.dump(new_tags, open(pymr_file, 'wb')) Ruby (rumr) For ruby this involves the use of the YAML module. # read cur_tags = YAML.load_file(rumr_file) # write # Edited (5/31) # old method: # File.open(rumr_file, 'w') { |f| f.write new_tags.to_yaml } IO.write(rumr_file, new_tags.to_yaml) Golang (gomr) For golang this involves the use of the config package. // read cfg, _ := config.ReadDefault(".gomr") // write outCfg.WriteFile(fn, 0644, "gomr configuration file") Run (Command Execution) The run logic is as follows: - Recursively walk from the given basepath searching for .[...]mrfiles - Load a found file, and see if the given tag is in it - Call the given command in the directory of a matching file. This breaks down into a few small tasks we can compare in each language: - Recursive Directory Search - String Comparison - Calling a Shell Command Recursive Directory Search Python (pymr) For python this involves the os module and fnmatch module. for root, _, fns in os.walk(basepath): for fn in fnmatch.filter(fns, '.pymr'): # ... Ruby (rumr) For ruby this involves the Find and File classes. # Edited (5/31) # old method: # Find.find(basepath) do |path| # next unless File.basename(path) == '.rumr' Dir[File.join(options[:basepath], '**/.rumr')].each do |path| # ... Golang (gomr) For golang this requires the filepath package and a custom callback function. func RunGomr(ctx *cli.Context) filepath.WalkFunc { return func(path string, f os.FileInfo, err error) error { // ... if strings.Contains(path, ".gomr") { // ... } } } filepath.Walk(root, RunGomr(ctx)) String Comparison Python (pymr) Nothing additional is needed in python for this task. if tag in cur_tags: # ... Ruby (rumr) Nothing additional is needed in ruby for this task. if cur_tags.include? tag # ... Golang (gomr) For golang this requires the strings package. if strings.Contains(cur_tags, tag) { // ... } Calling a Shell Command Python (pymr) For python this requires the os module and the subprocess module. os.chdir(root) subprocess.call(command, shell=True) Ruby (rumr) For ruby this involves the Kernel module and the Backticks syntax. # Edited (5/31) # old method # puts `bash -c "cd #{base_path} && #{command}"` Dir.chdir(File.dirname(path)) { puts `#{command}` } Golang (gomr) For golang this involves the os package and the os/exec package. os.Chdir(filepath.Dir(path)) cmd := exec.Command("bash", "-c", command) stdout, err := cmd.Output() Packaging The ideal mode of distribution for this tool is via a package. A user could then install it tool install [pymr,rumr,gomr] and have a new command on there systems path to execute. I don’t want to go into packaging systems here, rather I will just show the basic configuration file needed in each language. Python (pymr) For python a setup.py is required. Once the package is created and uploaded it can be installed with pip install pymr. from setuptools import setup, find_packages classifiers = [ 'Environment :: Console', 'Operating System :: OS Independent', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7' ] setuptools_kwargs = { 'install_requires': [ 'click>=4,<5' ], 'entry_points': { 'console_scripts': [ 'pymr = pymr.pymr:pymr', ] } } setup( name='pymr', description='A tool for executing ANY command in a set of tagged directories.', author='Kyle W Purdon', author_email='kylepurdon@gmail.com', url='', download_url='', version='2.0.1', packages=find_packages(), classifiers=classifiers, **setuptools_kwargs ) Ruby (rumr) For ruby a rumr.gemspec is required. Once the gem is created and uploaded is can be installed with gem install rumr. Gem::Specification.new do |s| s.name = 'rumr' s.version = '1.0.0' s.summary = 'Run system commands in sets' \ ' of registered and tagged directories.' s.description = '[Ru]by [m]ulti-[r]epository Tool' s.authors = ['Kyle W. Purdon'] s.email = 'kylepurdon@gmail.com' s.files = ['lib/rumr.rb'] s.homepage = '' s.license = 'GPLv3' s.executables << 'rumr' s.add_dependency('thor', ['~>0.19.1']) end Golang (gomr) For golang the source is simply compiled into a binary that can be redistributed. There is no additional file needed and currently no package repository to push to. Conclusion: Command-Line Interface Declaration Python is the winner here. The click libraries decorator style declaration is clean and simple. Keep in mind I have only tried the Ruby thor gem so there may be better solutions in Ruby. This is also not a commentary on either language, rather that the CLI library I used in python is my preference. Recursive Directory Search Ruby is the winner here. I found that this entire section of code was much cleaner and more readable using ruby’s Find.find() and especially the next unless syntax. Packaging Ruby is the winner here. The rumr.gemspec file is much simpler and the process of building and pushing a gem was much simpler as well. The bundler tool also makes installing in semi-isolated environments a snap. Final Determination Because of packaging and the recursive directory search preference I would choose Ruby as the tool for this application. However the differences in preference were so minor that Python would be more than fitting as well. Golang however, is not the correct tool here. This post was originally authored on Kyle’s personal blog and included great discussion on Reddit.
https://realpython.com/python-ruby-and-golang-a-command-line-application-comparison/?utm_source=golangweekly&utm_medium=email
CC-MAIN-2021-49
refinedweb
1,507
59.4
Product Version = NetBeans IDE 7.1.1 (Build 201202271535) Operating System = Windows 7 version 6.1 running on amd64 Java; VM; Vendor = 1.7.0_03 Runtime = Java HotSpot(TM) 64-Bit Server VM 22.1-b02 While editing an FXML file in a Netbeans' JavaFX project, the Navigator window does not display any element hierarchy. Also, the FXML editor window does not provide any sugestions while typing some FXML element, even using the FXML xml namespace. Navigator display fixed in jetmain: Thanks Svata for help with this. Please note that FXML code completion is a complex issue and is still under development, see Integrated into 'main-golden', will be available in build *201205120400* on (upload may still be in progress) Changeset: User: Petr Somol <psomol@netbeans.org> Log: #209819 - Navigator window does not display FXML elements hierarchy
https://netbeans.org/bugzilla/show_bug.cgi?id=209819
CC-MAIN-2015-14
refinedweb
137
57.37
Invest Description Category : Inforensic Points : 50 “A paranoid guy seems to have secured his file very well. But I am convinced he made a mistake somewhere.” Solution The challenge provided us with invest.pcapng, a packet capture for us to analyze. With Wireshark we could extract several files with File->Export Objects->HTML. Within the pcap is a file called ‘key.txt’, which contains a binary chain. Interpreting the chain in ASCII showed that it does not look really random: G^cnI9^GG9G9G9G9^cnInI95^c95nInIG^95nI^cG^95^c^c^cG^^cnIG^95G^nI^c^cnI^c^c95G^^c^c^cG^G^^cnInI^c The pcap also contains several pictures; one in particular seems interesting: We noticed that this function takes 8 bit as input and output one bit. Among the downloaded they were 81 files with their name starting by encrypt. They are base64 encoded. We merged, decoded them and obtained a file which start with the string ``Salted__`. >binwalk merged.bin DECIMAL HEXADECIMAL DESCRIPTION -------------------------------------------------------------------------------- 0 0x0 OpenSSL encryption, salted, salt: 0x7DD883F026435AB8 It means it is a file encrypted with OpenSSL. Then we coded the function represented by the previous picture: import binascii key="010001110101111001100011011011100100100100111001010111100100011101000111001110010100011100111001010001110011100101000111001110010101111001100011011011100100100101101110010010010011100100110101010111100110001100111001001101010110111001001001011011100100100101000111010111100011100100110101011011100100100101011110011000110100011101011110001110010011010101011110011000110101111001100011010111100110001101000111010111100101111001100011011011100100100101000111010111100011100100110101010001110101111001101110010010010101111001100011010111100110001101101110010010010101111001100011010111100110001100111001001101010100011101011110010111100110001101011110011000110101111001100011010001110101111001000111010111100101111001100011011011100100100101101110010010010101111001100011" chunks, chunkSize = len(key), 8 l = [ key[i:i + chunkSize] for i in range(0, chunks, chunkSize) ] # The logic part s = "" for b in l: b0 = int(b[0]) b1 = int(b[1]) b2 = int(b[2]) b3 = int(b[3] b4 = int(b[4]) b5 = int(b[5]) b6 = int(b[6]) b7 = int(b[7]) c1 = b0 and (not b2) c2 = (not b2) and (not b1) c3 = b0 and b1 c4 = b5 ^ b6 c5 = (not b1) ^ (not b7) d1 = c1 and (not b3) d2 = c2 and (not b3) d3 = c3 and (not b3) d4 = b2 and (not b5) d5 = c5 and b2 e1 = d1 and (not b4) e2 = d2 and (not b4) e3 = d3 and (not b4) e4 = d4 and c4 f1 = e1 or e2 f2 = e3 or e4 g = f2 or d5 o = int(g or f1) s += str(o) password = binascii.unhexlify(hex(int(s,2))[2:]) print(password) We passed the string contains in key.txt to the script and we obtained the string “4Ukz95F2YqPi”. The string is 12-byte long. We did not know any cipher using such length for the key so we thought about a password. Since the guy is paranoid he would have used a strong block cipher. We started with AES-128: openssl enc -aes128 -in merged.bin -out merged.out -d -k 4Ukz95F2YqPi -p salt=7DD883F026435AB8 key=215350CECF73E345AF6894267B335AA0 iv =7413F91D4B87534B953CC656476C3107 bad decrypt 140385251583632:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:evp_enc.c:529: Then we tried AES-256: openssl enc -aes256 -in merged.bin -out merged.out -d -k 4Ukz95F2YqPi -p salt=7DD883F026435AB8 key=215350CECF73E345AF6894267B335AA07413F91D4B87534B953CC656476C3107 iv =C2E8D310CAD4C7A8CC4CD67BA81E672F The file was decrypted properly. The decrypted file is a Word file which shows a picture. We unzip the file a run a grep on the repository. grep "NDH" -r merged.out_FILES/ <w:t>NDH[59rRS57bd5WH8RxgPbRS27q89a5bWrjL]</w:t> It revealed the flag. However we could have open the file and move or delete the image to display the flag.
https://duksctf.github.io/resources/2016/ndh/invest/invest.html
CC-MAIN-2021-25
refinedweb
524
72.97
class Timer – control internal timers¶ Timers can be used for a great variety of tasks. At the moment, only the simplest case is implemented: that of calling a function periodically. Each timer consists of a counter that counts up at a certain rate. The rate at which it counts is the peripheral clock frequency (in Hz) divided by the timer prescaler. When the counter reaches the timer period it triggers an event, and the counter resets back to zero. By using the callback method, the timer event can call a Python function. Example usage to toggle an LED at a fixed frequency: tim = pyb.Timer(4) # create a timer object using timer 4 tim.init(freq=2) # trigger at 2Hz tim.callback(lambda t:pyb.LED(1).toggle()) Example using named function for the callback: def tick(timer): # we will receive the timer object when being called print(timer.counter()) # show current timer's counter value tim = pyb.Timer(4, freq=1) # create a timer object using timer 4 - trigger at 1Hz tim.callback(tick) # set the callback to our tick function Further examples: tim = pyb.Timer(4, freq=100) # freq in Hz tim = pyb.Timer(4, prescaler=0, period=99) tim.counter() # get counter (can also set) tim.prescaler(2) # set prescaler (can also get) tim.period(199) # set period (can also get) tim.callback(lambda t: ...) # set callback for update interrupt (t=tim instance) tim.callback(None) # clear callback Note: Timer(2) and Timer(3) are used for PWM to set the intensity of LED(3) and LED(4) respectively. But these timers are only configured for PWM if the intensity of the relevant LED is set to a value between 1 and 254. If the intensity feature of the LEDs is not used then these timers are free for general purpose use. Similarly, Timer(5) controls the servo driver, and Timer(6) is used for timed ADC/DAC reading/writing. It is recommended to use the other timers in your programs. Note: Memory can’t be allocated during a callback (an interrupt) and so exceptions raised within a callback don’t give much information. See micropython.alloc_emergency_exception_buf() for how to get around this limitation. Constructors¶ Methods¶ - Timer.init(*, freq, prescaler, period, mode=Timer.UP, div=1, callback=None, deadtime=0)¶ Initialise the timer. Initialisation must be either by frequency (in Hz) or by prescaler and period: tim.init(freq=100) # set the timer to trigger at 100Hz tim.init(prescaler=83, period=999) # set the prescaler and period directly Keyword arguments: freq— specifies the periodic frequency of the timer. You might also view this as the frequency with which the timer goes through one complete cycle. prescaler[0-0xffff] - specifies the value to be loaded into the timer’s Prescaler Register (PSC). The timer clock source is divided by ( prescaler + 1) to arrive at the timer clock. Timers 2-7 and 12-14 have a clock source of 84 MHz (pyb.freq()[2] * 2), and Timers 1, and 8-11 have a clock source of 168 MHz (pyb.freq()[3] * 2). period[0-0xffff] for timers 1, 3, 4, and 6-15. [0-0x3fffffff] for timers 2 & 5. Specifies the value to be loaded into the timer’s AutoReload Register (ARR). This determines the period of the timer (i.e. when the counter cycles). The timer counter will roll-over after period + 1timer clock cycles. modecan be one of: Timer.UP- configures the timer to count from 0 to ARR (default) Timer.DOWN- configures the timer to count from ARR down to 0. Timer.CENTER- configures the timer to count from 0 to ARR and then back down to 0. divcan be one of 1, 2, or 4. Divides the timer clock to determine the sampling clock used by the digital filters. callback- as per Timer.callback() deadtime- specifies the amount of “dead” or inactive time between transitions on complimentary channels (both channels will be inactive) for this time). deadtimemay be an integer between 0 and 1008, with the following restrictions: 0-128 in steps of 1. 128-256 in steps of 2, 256-512 in steps of 8, and 512-1008 in steps of 16. deadtimemeasures ticks of source_freqdivided by divclock ticks. deadtimeis only available on timers 1 and 8. You must either specify freq or both of period and prescaler. - Timer.deinit()¶ Deinitialises the timer. Disables the callback (and the associated irq). Disables any channel callbacks (and the associated irq). Stops the timer, and disables the timer peripheral. - Timer.callback(fun)¶ Set the function to be called when the timer triggers. funis passed 1 argument, the timer object. If funis Nonethen the callback will be disabled. - Timer.channel(channel, mode, ...)¶ If only a channel number is passed, then a previously initialized channel object is returned (or Noneif there is no previous channel). Otherwise, a TimerChannel object is initialized and returned. Each channel can be configured to perform pwm, output compare, or input capture. All channels share the same underlying timer, which means that they share the same timer clock. Keyword arguments: modecan be one of: Timer.PWM— configure the timer in PWM mode (active high). Timer.PWM_INVERTED— configure the timer in PWM mode (active low). Timer.OC_TIMING— indicates that no pin is driven. Timer.OC_ACTIVE— the pin will be made active when a compare match occurs (active is determined by polarity) Timer.OC_INACTIVE— the pin will be made inactive when a compare match occurs. Timer.OC_TOGGLE— the pin will be toggled when an compare match occurs. Timer.OC_FORCED_ACTIVE— the pin is forced active (compare match is ignored). Timer.OC_FORCED_INACTIVE— the pin is forced inactive (compare match is ignored). Timer.IC— configure the timer in Input Capture mode. Timer.ENC_A— configure the timer in Encoder mode. The counter only changes when CH1 changes. Timer.ENC_B— configure the timer in Encoder mode. The counter only changes when CH2 changes. Timer.ENC_AB— configure the timer in Encoder mode. The counter changes when CH1 or CH2 changes. callback- as per TimerChannel.callback() pinNone (the default) or a Pin object. If specified (and not None) this will cause the alternate function of the the indicated pin to be configured for this timer channel. An error will be raised if the pin doesn’t support any alternate functions for this timer channel. Keyword arguments for Timer.PWM modes: pulse_width- determines the initial pulse width value to use. pulse_width_percent- determines the initial pulse width percentage to use. Keyword arguments for Timer.OC modes: compare- determines the initial value of the compare register. polaritycan be one of: Timer.HIGH- output is active high Timer.LOW- output is active low Optional keyword arguments for Timer.IC modes: polaritycan be one of: Timer.RISING- captures on rising edge. Timer.FALLING- captures on falling edge. Timer.BOTH- captures on both edges. Note that capture only works on the primary channel, and not on the complimentary channels. Notes for Timer.ENC modes: Requires 2 pins, so one or both pins will need to be configured to use the appropriate timer AF using the Pin API. Read the encoder value using the timer.counter() method. Only works on CH1 and CH2 (and not on CH1N or CH2N) The channel number is ignored when setting the encoder mode. PWM Example: timer = pyb.Timer(2, freq=1000) ch2 = timer.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.X2, pulse_width=8000) ch3 = timer.channel(3, pyb.Timer.PWM, pin=pyb.Pin.board.X3, pulse_width=16000) class TimerChannel — setup a channel for a timer¶ Timer channels are used to generate/capture a signal using a timer. TimerChannel objects are created using the Timer.channel() method. Methods¶ - timerchannel.callback(fun)¶ Set the function to be called when the timer channel triggers. funis passed 1 argument, the timer object. If funis Nonethen the callback will be disabled. - timerchannel.capture([value])¶ Get or set the capture value associated with a channel. capture, compare, and pulse_width are all aliases for the same function. capture is the logical name to use when the channel is in input capture mode. - timerchannel.compare([value])¶ Get or set the compare value associated with a channel. capture, compare, and pulse_width are all aliases for the same function. compare is the logical name to use when the channel is in output compare mode. - timerchannel.pulse_width([value])¶ Get or set the pulse width value associated with a channel. capture, compare, and pulse_width are all aliases for the same function. pulse_width is the logical name to use when the channel is in PWM mode. In edge aligned mode, a pulse_width of period + 1corresponds to a duty cycle of 100% In center aligned mode, a pulse width of periodcorresponds to a duty cycle of 100% - timerchannel.pulse_width_percent([value])¶ Get or set the pulse width percentage associated with a channel. The value is a number between 0 and 100 and sets the percentage of the timer period for which the pulse is active. The value can be an integer or floating-point number for more accuracy. For example, a value of 25 gives a duty cycle of 25%.
https://docs.micropython.org/en/latest/library/pyb.Timer.html
CC-MAIN-2022-21
refinedweb
1,513
68.97
The Gnome Print widget module of Gtk-Perl (Gnome::Print namespace). WWW: No installation instructions: this port has been deleted. The package name of this deleted port was: p5-GnomePrint p5-GnomePrint PKGNAME: p5-GnomePrint ONLY_FOR_ARCHS: nil NOT_FOR_ARCHS: nil distinfo: There is no distinfo for this port. NOTE: FreshPorts displays only information on required and default dependencies. Optional dependencies are not covered. No options to configure Number of commits found: 14 Remove expired ports This port is scheduled for deletion on 2005-09-22 if it is still broken at that time and no PRs have been submitted to fix it. BROKEN: Incomplete pkg-plist Approved by: portmgr (self) reset MAINTAINER bit to ports@ I have no too much time to maintain. Add SIZE. Submitted by: trevor Bump PORTREVISION on all ports that depend on gettext to aid with upgrading. (Part 1) Make IGNORE for perl < 5.6. Upgrade to 0.7009. 0.7008 Upgrade to 0.7006. Various patches (mainly shared library revision changes) for those ports that depend on GNOME and need to change for 1.4 Add p5-GnomePrint, it's perl binding to Gnomeprint library. Servers and bandwidth provided byNew York Internet, SuperNews, and RootBSD 12 vulnerabilities affecting 44 ports have been reported in the past 14 days * - modified, not new All vulnerabilities
http://www.freshports.org/print/p5-GnomePrint/
CC-MAIN-2017-22
refinedweb
217
65.32
. The plan is to provide a base for a future native KDE port. Several screenshots of the ongoing port are available. Richard is seeking developers, who don't have access to the original Qt Windows sources, to help him. Holger Schroeder of Automatix GmbH, who started the native Win32 port of the Qt2 library and finished about half of it before license conflicts due to use of the commercial Qt version disallowed him to continue, will be present in Nové Hrady at the KDE Contributor Conference 2003 and give a talk about the "KDE on Cygwin" project and its current state. Very cool indeed ! So sooner or later, native Konqueror for Windows isn't a dream anymore. Not cool indeed. First reason would be that I consider this as a complete waste of time, which could be invested in projects useful to free software users. Needless to say that there are good reasons why developping fs on windows is not a good thing : . Second and much more important. Qt once made a real gift to the community by licensing their extraordinary graphical toolkit (the best ever, every platform, etc. that may be) with the GPL licence. There decision was surely not easily made at this time. Do you really think we should made them doubt to continue licensing their following work with the GPL. They live thanks to the proprietary version of their Windows toolkit. Let's make them live and leave them on that... Free software is also a matter of respect, and some should never forget that. I forgot: it's long since windows has ever been a "dream"... Last time was win3.11fwg for me. Why don't just leave windows if you want kde on it ? Or kill your boss if he doesn't want to, or just change job ? If everyone does so, only incompetent people will still use windows and this bunch of idiots will spend a _lot_ of time working together with their poor skills: that sounds like a better dream to me. There must be a reason why Trolltech doesn't give Qt away for free on Windows, don't you think? Why don't you guys spend your time on something more useful: make Qt work on DirectFB or so. That would help all Linux people instead of just those 2 Windows freaks out there trying to run KDE apps on top of a bad OS. And if people can run KDE apps on Windows there aren't much reasons to run Linux anymore. (except for staying away from the blue screens and Bills money eater) Are you sure that is really what you guys want? ?) >There must be a reason why Trolltech doesn't give Qt away for free on Windows, don't you think? But what is that reason? It cant be money. I think it would be better to Trolltech if they just release Free QT for Windows and Mac OS. That is best way to QT become de-facto standard in cross-platform toolkits. >And if people can run KDE apps on Windows there aren't much reasons to run Linux >anymore. I disagree with you. It is not harmfull to Linux or KDE either if you could run KDE apps natively in Windows. >> But what is that reason? It cant be money. I think it would be better to Trolltech >> if they just release Free QT for Windows and Mac OS. >> That is best way to QT become de-facto standard in cross-platform toolkits. If there's a GPL-ed version of Qt for Windows companies can use it to create inhouse apps without paying Trolltech. Yes, I think money is one of the reasons. >> I disagree with you. It is not harmfull to Linux or KDE either if you could run KDE apps natively in Windows. I truely hope you're right about that.. It's not harmful to Linux - once windows users are familiar with using linux applications, if they discover that the switch is seamless - no change of their choice of apps, then all the better for us. The problem with most (Windows) users I know is that they're saying: "hey, if Linux doesn't have any additional value, why would I switch?" (they don't care if it's free or not because Windows is 'free' as well) And switching from Windows to Linux isn't just about the apps. If there's a GPL-ed version of Qt for Windows companies can use it to create inhouse apps without paying Trolltech. If there's GPL-ed version of Qt for windows, companies willing to use the free version will be forced to release their software as GPL-ed, so companies that use Qt on Windows won't use the free version like photoshop and that supposedly fast browser I keep forgetting the name. That means those companies will keep using the proprietary version and trolltech won't make any less money. Also that would be great cause people will be allowed to use great apps such as Kopete, Konqueror and the like on Windows. I really do think it's a win-win situation for floss software :) >> companies willing to use the free version will be forced to release their software as GPL-ed You have got to be kidding.. indeed. Re-read the GPL please. Nothing would stop Trolltech from releasing a free Qt for windows under a modified GPL that doesn't allow using the free version for in-house development. Good point - but then the problem would be again misuse. > Nothing would stop Trolltech from releasing a free Qt for windows under a modified GPL that doesn't allow using the free version for in-house development. Technically true, except such a license would not be compatible with the GPL and therefore unable to run KDE. > There must be a reason why Trolltech doesn't give Qt away for free on Windows, don't you think? Probably because they consider it to not be in their best interests. > Why don't you guys spend your time on something more useful Probably because those guys working on it consider it to be useful. Scratching an itch and all that. > And if people can run KDE apps on Windows there aren't much reasons to run Linux anymore. Windows has plenty of applications already. This isn't about KDE applications, it's about Qt applications. Increased userbase for Qt applications means higher quality across all platforms. > ?) Stop whining and do something about it then! >> This isn't about KDE applications, it's about Qt applications. Let me quote this for you: "The plan is to provide a base for a future native KDE port." >> Stop whining and do something about it then! How can I do something about it if even one of the greatest guys that has been kicked out of the team isn't able to change things drastically? Getting kicked off the team hasn't stopped Keith Packard. Just check out If he can't change the group from within, it seems he'll change the group from without. I would strongly disagree that this is a bad thing. KDE, and the Qt/Free community stand to gain a lot by this. If one could write apps with Qt's great framework for Free on Windows, many of those apps will eventually end up on KGX (KDE/GNU/linuX). Moreover, increased adoption of technologies such as Konqueror/KHTML, KMail, and KOffice will encourage more standards compliant web sites, e-mail messages, and document formats. It's all good stuff. Konqueror is the best part, IMO. If Konqueror/KHTML are available in a native Windows format, that would mean that KHTML would be available for almost all users (Konqueror on Linux/*nix/Windows/Mac and Safari on Mac). Since Qt/Free is now available for Mac OS X, a Windows version is the last step towards a very cross platform Free Software solution. I might also add, the pressure of a community port might make TrollTech inclined to release and official Qt/Free Win32 version, since TT would gain volunteer support for their Win32 version that way... something they won't do if the Qt/Free Win32 version is a seperate codebase from their own Win32 version. I doubt it will hurt TT much, since many companies won't want their software licensed under a GPL compatible license. Furthermore, it probably won't have the full Visual Studio integration like TT offers. -Tim >I doubt it will hurt TT much, since many companies won't want their software licensed under a > GPL compatible license. What about companies that write software internally? How many of these companies actually write these in-house, vs hiring consultants? If consultants write software, or the company hires another one to write the software, the GPL kicks in. "Why don't you guys spend your time on something more useful: make Qt work on DirectFB or so." Translation: someone on Slashdot said that XFree86 sux, and DirectFB is l33t, so why don't you work on that instead? "And if people can run KDE apps on Windows there aren't much reasons to run Linux anymore." Translation: I have no idea what Linux is all about, so I'm assuming it must just be the KDE thing. "why would I want to stay with Linux and the slow XFree86?" Translation: back to this XFree86 thing, I also heard it was slow, but I never actually checked it out for myself, and am only assuming that the exceedingly sparse and barren feature set of the win32 API should be enough for anybody. I'm wondering why I'm replying to this, but what the heck.. >> Translation: someone on Slashdot said that XFree86 sux, and DirectFB is l33t, so why don't you work on that instead? XFree86 does not completely suck, but it's development is more or less stopped (except for the bugfixes). That's my problem with it, almost no new features and no new code to actually _improve_ things is being added anymore, and the core team members seem to be happy with that. DirectFB is certainly cool, but not usable (especially when using a NVIDIA graphics card). >> Translation: I have no idea what Linux is all about, so I'm assuming it must just be the KDE thing. Seeing how you speak with words like 'l33t' and 'sux' and visiting sites like Slashdot tells me enough about what you actually know. >> Translation: back to this XFree86 thing, I also heard it was slow, but I never actually checked it out for myself, and am only assuming that the exceedingly sparse and barren feature set of the win32 API should be enough for anybody. At least the win32 GDI is multi threaded, doesn't block on many functions, doesn't have any slow way to get properties, ..... yadda, yadda, yadda, ......, and most importantly; it does not _feel_ slow, like XFree86. I swear that TuxRacer on Linux/XFree86 doesn't feel slow at all. That's because TuxRacer uses OpenGL, which does not use _any_ drawing functions from XFree86, and doesn't really use the other XFree86 stuff either (except for setting up some initial settings and a window, but that doesn't make a program slow). Wouldn't Qt GPL on DirectFB be pretty close to Qt/Embedded? I think you can even use Qt/E under the GPL. Yeah, go ahead, port more free software on non-free platforms. Why couln't these people work on something really useful ? Koffice, Kdevelop, Wine , Samba .. all these projects need help (koffice especially). If Koffice want's to be really usefull and used on as many computers as possible then needs to run on as many plattforms as posibble. It means Mac and it means Windows (think about OpenOffice). Creating freely usable Qt on Windows is first step. If your primary goal is to make everybody use KOffice, yes. If your primary goal is to make everybody use free software, then certainly not. Simply for the same reason that Microsoft stops to port Office to Linux (beside the PR effect), even if they could make money with it. KOffice would help Windows, because it lowers the overall costs (just as OO already does, but Sun does it only to cut off MS's primary source of revenue). I want everybody to use free software. But you can't switch right now - there are missing some applications (MicroStation, ...). So I can go slow route - switch some apps for now and wait for other apps to catch up. OpenOffice is great for this. Having KDE apps on Windows can be very usefull in this scenario. Yes this can hurt Trolltech. But maybe not. GPL version of QT can be used only for inhouse development. GPL version can be created to only work with gcc (yes somebody can port this to msvc) and without msvc development environment integration. Trolltech don't want to release GPL version of X11 (linux/unix) Qt because they think it will hurt them. Harmony created pressure forces them to release GPL version. From today point of view I beliewe GPL version helped Trolltech. Maybe Win32 GPL version can help them too. In my opinion it is better to have a common open office file standard than having koffice on Windoze. I think that porting more and more KDE applications over to Windoze does not free us from the Microsoft monopoly, on the contrary, people are lazy enough and will stay on Windows forever as they are too ignorant to learn and understand that the 21st century is the information century and whoever controls the underlying information storage, processing and distribution framework rools the world. On Windoze people will probably more likely stick with MS office, as it will always be the best integrated office suite on this platform (as MS controls the underlying API). Microsoft will lower the price for their office suite so much that the free software alternatives will have great difficulties competing - remember, most people are only interested in free beer as they are ignorants and don't understand the importance of free speech. because most users use the OS that was installed when they bought the computer. And what does [insert name of discounter here] do when they have to make the decision: ok, we got 50.000 comps to sell here, + windows each does ~50.000*20=1 million. So if we put Linux on it, we could do that for free (without license cost), if we wanted to. Mhh. Windows is buggy and confusing, Linux is easy and performant. Mhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh... => Sooner or later Open Source will prevail even though capitalism... And I think maybe end of this year it'll start... with kernel 2.6; Koffice 1.3; KDE 3.2; Kdevelop 3 it should kick M$ ass - for free (muahmuah) good thing ain't it.. ciao Marcel > ...Samba .. all these projects need help I would put the Samba server on the list of software that helps to promote (or rather keep) proprietary software on the desktop. If people want to use proprietary desktops, they should pay the full price for their servers. If people want to access free systems from proprietary systems, they should implement a file system that allows the proprietary systems to access the data on the free systems. (of course I can not stop anybody to do what he want with his time or money, but if you want to help to create a free infrastructure I would suggest you to work one something that helps free software by making free software better, and not by lowering the costs for the competition...) "Why couln't these people work on something really useful " Maybe because its a hobby? And they want to work on a GPL port fo QT to win32? Why do people play video games? Couldn't they be working on something really useful? These people aren't factory slaves that can be ordered around. They are real people that have interests and ambitions. They do what they want within reason (usually). would be a LGPL "port" of Qt. That would make it attractive to more developers who must now use GTK+/wxWindows/other for licensing reasons. Do you want to destroy Trolltech? Actually, since an identical API exists under the QPL/GPL licensing, the upshot of a GPLd Qt-Windows is that it still acts as QPL/GPL. Why? Because the application is no longer tied to a specific implementation and its license. This same issue came up during discussions of Harmony's licensing, and RMS himself remarked that a GPL Harmony would act as a QPL/GPL Qt. It still won't allow proprietary applications to link to the library, but it's much more free than a GPL-only requirement. void Windoze (Fools) { Support QT by buying QT for Windoze. If you want QT around in the next decade buy QT for Windoze. Why push out of the market a great company like TrollTech by porting QT to Windoze. return (Fools) } You may not know that through Qt 2.x TrollTech offered Qt/Windows under the GPL. Yet somehow they weren't destroyed. By the way, don't pretend you are a coder. You clearly aren't. Yes, at one point (and for 1 release only!), Trolltech released Qt 2.x for Windows. As was once said on the Trolltech mailing list: the results were disastrous, with a very sudden decrease in the number of sold licenses. I know quite some companies that use Qt only for in-house tools that will never be used outside the company. GPL does NOT force anybody to release code to the rest of the world. They only require to release the source code when binaries are released. In other words, all those in-house tools that were developped for Windows suddenly didn't need a commercial license. Hence the drop in revenue for Trolltech... Tom Hmm, then TrollTech has no reason to actually want to see KDE/Linux succeed on the desktop? If what you say is true, then TrollTech exists by virtue of the Windows desktop monopoly (because that's where their licensing revenue comes from, or at least that's what you claim). And, since both MacOS X and Unix/X versions of Qt are "free", if one of these platforms would take a significant/majority share of the desktop market (which is what we're all rooting for, no?), this would dramatically reduce Qt/Windows revenue. At which point it might suddenly be in TrollTech's best interest _not_ to support KDE/Unix (by not offering newer versions of GPL'ed Qt, for example) any longer. Thus, if what you say is true, then KDE's success on the desktop risks destroying the company that created and supports one of KDE's base technologies... Obviously they have a business interest in seeing KDE succeed. Any non-free KDE application requires a commercial Qt license per developer, because you can not avoid using Qt for KDE applications. Trolltech has in interest seeing the KDE desktop *framework* succeed, since many extensions of Qt features in KDE libs are later integrated back into Qt itself, thus encouraging KDE developers preferring Qt also for commercial projects. On Unix and alike KDE as a desktop framework is already the most widespread so supporting it without sacrifying much is easy. On OSX Apple successfully convinced people that their system represents a Unix alike system encouraging the use of both commercial and non-commercial Unix solutions. While OSX itself already offers a desktop framework solution itself Trolltech obviously is confident that the KDE desktop framework will be accepted as well by many OSX users. This can't be said of Windows user, the acceptance for an alternative desktop framework is not there thus limiting the use of Qt to it sole toolkit self. And as a toolkit without desktop framework around it encourages more in house developments (since "it's easier") than commercial apps integrated with Qt. A GPL'ed Qt hurts the former and boosts the latter. The latter, as mentioned, is none-existant on Windows tho so there won't exist an official GPL'ed Qt for Windows by Trolltech. I really hope those working on a GPL Qt for Windows are aware of this situation and better disallow the usage of their Qt port alone without KDE libs for this very reason. You seem to understand TrollTech's interest in KDE (the framework) as rooted in TrollTech's view of KDE as an interesting (and free) feature research and test platform. Hadn't looked at it from that angle, and I must say it could make sense. I don't agree with your point of view re. MacOS X. I'd say there's just as few Mac users interested in running KDE (desktop) apps as there are Windows users interested in that (percentagewise that is, there's a lot more Windows users than Mac users, I believe ;-). Yet there is a free Qt for MacOS X, and not for Windows. So that leaves marketshare of both OSes as an important factor. Which results in an interesting situation should these marketshare figures significantly change in favor of free OSes like Linux, the BSDs, etc. Not that I don't agree that a GPL Qt/Windows port separate from TrollTech appears to be a waste of time, at least to me. Then again, since I'm not writing code for it, who am I to say what this/these guy(s) should do. If they're itching, let them scratch it! You are kind of missing the point: Of course there's just as few Mac users interested in running this or that framework as there are Windows users interested in that, users naturally shouldn't even need to bother about this kind of stuff. What makes the OSX platform different from the Windows platform is that Microsoft on the one hand is known for trying to offer more and more all-included packages for every possible solution which sells (and buying up small specialized companies all the time for that purpose). Combined with their quasi-monopolistic position in the market this is strongly discouraging alternative solutions by competitors on the same platfrom. Apple on the other hand already support KDE indirectly by using and contributing to kjs and khtml, they actively supported Trolltech for having a well integrated Qt/Mac, they advertise OSX as Unix compatible system and offer a native X Window implementation encouraging the use of non-OSX specific software as well. There are worlds between Microsoft and Apple, and Trolltech offering a GPL'ed Qt on OSX is a consequential result of that imo. Don't you think they stopped providing it under GPL for windows for a reason? They didn't offer it under the GPL. They offered it under a license that forbids all commercial use. First, you can still download Qt/Windows 2.3.1 from TrollTech's site: I suppose TrollTech didn't find it so destructive after all. Second, as pointed out by SadEagle, the license isn't GPL, but a different license that forbids commercial use. I don't know if that includes in-house development at companies, though. Maybe a solution would be that TrollTech donated a license to KDE that couldn't legally be used for any other purpose than porting KDE to Windows. Yes I know what you mean, Trolltech is a great company, and KDE owes, well, a great deal to them. I don't know how KDE would have been without the terrific toolkit that is Qt. I find myself not wanting this project. Qt is something that is great because a company is behind it. Yes there are benefits to the larger community if there is a win32 open source port, but at what costs? I'd not have started this project as I feel I owe too much to Trolltech. I don't spose we'll know the effects for a few years. I hope it turns out ok. You have a point. But, I can't just buy an individual license for like $50.00. -- JRT Hopefully they are cooperating with the already (at least partially existing) port of Qt to win32 of the KDEonCygwin-Project. - me. KDE + win XP ? You need a cluster :P
https://dot.kde.org/2003/07/11/native-win32-port-qt3-gpl-started
CC-MAIN-2017-43
refinedweb
4,092
71.65
Rationale Promises are one of my favorite features of all the ECMAScript standards and provide a clever way of dealing with asynchronous results that can either be resolved or rejected. But sometimes, when the source-code is growing, it can be tedious to work with, especially when error messages can be easily ignored. If you don't care about the error messages, but rather the end result, you can provide a simple fallback value with this simple trick. Context Let's say you wanted to fetch the list of users from your API. <!DOCTYPE html> <html> <body> <script> "use strict"; fetch(""); </script> </body> </html> In this short example, we are using the Fetch API to ask our API for a list of users. Of course, we need to deal with the success (resolved) and errors (rejected) cases. <!DOCTYPE html> <html> <body> <script> "use strict"; fetch("").then(response => { return response.json(); }).then(users => { console.log(users); }).catch(() => { console.error("Yep, no users."); }); </script> </body> </html> In this particular example, we don't really care about the reason why it would reject, we simply want to provide a default value. We could do that in a more imperative way using an async function. <!DOCTYPE html> <html> <body> <script> "use strict"; const main = async () => { let users = []; try { const response = await fetch("") users = await response.json(); } catch { // ... discarded } console.log(users); }; main(); </script> </body> </html> Here we are using an async function to imperatively handle each step of our promise. And if it fails, we simply have our default value that will kick in when we log the result. This works well and as intended, but this is a lot of work for so little. Plus, we are using a try-catch with the catch part that is being discarded and is pretty much useless. Let's see if we can find an alternative to all of this. Alternative Since the await keyword is used on a promise, nothing can stop you from writing all the promise instructions in one line and provide a default value right away. <!DOCTYPE html> <html> <body> <script> "use strict"; const main = async () => { const users = await fetch("...").then(response => response.json()).catch(() => []); console.log(users); }; main(); </script> </body> </html> Let's break this down real quick. fetch("..."); This is our promise. Nothing fancy, it will just fetch our data as earlier. .then(response => response.json()) This is the part where we handle any resolved value. This means that when the response can be turned into a JSON value, we will receive what's behind this call (here, the list of users). .catch(() => []); This is the part where we handle the error. Here we simply say that instead of logging anything, we simply return a default value. Here it is an empty array so that it becomes easy to work with our data even if the request fails. fetch("...").then(response => response.json()).catch(() => []); All of this is a single promise. This is important to understand because this is literally the heart of this technique. Because we have only one single promise here we are able to use what is coming next. It will either reject and trigger the .then part, or fail and trigger the .catch part. You handled all possible cases in one line and whatever the outcome of the promise is, you know that you have a value for one or the other. await fetch("...")... Here we simply make sure that anything that is being done on this line with the promise should be blocking the function until the promise is either resolved (the list of users) or rejected (the empty array). If we put this all together, this means that in one line, you can easily request data from an API, tell it how you want it to be (either JSON or Text), and provide a default value in case it fails to fetch the data. And this lets you use a nice two-liner for requesting and displaying any data from an API. const users = await fetch("...").then(response => response.json()).catch(() => []); console.log(users); Conclusion This technique is very interesting because it lets you prototype things quickly, and even if you don't really need the error message. If you are on a recent version of Node.js and using an ECMAScript Module, you can even leverage the new top-level await feature to make this a short little script. $ npm install node-fetch $ touch index.mjs import fetch from "node-fetch"; const users = await fetch("").then(response => response.json()).catch(() => []); console.log(users); $ node index.mjs [...] (output truncated) Be aware that any error messages will be hidden and so this technique is not well suited in a large application where you want to have controls and monitoring about what failed, and possibly file error reports to a third-party application like Sentry. Also, the goal of this technique is definitively not to be clear and readable, if you are concerned about these points, you should be writing your promises using the classic syntax instead. And of course, this technique is only usable in environments that support writing async functions so be aware of that if you are not transpiling your code. Discussion (1) Promises and error handling, such a tough topic to wrap my head around. While I love the simplicity of promises I do think it caused people to compromise significant performance . The previous syntax would at least encourage you to run Promise.all() or race properly because you receive simpler code in return. Async await is just too sleek not to use lmao
https://dev.to/aminnairi/quick-prototyping-playing-with-promises-in-one-line-d3c
CC-MAIN-2021-25
refinedweb
932
70.94
In common/jk_shm.c and in iis/jk_isapi_plugin.c we create objects in the Windows "Global" name space. Those are used as names for mutexes and for shared memory. Creating global objects needs the privilege SeCreateGlobalPrivilege. It did not work for me when using a Windows binary of mod_jk inside httpd not running as a service. I has to add "run as administator" to the binary although the user already was in the administrator group. I question the use of the global namespace. I can't see, why local should not be enough plus local would make conflicts between multiple instances less likely. Do we see any reasons, why using Local\ insted of Global\ should not work (and even be better)? Especially for IIS I don't know enough about the various operating models. I've been doing some research: Global essentially means all user sessions (including the system). Local means the current session. Local looks like the better choice to me. As a sanity check, I've changed it in my local build with no obvious issues with ISAPI. Fixed in 1.2.x for 1.2.44 onwards.
https://bz.apache.org/bugzilla/show_bug.cgi?id=58287
CC-MAIN-2022-27
refinedweb
190
68.67
01 March 2011 16:07 [Source: ICIS news] LONDON (ICIS)--The ICIS Petrochemical Index (IPEX) for March has climbed further to 336.84, the highest since September 2008. The IPEX figure saw an improvement of 5.4 % from its revised* February figure of 319.48 on firmer global chemical prices. Firmer prices resulted from higher crude values and strong demand as well as reduced outputs, mainly in Europe and the ?xml:namespace> A panic-buying attitude, triggered by the escalating political turmoil in North Africa and the This month, the European component of the index plays the leading role in the IPEX improvement, increasing by 7.0% from last month’s figure. A 1.8% weakening of the dollar exchange rate against the euro combined with higher prices have promoted the strengthening of the European component. The benzene contract saw the greatest price hike, climbing to €1,001/tonne ($1,390/tonne). The The Asian component of the index grew by 5.7%. PX prices, which climbed by $240/tonne on tight supply, had the greatest impact. Polyethylene (PE) was the only product to record a decline, by an average of $14/tonne, holding back growth of the Asian component., butadiene, polyvinyl chloride (PVC), PE, polypropylene (PP) and polystyrene (PS). The February IPEX has been revised from 318.74 to 319.48, following incorporation of the ($1 = €0.72) *As of July 2010, the index has been revised retrospectively to replace latest available contract prices at the time of publication that had previously been used in the data series with actual settled contract prices. This has had the effect of moving the derived IPEX index from an estimated status to an actual status. The revised historical IPEX data is available from ICIS
http://www.icis.com/Articles/2011/03/01/9439868/march-ipex-climbs-further-highest-since-september-2008.html
CC-MAIN-2015-11
refinedweb
292
66.13
if code based on certain conditions. Contents - 1 Prerequisites - 2 The Video: if-else if-else statements in Java - 3 The Program Used in the Video - 4 Exercise to practice if-else if-else statements - 5 Notifications - 6 Transcription of the Audio of the Video Prerequisites Please make sure to go over the previous lecture on Boolean Variables and Relational Operators, if you haven’t already done so. The last lecture will give a good idea on Conditions, which is the basis for the current video. The Video: if-else if-else statements in Java The video explains if-else if-else statements in Java. It uses a simple example to explain the concept. Overall, the video will help beginners to start practicing if-else if-else statements. The Program Used in the Video The program demonstrated in the video is provided below. Please save the code in a file named ConditionTest.java if you want to use the code directly. We suggest that you type the code while you watch the video. When you type the code, you practically develope an understanding regarding the syntax you type. import java.util.Scanner; class ConditionTest{ public static void main(String[] args){ int x; int y; Scanner scan = new Scanner(System.in); System.out.println("Enter the 1st number"); x=scan.nextInt(); System.out.println("Enter the 2nd number"); y=scan.nextInt(); if (x>y){ System.out.println("x is greater"); }else if (x<y){ System.out.println("x is smaller"); }else{ System.out.println("Equal numbers"); } } } Exercise to practice if-else if-else statements. Please do not hesitate to send us your code via the comments section below. We will be happy to provide you feedback. Notifications Subscribe to our YouTube Channel to receive notifications when we post YouTube videos. Transcription of the Audio of the Video From the previous video, you are familiar with comparisons and Boolean variables, we are now moving to what we can do with the comparisons. Practically, we can use comparisons for decision making in the program. That is, a part of our code will be executed if certain conditions are met; otherwise, another part of the code will be executed. Starting of the code I am starting my code where I will show how we can use if-else statements. The name of the class is ConditionTest; Of course the file name is ConditionTest.java. I have already written the main method, inside which I will write my code. I am declaring two integer variables, x and y. the variable scan is my Scanner object, using which I will get input from the user. I have written my code to get input for the first number x, and the second number y. The first if statement At this point, what I will do is, I will print a message if x and y have a certain relationship. The statement is written using “if” then in parentheses state the comparison. Within the parentheses, you must have a Boolean value. Notice that the comparison x>y results in a boolean value, either true or false. Again, at first write if, then within parentheses provide the condition or comparison that results in a Boolean value. After the parentheses provide the scope of the code that should be executed if the condition in the parentheses results in “true”. You define the scope using a left curly bracket and a right curly bracket. Anything you write inside the curly brackets will be executed, only if the condition you have provided within the “if” statement results in true. Inside the scope of the if statement I have written, I am writing a System.out.println statement. If x is greater than y, then the System.out.println will print “x is greater than y.” Save, compile, and run Let us save the file, compile it and run it. If the user enters a larger number for x than y, then the program should print “x is greater than y”, otherwise the program will print nothing after the user enters the numbers. The user enters 10 for x and 5 for y. The program immediately prints “x is greater” because the first number the user provided is greater than the second number. Let us run the code again. The user now provides 10 as the first number and 20 as the second number. Now, the program compares x>y, which results in the comparison 10>20, which in turn results in false. Since the if statement results in false, the System.out.println is not executed. The program just ends without printing anything. Change the code to include another scope Now, if we want the program to print something when x is not greater than y, then we can create another scope, which will be executed if the if statement results in false. What we write is, “else” and then we create another scope using left and right curly brackets. You can print anything inside these curly brackets. Anything you print via a System.out.println statement will be printed on the terminal when x is NOT greater than y. Let us just print “x is not greater.” Save, compile, and run the code Let us save the file, compile it, and then run it. Now, notice that for the first number 10, and the second number 20, the program outputs ” x is not greater.” Earlier, the program was not printing anything for 10 and 20. Running the program again with 20 and 10. Now the program is saying “x is greater.” That is if the first number if greater than the second number, the program says “x is greater”, otherwise the program says “x is not greater.” What happens if you have two equal numbers Now, what will happen if the user provides two equal numbers, say 10 and 10? Based on the code we have, the program will say that x is not greater. Notice that in the code, the if statement will result in false because x is not greater than y. Therefore, the first System.out.println will not be executed. The execution will go to the else part and execute the System.out.println of the scope of the else, which is “x is not greater.” What if we want to say something different when x and y have the same value? Practically, we have to include a scope which will be executed when x is equal to y. In the code, currently, we have if x is greater than y, then do something, otherwise, do another thing. The otherwise part executes only when x is smaller than or equal to y. We will separate the smaller than part and the equal part. In the else part, we will include another if statement, with a condition x is smaller than y. When x is smaller than y, we want the program to print “x is smaller”. Save this code, compile, and run the program. When the user puts 10 as the first number and 20 as the second number, the program outputs, “x is smaller.” It is the correct outcome. When the user enters 20 as the first number and 10 is the second number, the program prints “x is greater.” This is a correct outcome too. Now notice that when the user enters 10 as the first number and 10 as the second number, the program does not print anything. That is, when the user provides two equal numbers, the program does not go to any of the if scopes. “The equal to” situation We would like to see output for “the equal” situation too. Notice that the first if statement handles the situation with x is greater than y. The second if statement, that is with else,handles the “x is smaller than y” situation. The only situation left is the “x is equal to y” situation. Therefore, we can simply add an “else” to handle the scope of “x is equal to y.” Inside the scope of “else”, we write “equal numbers,” within System.out.println. We have now written a program that takes two numbers, x and y, from the user and gives an idea of which number is larger, or smaller, or if they are equal. Let us save the file, compile the code, and run the program. Notice that for equal numbers, the program now outputs “Equal numbers.” The general structure of if-else if-else statements [Show the following on screen] if (condition 1) { ------------ } else if (condition 2) { ------------ } else if (condition 3) { ------------ } ------------ ------------ } else if (condition n) { ------------ } else { ------------ } [End of — Show the following on screen] Here is the general structure of “if then else” statements. The first “if” statement is straightforward. If more “if” statements are required in a sequence, they must be preceded by an “else”. You can write as many else if conditions as you need. You may end the if-then-else sequence with just an “else”. The last “else” will cover all situations that are not covered by all the if and else if statements you have in the sequence. This overall sequence is called if-then-else statements. One thing I should mention is that, each scope under an “if” statement or an “else if” statement or an “else” statement may have many lines of code depending the problem the programmer is trying to solve. In our example, we just had a System.out.println statement within each scope. Once a condition of the sequence is satisfied, the corresponding scope is executed. Nothing else will execute. The purpose of if-then-else sequence is to execute only one scope. Conclusion background. Please start from the beginning of this lecture series if you are entirely a new learner. Thank you very much for watching the video.
https://computing4all.com/if-else-if-else-in-java/
CC-MAIN-2022-40
refinedweb
1,639
73.68
>>. 15 thoughts on “SparkFun stencil and solder paste class notes” why exactly must you learn it hands-on? i learned it by reading a few websites on the matter, and then trying it once… thats all it takes; its not that difficult, especially compared to the alternative of soldering surface mount components by hand (although hot air rework isn’t bad) ‘i learned it by reading a few websites on the matter, and then trying it once…’ um, if that doesn’t count as hands-on, what does? stuff like this makes me wish that i lived in america. you guys seem to have so many open-to-the-public classes, workshops and stuff available compared to over here in the UK. whatever people say about your country, at least people still have a desire to build things! I think the “trying it once” part is just doing it, not “learning hands on.” All his “learning” was done by reading the websites. @roboguy… ‘greed. Learning is figuring out it exists and that you do it kinda like this… Doing it is just doing it. That’s like saying a guy learned to drive a car hands on by reading the internet then just getting in and driving it. Hands on is a class where the first day they put you in the car and say, “Drive and I’ll correct you when you screw up.” I am jealous of the folks in close proximity to these classes! not only would it be awesome to learn new techniques, but to actively discuss them with humans in a face to face environment? priceless! The internet might be good for some things, but humans still have to interact on a personal level if we want to stay humans. Don’t make me get the gom jabbar!! Soldering surface mount parts is NOT bad if you have the right tools. Most guys are trying to half arse it with their radio shack special Club iron. you gotta get a good weller blade iron, micropencil and a set of hot tweesers. hot air reflow is good for stripping boards but I prefer a IR rework station. Snagged all I need for SMD work at Dayton Hamvention last year for nearly $100.00 total. also get a good soldering microscope. That helps a LOT when you start going to the ultra-tiny SMD components. I should pick up a basics kit and start learning some SMD skills. Hackaday you still rule. Solder stenciling is a great idea but has its drawbacks. You really don’t need a class for this if you have any experience soldering with paste. If not, buy some and learn. The problem with stenciling paste is that if you are only doing one or two chips at a time, why hassle with stenciling since a nice soldering iron will do the same? The stencils cost money ($99 I believe), the paste is expensive (~$50) and goes bad after a few months (even in the fridge). If you are doing a multiple part board stuff then by the time you hand place all the components you will find that the paste has dried out and does not reflow well or at all. The only way I consider using paste stencils is with a pick and place machine or if you have a big panel of boards with only a few parts on each. I’ve stuffed plenty of 100+ component boards with all 0402 and QFN parts using a soldering iron without trouble. really like this place, everyday a new invention @rob: Okay, you didn’t read the tutorial. They’re using a Pololu stencil () which is much cheaper. If you have access to a laser, you can make your own. And you can get 50g of solder paste for under $4 (). I have some and it works great. @fartface I agree that hand-soldering is preferable for 1 or 2 boards, but if you ever plan on trying your hand at 20+ circuit boards, a large stencil is the way to go. solder paste will easily last months in a not-hot environment (e.g. room temperature) the reason the manufacturers have such stringent temperature requirements and expiration dates is because if a large batch of solder paste goes bad and ruins a large manufacturing run, someone is out of a lot of money! for hobbiest purposes, don’t worry about keeping it cold or following the expiration date Where do you get the stencils? @Billy – I’ve had solder paste thicken up on me after a few months. I have had good luck ‘revitalizing’ it by mixing it with either a bit of isopropol alcohol (which dries out quickly on the pcb) or some liquid flux, which works great. Now if I could get a good, cheap, easy way to cut stencils, I’d be thrilled.
http://hackaday.com/2009/02/17/sparkfun-stencil-and-solder-paste-class-notes/?like=1&source=post_flair&_wpnonce=04d8dffccf
CC-MAIN-2015-35
refinedweb
815
78.18
Over the past year, JetBrains Rider has become the primary IDE for many .NET developers. Many of our users have been asking us about how they can develop and build their applications without having Visual Studio 2017 installed. The answer is simple on macOS and on Linux, where Mono can be installed. And for .NET Core projects, all we need is the .NET Core SDK which exists for Windows, macOS and Linux. Things get a bit more interesting when developing and building apps for the full .NET Framework on Windows… Rider will use the tools that are available after installing the Microsoft Build Tools 2017, but these come with one caveat in their license agreement: a validly licensed copy of Visual Studio is required. Since all we need from the build tools is MSBuild, which is MIT-licensed, we are providing a JetBrains redistributable of MSBuild that can be used freely. Once downloaded and extracted on our machine, we can configure Rider to use it. From Rider’s settings, under Build, Execution, Deployment | Toolset and Build, then Use MSBuild version, we can specify the Custom MSBuild executable we just extracted. Our redistributable of MSBuild is built from our GitHub fork of the official MSBuild repository. We’re not planning on creating a custom MSBuild version – we just want to provide an MIT-licensed build. In case you have any PR’s, head over to the original repository by Microsoft. Note that our redistributable excludes some of the proprietary targets files, such as Microsoft.WebApplication.targets. The Mono project does have a stub that could help here. In summary, to use Rider to develop full .NET framework applications on Windows without the need to have Visual Studio installed: - Download and extract the JetBrains redistributable of MSBuild - Download and install Microsoft .NET Framework Developer Pack 4.5.1 or later - Configure Rider to use a custom MSBuild executable - For any other application types, check the list of prerequisites for using Rider under Windows without Visual Studio Download Rider now and give it a try with our redistributable of MSBuild. We’d love to hear your feedback! Update June 15, 2018: Updated binaries to include fix for “The “GetReferenceNearestTargetFrameworkTask” task was not found.” when building app project with reference to library project if .NET Core cross-platform development workload not installed. Doesn’t the Dotnet SDK come with a MSBuild () already? This is not enough for the full .NET Framework. Okay, understandable. I’ll give it a try. Btw, will the “JetBrains redistributable of MSBuild” be included as part of the upcoming release, or do we need to install it manually by every update? We are planning to update this MSBuild frequently and having a link to it right from within Rider. That would be great! Looking forward to the upcoming release. I also hope this () gets fixed by then. Would be great to download MSBuild as we download drivers in datagrip – without leaving IDE. Maybe I’m mistaken but wouldn’t the “Community” edition of the MSBuild tools suffice (I assume that counts as a validly licensed VS)? Which link are they on? Afaik it’s not a separate download. But I would assume that since you can install & run the BuildTools while only having a VS Community “license” that should take care of the licensing problem, right? Best to read the license agreement at For OSS, what you say is true. For training and evaluation purposes as well. But anything beyond that seems to not be allowed. VS Community Edition is only for personal (non-commercial) use, OSS, small teams or education. For day job at not super-small company you can’t use VS Community Edition. Can’t it be on the Nuget? So, will make it easier to upgrade? Can I build Setup project files .vdproj files? Because that is one of the main disaveteges from MSBuild. And what about missing NuGet packages? Are they automaticily downloaded? Packages will be downloaded. For setup projects, you will need the targets for that on your machine as well. This is of interest to me as well. I’d love to be able to build setup projects using your version of MSBuild without installing VS. When you say that the targets for setup projects need to be on your machine, what do you mean exactly? Would it be possible to point us towards some documentation that might help us set this up? MSBuild uses targets files (usually containing build tasks) to be able to build certain application types. For web apps, these targets are available with a bit of searching. For several other project types (e.g. Azure Cloud Services), the targets usually ship with the SDK provided by Microsoft. And lately, may targets are appearing on NuGet.org, and can be included in your project file instead of having to rely on the targets being installed on your machine. Some examples can be seen searching NuGet for “targets” or “msbuild”. Thanks for providing the JetBrains redistributable of MSBuild! I tried switching to this version. Now the projects fail to load with the following error message: “5:40 PM Project ‘DbContextScope’ load failed: The SDK ‘Microsoft.NET.Sdk’ specified could not be found. C:\code\Backend\DbContextScope\DbContextScope.csproj at (0:0)” Content of “DbContextScope.csproj” net462 It works perfectly fine when switching back to the MSBuild provided by the Microsoft Build Tools 2017. Any ideas? Dear JetBrains moderators: Unfortunately my previous comment is incomplete as the comment box removed the xml content of my example file. I uploaded it as a gist: It would be great if you could insert this link instead of the string “net462”. Thank you! Our MSBuild will only work for regular .NET projects (not .NET Core/new project format right now) Too bad this leaves me stuck at C# 7.2 for now… Please elaborate… Well, I couldn’t select C# 7.3 in the language level for my project, 7.2 is the most recent item in the drop down. Using the latest version of Jetbrains distribution of msbuild. Thanks! I have just logged an issue for you: Feel free to upvote. You may also want to give our latest EAP a try (which should have C# 7.3 support) – I’m having a minor issue using this MSBuild version: It’s not automatically detected by NuGet (despite being on my Path, and NuGet’s auto-detection claiming to use the version from the path by default). It’s finding the version included with the .NET developer pack instead. Any workarounds, or plans to include an installer in future so that NuGet is able to detect MSBuild? Looks like you can pass the MSBuild path to many commands, e.g. for nuget.exe packyou can add the -MSBuildPathargument. Reference: Hello! I´m having some problems trying to build my solution with multiple projects inside with this Redistributable MSBuild, but not with Visual Studio one. Error: error CS0246: The type or namespace name ‘LiveJob’ could not be found (are you missing a using directive or an assembly reference?) Thanks! If that project (or another) happens to reference the web targets, compilation will fail for that project/those projects. what about mono executable? how and where I can find it? This can be downloaded from Hi! Does this redistributable contain the 32-bit version of MSBuild only? I’m trying to build a project with it and am running into an error: error MSB4216: Could not run the “GenerateResource” task because MSBuild could not create or connect to a task host with runtime “CLR4” and architecture “x64”. Please ensure that (1) the requested runtime and/or architecture are available on the machine, and (2) that the required executable “C:\SDK\MSBuild\15.0\Bin\amd64\MSBuild.exe” exists and can be run. There is no Bin\amd64 folder in the redistributable, so I’m wondering if I need to point to the 64-bit MSBuild located elsewhere or if it is truly missing. Right now we indeed only ship the 32-bit version. Feel free to open a request at Had a problem compiling solution which reads error MSB1003: Specify a project or solution file. The current working directory does not contain a project or solution file.
https://blog.jetbrains.com/dotnet/2018/04/13/introducing-jetbrains-redistributable-msbuild/?replytocom=548625
CC-MAIN-2019-51
refinedweb
1,380
66.13
![endif]--> Current version 1.2 Changes: State machines lend themselves to the solution of many computational problems. Especially of industrial and/or real time nature. Part of what makes them attractive is that once the problem is described in terms of states and transitions the solution is almost trivial. The traditional approach to state machines Statemachines are normally defined by a number of interrelated sets: There are two general description methods for state machines The implementation of statemachines differs whether they are made in hardware or software The normal hardware implementation consists of a set of registers in which the current states are coded using different coding methods and some combinational logic generating the transitions and output signals from the current state and inputs. This can be done by discrete or programmable logic Software implementation are based on either the table approach with logic or jump tables or use switch statements. Neither of which are easy to interpret. The complexity led me to a new and somewhat more relaxed idea: This function will be called repeatedly, most often from inside Arduinos loop function but other options are possible. This leads to a number of interesting features. More of this later. Demands on state functions In order for the statemachine to function efficiently the functions representing the states must fulfil a number of prerequisites: The idea of having one function for each state leads to the concept of representing the statemachine by one function pointer. Changing the state then becomes assigning this function pointer to a new state function. In order to provide a well defined mechanism for state changes, two typedefs are introduced (these must be in separate .h file): typedef void State; typedef State (*Pstate)(); Statefunctions are declared of type State with no parameters. The function pointer representing the statemachine is of type Pstate. Example 1 is a simple statemachine toggling a led using this principle. The SM library can be found HERE:Attach:SM.zip Finding myself using the concept of function pointer based statemachines over and over I decided that it was time to write a library to facilitate them. This gave also the opportunity for some useful enhancements. The SM library offers the concept of a function pointer based statemachine encapsulated in a C++ class with some added bells and whistles. These are: This is the as using the raw function pointers but encapsulated and more user friendly. Example 2 has the same function as example1 but using the SM library instead. I often found the need to do a specific set of tasks the first time a state is entered (or re-entered). Those task could be sending something over the serial port, increasing or resetting a counter, resetting a timer and so on. In order to facilitate this I created a mechanism where a state change involved to new states: Example 3 is a simple machine with a head state that sends a serial message and a body state that waits for a specified amount of time before re-entering. Creating a statemachine consists of two parts The SM constructor is overloaded. The options are SM Machine(State Initial_state);//simple machine SM Machine(State Initial_head, State Initial_body);//machine with head and body states The SM class is actually a statemachine with function pointers in itself. That’s how the head state and timer mechanisms are implemented. The syntax for calling a member function through a function pointer is a bit awkward so there is a macro to tidy it up a bit: EXEC(Machine) It is possible to have several statemachines running at once. In order to do that each machine must be called with a EXEC macro repeatedly. Remember, loops inside state functions should be avoided. Changing states is accomplished by calling the statemachines Set() function. Just like the constructor this function is overloaded: Machine.Set(State Next_state)//simple machine Machine.Set(State Next_head, State Next_body)//machine with head and body states The new state function will be invoked by the next execution of EXEC(Machine). The Set() function will normally called from within the current state function but this is not mandatory. It is fully possible to call a statemachines Set() function from elsewhere in the program, even from within another statemachine. Statemachines are very closely related to timing, at least in the field of industrial automation. Therefore I have included two timing functions: unsigned long Statetime();//returns the number of ms since the state was enterered or re-entered boolean Timeout(unsigned long Time);//returns true if specified time is exceeded Their use should be clear from the examples A machine can be stopped/suspended by calling its Finish() function. All EXEC calls return immedediately and the Finished flag is set. A machine can be restarted with a call to Restart(). This will reä-enter the last executed state. Or on can use the Set() functions to restart the machine with a specified state Two macros for edge detection are now inculded, both must have a int varialble as the second parameter. This is for storing the signal state between calls RE(signal, int state)//true if signal was 0 last call and is 1 this call FE(signal, int state)//true if signal was 1 last call and is 0 this call Simple statemachine using function pointers toggling a LED on PIN13 #include "example1.h"//tydefs for State and Pstate Pstate Exec; #define toggle 9//input pin to toggle LED #define led 13 void setup(){ pinMode(led, OUTPUT); } void loop(){ Exec(); } State S1(){ digitalWrite(led, HIGH);//LED on if(digitalRead(toggle)) Exec = S2;//wait for toggle pin to go high and change to S2 } State S2(){ if(!digitalRead(toggle)) Exec = S3;//wait for toggle pin to go low and change to S3 } State S3(){ digitalWrite(led, LOW);//LED off if(digitalRead(toggle)) Exec = S4;//wait for toggle pin to go high and change to S4 } State S4(){ if(!digitalRead(toggle)) Exec = S1;//wait for toggle pin to go low and change to S1 } Simple statemachine using the SM library, same function as example 1 #include <SM.h> SM Simple(S1);//create simple statemachine #define toggle 9//pin to toggle led on and off #define led 13 void setup(){ pinMode(led, OUTPUT); } void loop(){ EXEC(Simple);//run statemachine } State S1(){ digitalWrite(led, HIGH);//turn led on if(digitalRead(toggle)) Simple.Set(S2);//wait for toggle pin to go high and change state to S2 } State S2(){ if(!digitalRead(toggle)) Simple.Set(S3);//wait for toggle pin to go low and change state to S3 } State S3(){ digitalWrite(led, LOW);//turn led off if(digitalRead(toggle)) Simple.Set(S4);//wait for toggle pin to go high and change state to S4 } State S4(){ if(!digitalRead(toggle)) Simple.Set(S1);//wait for toggle pin to go low and change state to S1 } Machine with head and body states #include <SM.h> SM M(S1H, S1B);//create statemchine with initial head and body state functions void setup(){ Serial.begin(115200); }//setup() void loop(){ EXEC(M);//run statemachine }//loop() State S1H(){//state head function, run only once at each entry Serial.println("S1 head");//print message on each re-entry } State S1B(){//state body function run constantly if(M.Timeout(500)) M.Set(S1H, S1B);//re-enter state after 0,5s }// Concurrent states #include <SM.h> SM m1(m1s1h, m1s1b);//machine1 SM m2(m2s1h, m2s1b);//machine2 SM m3(m3s1h, m3s1b);//machine3 SM Blink(On);//machine to blink led continously static int m2c = 0;//counter for machine2 int ledPin = 13;// LED connected to digital pin 13 void setup(){ Serial.begin(115200); pinMode(ledPin, OUTPUT); // sets the digital pin as output }//Setup() void loop(){ EXEC(m1);//run machine1 EXEC(Blink);//blink led concurrently for ever }//loop() State m1s1h(){ Serial.println("Machine1:State1"); }//m1s1h() State m1s1b(){ if(m1.Timeout(300)){ m1.Set(m1s2h, m1s2b); Serial.println("chaging to 2"); }; }//m1s1b() State m1s2h(){ Serial.println("Machine1:State2:Splitting execution"); }//m1s2h() State m1s2b(){ EXEC(m2);//run machine2 EXEC(m3);//run machine3 //machines 2 & 3 now run concurrently if(m2.Finished && m3.Finished){ Serial.println("Split completed"); m1.Finish(); }; }//m1s2() State m2s1h(){ Serial.print("Machine2:State1:Count"); Serial.println(m2c++); }//m2s1h() State m2s1b(){ if(m2.Timeout(200)) m2.Set(m2s1h, m2s1b); if(m2c>10) m2.Finish(); }//m2s1b() State m3s1h(){ Serial.println("Machine3:state1"); }//m3s1h() State m3s1b(){ if(m3.Timeout(250)) m3.Set(m3s2h, m3s2b); }//m3s1b() State m3s2h(){ Serial.println("Machine3:state2"); }//m2s2h() State m3s2b(){ if(m3.Timeout(250)) m3.Set(m3s3h, m3s3b); }//m3s2b() State m3s3h(){ Serial.println("Machine3:state3"); } State m3s3b(){ if(m3.Timeout(250)) m3.Finish(); }//s3m1() State On(){ digitalWrite(ledPin, HIGH);// sets the LED on if(Blink.Timeout(400)) Blink.Set(Off); } State Off(){ digitalWrite(ledPin, LOW); // sets the LED on if(Blink.Timeout(400)) Blink.Set(On); }
http://playground.arduino.cc/Code/SMlib
CC-MAIN-2014-35
refinedweb
1,459
54.12
From Google Test to Catch If you ever met me, you’ll probably know that I’m a big believer in automated testing. Even for small projects, I tend to implement some testing early on, and for large projects I consider testing an absolute necessity. I could ramble on for quite a while as to why tests are important and you should be doing them, but that’s not the topic for today. Instead, I’m going to cover why I moved all of my unit tests from Google Test – the previous test framework I used – to Catch, and shed some light on how I did this as well. Before we start with the present, let’s take a look back at how I arrived at Google Test and why I wanted to change something in the first place. A brief history Many many moons ago this blog post got me interested into unit testing. Given I had no experience whatsoever, and as UnitTest++ looked as good as any other framework, I wrote my initial tests using that. This was sometime around 2008. In 2010, I was getting a bit frustrated with UnitTest++ as development wasn’t exactly going strong there, I was hoping for more test macros for things like string comparison, and so on. Long story short, I ended up porting all my tests to Google Test. Back in the day, Google Test was developed on Google Code, and releases did happen regularly but not too often. Which was rather good as bundling Google Test into a single file required running a separate tool (and it still does.) I ended up using Google Test for all of my tests – roughly 3000 of them total, with a bunch of fixtures. While developing, I run the unit tests on every build, so I also wrote a custom reporter so my console output would look like this: SUCCESS (11 tests, 0 ms) SUCCESS (1 tests, 0 ms) SUCCESS (23 tests 1 ms) You might wonder why the time is logged there as well: Given the tests were run on every single compilation, they better ran fast, so I always had my eye on the test times, and if something started to go slow, I could move it into a separate test suite. Over the years, this served me well, but there were a few gripes with Google Test. First of all, it was clear this project was developed by and for Google, so the direction they were going – death tests, etc. – was not exactly making my life simpler. At the same time, a new framework appeared on my radar: Catch. Enter Catch Why Catch, you may ask? For me, mostly for two reasons: - Simple setup – it’s always just a single header, no manual combining needed. - No fixtures! - More expressive matchers. The first reason should be obvious, but let me elaborate on the second one. The way Catch solves the “fixture problem” is by having sections in your code which contain the test code, and everything before that is executed once per section. Here’s a small appetizer: TEST_CASE("DateTime", "[core]") { const DateTime dt (1969, 7, 20, 20, 17, 40, 42, DateTimeReference::Utc); SECTION("GetYear") { CHECK (dt.GetYear () == 1969); } SECTION("GetMonth") { CHECK (dt.GetMonth () == 7); } // And so on } This, together with nicer matchers – no more ASSERT_EQ macros, instead, you can use a normal comparison, was enough to convince me of Catch. Now I needed a couple of things, though: - Port a couple of thousand tests, with tens of thousands of test macros from Google Test to Catch. - Implement a custom reporter for Catch. Porting As I’m a rather lazy person, and because the tests are super-uniform in format, I decided to semi-automate the conversion from Google Test to Catch. It’s probably possible to make a perfect automated tool, at least for the assertions, by building it on Clang and rewriting things, but I figured if I get 80% or so done automatically that should be still fine. On top of that, I’m porting tests, so I can easily validate if the conversion worked (as the tests still should pass.) The script is not super interesting, it does a lot of regular expression matching on the macros and then hopes for the best. While it’s probably going to explode when used in anger, it still converted the vast majority of the tests in my code. In total, it took me less than a day of typing to finish porting all my tests over. Before you ask why I’m not porting to some other framework like doctest which is supposed to be faster: In my testing, Catch is fast enough to the point that the test overhead doesn’t matter. I can easily execute 20000 assertions in less than 10 milliseconds, so “faster” is not really an argument at this point. What is interesting though is that there was a significant reduction in lines of code by moving over to Catch, most of which came from the fact that fixtures were gone, and some more code now used the SECTION macros and I could merge common code. Previously, I would often end up duplicating some small setup because it was still less typing than writing a fixture. Witch Catch, this is so simple that I ended up cleaning my tests voluntarily. To give you some idea, this is the commit for the core library: 114 files changed, 6717 insertions(+), 6885 deletions(-) (or -3%). For my geometry library, which has more setup code, the relative reduction was quite a bit higher: 36 files changed, 2342 insertions(+), 2478 deletions(-) – 5%. A couple of percent here and there might not seem too significant, but they directly translate into improved readability due to less boilerplate. There are a few corner cases where Catch just behaves differently from Google Test. Notably, a EXPECT_FLOAT_EQ with 0 needs to be translated into CHECK (a == Approx (0).margin (some_eps)) as Catch by default uses a relative epsilon, which becomes 0 when comparing to 0. The other one affects STREQ – in Catch, you need to use a matcher for this, which turns the whole test into CHECK_THAT (str, Catch::Equals ("Expected str"));. The script wil try to translate that properly but be aware that those are the cases which are most likely to fail. Terse reporter The last missing bit is the terse reporter. This got changed again for Catch2, which is the current stable release. The reporter is part of a catch-main.cpp which I compile into a static library, which then gets linked into the test executable. The terse reporter is straightforward: namespace Catch { class TerseReporter : public StreamingReporterBase<TerseReporter> { public: TerseReporter (ReporterConfig const& _config) : StreamingReporterBase (_config) { } static std::string getDescription () { return "Terse output"; } virtual void assertionStarting (AssertionInfo const&) {} virtual bool assertionEnded (AssertionStats const& stats) { if (!stats.assertionResult.succeeded ()) { const auto location = stats.assertionResult.getSourceInfo (); std::cout << location.file << "(" << location.line << ") error\n" << "\t"; switch (stats.assertionResult.getResultType ()) { case ResultWas::DidntThrowException: std::cout << "Expected exception was not thrown"; break; case ResultWas::ExpressionFailed: std::cout << "Expression is not true: " << stats.assertionResult.getExpandedExpression (); break; case ResultWas::Exception: std::cout << "Unexpected exception"; break; default: std::cout << "Test failed"; break; } std::cout << std::endl; } return true; } void sectionStarting (const SectionInfo& info) override { ++sectionNesting_; StreamingReporterBase::sectionStarting (info); } void sectionEnded (const SectionStats& stats) override { if (--sectionNesting_ == 0) { totalDuration_ += stats.durationInSeconds; } StreamingReporterBase::sectionEnded (stats); } void testRunEnded (const TestRunStats& stats) override { if (stats.totals.assertions.allPassed ()) { std::cout << "SUCCESS (" << stats.totals.testCases.total () << " tests, " << stats.totals.assertions.total () << " assertions, " << static_cast<int> (totalDuration_ * 1000) << " ms)"; } else { std::cout << "FAILURE (" << stats.totals.assertions.failed << " out of " << stats.totals.assertions.total () << " failed, " << static_cast<int> (totalDuration_ * 1000) << " ms)"; } std::cout << std::endl; StreamingReporterBase::testRunEnded (stats); } private: int sectionNesting_ = 0; double totalDuration_ = 0; }; CATCH_REGISTER_REPORTER ("terse", TerseReporter) } To select it, run the tests with -r terse, which will pick up the reporter. This will produce output like this: SUCCESS (11 tests, 18 assertions, 0 ms) SUCCESS (1 tests, 2 assertions, 0 ms) SUCCESS (23 tests, 283 assertions, 1 ms) As an added bonus, it also shows the number of test macros executed. This is mostly helpful to identify tests running through some long loops. Conclusion Was the porting worth it? Having spent some time with the new Catch tests, and after writing some more tests in it, I’m still convinced it was worth it. Catch is really simple to integrate, the tests are terse and readable, and neither compile time nor runtime performance ended up being an issue for me. 10/10 would use again!
https://anteru.net/blog/2017/from-google-test-to-catch/
CC-MAIN-2019-13
refinedweb
1,429
60.04
Code:#include <iostream> #include <iomanip> using namespace std; int main() { int cards, num, count; char value, j, k, q, t, a, J, K, Q, T, A; int total = 0; cout<<"How many cards do you have?"<<endl; cin>>cards; count=1; for (count = 1; count <= cards; count++) { if (num=='k'||'K'||'q'||'Q'||'j'||'J'||'t'||'T') { num=10; } else if (num=='a'||'A') { num=11; } cout << "Please enter the card value for card " << count <<": "<< endl; cin >> num; total=total+num; } if (total <=21 && total >= 2) { cout << "Total is "<< total << endl; } else cout<< "Bust"<<endl; return 0; } This is just a blackjack program that counts the cards. Something is wrong with my q, k, j, a, I'm trying to give q k j = 10 and ace = 11 or 1. I got the program correctly with normal numbers, but when I start to use q, k, j and a, it starts to bug out :| Any help would be appreciated, I'm a beginner and this is an exercise, I'm just a bit stuck at the moment The output should be something like this: Example 1: How many cards do you have? 2 Please enter the card values for card 0: a Please enter the card values for card 1: j Your score is 21 Example 2: How many cards do you have? 3 Please enter the card values for card 0: j Please enter the card values for card 1: k Please enter the card values for card 2: 3 BUSTED Edit: Took out the extra things on int, I had a lot of inputs when I was using the switch command, but since I just used a loop instead I took out the card1 card2 etc.
http://cboard.cprogramming.com/cplusplus-programming/141696-need-help-tweak-beginner-program-%7C.html
CC-MAIN-2016-07
refinedweb
288
60.45
waitid - wait for a child process to change state [XSI] #include <sys/wait.h>. If a child process changed state prior to the call to waitid(), waitid() shall return immediately. If more than one thread is suspended in wait() one or more of the following flags: - WEXITED - Wait for processes that have exited. - WSTOPPED - Status shall be returned for any child that has stopped upon receipt of a signal. - WCONTINUED - Status shall be returned for any child that was stopped and has been continued. - WNOHANG - Return immediately if there are no children to wait for. - WNOWAIT - Keep the process whose status is returned in infop in a waitable state. This shall not affect the state of the process; the process may be waited for again after this call completes. always be equal to SIGCHLD. If WNOHANG was specified and there are no children to wait for,. None. None. None. exec(), exit(), wait(), the Base Definitions volume of IEEE Std 1003.1-2001, <sys/wait.h> First released in Issue 4, Version 2. Moved from X/OPEN UNIX extension to BASE. The DESCRIPTION is updated for alignment with the POSIX Threads Extension. The DESCRIPTION is updated to avoid use of the term "must" for application requirements.
http://pubs.opengroup.org/onlinepubs/009604499/functions/waitid.html
crawl-003
refinedweb
205
75
***************************************** . ***************************************** So I have been using the Intel Setup and Configuration Software to manage my vPro AMT clients in my test network. I have to admit it is quite nice to have things just work when I want to setup and configure Intel vPro AMT. But how do I manage those systems? Come on – you know me…I use the Intel vPro Technology Module for PowerShell. I helped make it. So then the question becomes, how do I get a list of configured computers from the SCS Database? Well, the SCS includes a WMI interface to the data. Great! Now I just need to make a couple wmi calls. And thanks to all the built in PowerShell WMI goodness, those calls are pretty easy. All my clients are in my network subdomain domain “ent.vprodemo”. I also have an RCS server setup. My credentials I am storing in $cred, and the server’s IP address is stored in $ServerIP. So here is a sample script that gets all the AMT system Full Qualified domain names and sends them to invoke-amtgui.ps1: $computerList = @() $query = "SELECT * FROM RCS_AMT" $output = Get-WMIObject -computername $serverIP -credential $cred -namespace "root/Intel_RCS_Systems" –query $query -authentication PacketPrivacy foreach ($item in $output) { $computerList += $item.AMTfqdn } invoke-amtgui $computerList -credential $cred If doesn't have to be invoke-amtgui - you could send all the machine to invoke-amtpowermanagement just as easily. Of course, we could use the IP address as well by using the following line: $computerList += $item.AMTIPv4 Want to see what else is available? Just write-host $output. Here are the results from one of the systems: You can see the name, AD OU, AMT version, managed state, LOTs of stuff. Awesome! In my environment I am using Kerberos, so authentication is covered. But what happens if your environment uses digest credentials? Well, you can use WMI to ask for the digest admin password on a machine: $output = invoke-WMIMethod -computername $serverIP -credential $cred -Namespace "root/Intel_RCS_Systems" -class "RCS_Systems_RemoteConfigurationService" -name GetConfiguredPassword -authentication PacketPrivacy -argumentlist $FQDN, $IPAddress, $true, $UUID $output.Password The WMI interface checks with the machine by logging into it to ensure that it returns the correct password to you. So if the machine is not available you will not be able to get the password. But that is ok since you could not manage it anyways. How do you get the $UUID and $FQDN? From that WQL query we made earlier – $query = "SELECT * FROM RCS_AMT" Just make sure you grab the data you need: $FQDN = $item.AMTfqdn $uuid = $ item.name $AMTIPv4 = $ item.AMTIPv4
https://communities.intel.com/community/tech/vproexpert/blog/2012/09/21/using-powershell-to-manage-intel-clients-configured-with-the-intel-scs
CC-MAIN-2017-51
refinedweb
428
65.62
How do you get the level of a treeviewitem in WPF C#? In windows forms there is a .Level member of the treeview class but there does not seem to be one for WPF C#. Build a view model. A View model gves you greater flexibility with the treeview than you can achieve without it. Do yourself a favour, dont walk the visual tree, If a parent node is not visible, it could be virtualised away and your level (or depth) figure will be wrong. build a view model that wraps your data and knows at what level it is at. answer link one (you would add another property to your view model - level) I did it with a converter because I wanted to do it with <style> <DataTrigger Binding="{Binding Parent, RelativeSource={RelativeSource Self}, Converter={StaticResource TreeViewItemConverter}}" Value="1"> <Setter TargetName="Bd" Property="Background" Value="Yellow"/> </DataTrigger> And the converter public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((value as TreeView) != null)//level 1 return 0; var item = (value as TreeViewItem); if (item != null) // level 2 and 3 return (item.Parent as TreeViewItem)!=null ? 2 : 1; return 0; } This is particularly useful for multilevel styling in the treeview Similar Questions
http://ebanshi.cc/questions/1580938/how-do-you-get-the-level-of-a-treeviewitem-in-wpf-c
CC-MAIN-2017-09
refinedweb
205
55.03
rint - round-to-nearest integral value #include <math.h> double rint(double x); The rint() function returns the integral value (represented as a double) nearest x in the direction of the current rounding mode. The current rounding mode is implementation-dependent. If the current rounding mode rounds toward negative infinity, then rint() is identical to floor(). If the current rounding mode rounds toward positive infinity, then rint() is identical to ceil(). Upon successful completion, the rint() function returns the integer (represented as a double precision number) nearest x in the direction of the current rounding mode. When x is ±Inf, rint() returns x. If the value of x is NaN, NaN is returned and errno may be set to [EDOM]. The rint() function may fail if: - [EDOM] - The x argument is NaN. None. None. None. abs(), isnan(), <math.h>.
http://pubs.opengroup.org/onlinepubs/007908775/xsh/rint.html
CC-MAIN-2015-14
refinedweb
139
57.98
IRC log of ws-addr on 2006-03-03 Timestamps are in UTC. 07:47:52 [RRSAgent] RRSAgent has joined #ws-addr 07:47:52 [RRSAgent] logging to 07:50:25 [bob] Meeting: Web Services Addresing WG face to face meeting 07:50:38 [bob] Chair: Bob Freund 07:59:06 [bob] Agenda: 08:06:51 [pauld] pauld has joined #ws-addr 08:08:25 [dhull] dhull has joined #ws-addr 08:09:51 [TRutt] TRutt has joined #ws-addr 08:10:06 [TonyR] TonyR has joined #ws-addr 08:10:09 [hugo] hugo has joined #ws-addr 08:10:18 [TRutt] scribe:TRutt 08:10:34 [TRutt] scribe:TRutt 08:11:06 [TRutt] TOPIC:FaultCodes 08:13:08 [TRutt] Jonathan stated that Microsoft has already implemented several of the FaultCodes that we agreed to eliminate on Thursday. 08:16:09 [TRutt] Agreed to put back DestUnreachable, ActionNotSupported, and EndpointNotAvailable 08:16:36 [TRutt] Katy asked if these had to be implemented to claim conformance 08:16:59 [TRutt] Bob F stated that they do not have a MUST constraint anywhere in the spec, 08:17:12 [dorchard] dorchard has joined #ws-addr 08:20:18 [TRutt] David: Implementation of these faults are optional (for the last three we are adding back in) 08:21:08 [Jonathan] Jonathan has joined #ws-addr 08:21:26 [TRutt] Agreed to add this note to the descriptions of each of these three faults 08:22:40 [TRutt] RESOLUTION: Insert after the description of "destination unreachable" action not supported" and endpoint not availalble, the following "implementation of this fault is optional." 08:23:05 [TRutt] TOPIC: Interop Testing Report 08:23:06 [Katy] Katy has joined #ws-addr 08:23:40 [Jonathan] 08:24:49 [TRutt] Paul: we lost the asynchronous tests from SUN. The test implementations need more work. 08:25:28 [pauld] as does the report 08:25:58 [pauld] and collection of logs which are dip feeding in from various sources asynchronously 08:26:20 [TRutt] Jonathan: microsoft/IBM and IBM/microsoft, IBM/IBM, and microsoft/Microsoft are all OK. 08:26:40 [uyalcina] uyalcina has joined #ws-addr 08:27:06 [TRutt] Marc H: there could be a problem with the logs, our developers state the implementation is correct. 08:28:02 [daveo] daveo has joined #ws-addr 08:28:16 [hugo] Zakim, who's on the phone? 08:28:16 [Zakim] sorry, hugo, I don't know what conference this is 08:28:17 [Zakim] On IRC I see daveo, uyalcina, Katy, Jonathan, dorchard, hugo, TonyR, TRutt, dhull, pauld, RRSAgent, Zakim, bob 08:28:25 [hugo] Zakim, this will be WS_Addr 08:28:25 [Zakim] ok, hugo; I see WS_AddrWG(TP)3:00AM scheduled to start 28 minutes ago 08:28:31 [TRutt] Paul: we could have problems with collecting the logs, or with generation of the report. Some of the "green" boxes could be wrongly idenfitied as well. 08:28:43 [TRutt] Jonathan: I do not think we have fundamental issues. 08:29:50 [TRutt] Jonathan: the biggest risk is that we do not have 4 complete implemenations. 08:30:42 [TRutt] Glen: once we fix some of the AXIS problems, that could be fixed. 08:31:24 [TRutt] Paul: we might have 5 implemenations, but some of the features may have a different set of 4 implementations. 08:31:39 [TRutt] s/menations/mentations/ 08:32:42 [TRutt] Bob F: are there any changes which need to be made to the spec. 08:33:18 [TRutt] Paul: I do believe we have found the problems in the text already, and we have already reported those to the group. 08:33:19 [yinleng] yinleng has joined #ws-addr 08:33:37 [Zakim] WS_AddrWG(TP)3:00AM has now started 08:33:45 [Zakim] +David_Illsley 08:33:47 [Zakim] -David_Illsley 08:33:48 [Zakim] WS_AddrWG(TP)3:00AM has ended 08:33:49 [Zakim] Attendees were David_Illsley 08:34:01 [TRutt] Bob F: what remains is documentation of 4 interoperating implemtations for all of the test cases. 08:36:17 [TRutt] Bob F: would be good to have the test documentation completed by March 13 WG teleconf. 08:37:10 [TRutt] Hugo: intention to go to PR from the WG on March 13. 08:37:42 [Zakim] WS_AddrWG(TP)3:00AM has now started 08:37:50 [Zakim] +??P2 08:38:05 [yinleng] zakim, ??P2 is me 08:38:05 [Zakim] +yinleng; got it 08:38:51 [hugo] Zakim, call TP_Iles_B 08:38:51 [Zakim] ok, hugo; the call is being made 08:38:52 [Zakim] +TP_Iles_B 08:39:03 [umit] umit has joined #ws-addr 08:39:39 [Nilo] Nilo has joined #ws-addr 08:40:26 [Jonathan] q+ to close with no action 08:40:32 [TRutt] TOPIC: Closure of remaining CR Issues 08:40:46 [bob] ack jo 08:40:46 [Zakim] Jonathan, you wanted to close with no action 08:41:13 [TRutt] Bob F stated that the at risk feature for wsa:from has been stated by several groups as a feature that they have a use case for. 08:41:48 [TRutt] Paul D: none of the implementations have used this feature. 08:42:09 [umit] q+ 08:42:58 [TRutt] Paul D: My statement is incorrect. there are implementations which send wsa:From. We could add one test case to show that implemtatations can deal with it. 08:43:11 [TRutt] Marc G: since its optional we need two implementations to send it. 08:43:15 [bob] ack u 08:43:53 [dhull] q+ 08:44:32 [bob] ack dh 08:44:52 [pauld] notes that a test case could be 'don't bail on reception of a message with wsa:From' and then make sure three others interop with WSO2 08:45:04 [TRutt] Umit: I recommend that we close this issue with no change. Even though there is no explicit fallback to use of wsa:from in the behaviour text for replies, some users have found a reason to use this. 08:45:15 [bob] scribenick: TRutt 08:46:33 [TRutt] Jonathan: the spec has the field, but does not say what to do. 08:47:50 [TRutt] RESOLUTION: agreed to remove the "at risk" note from the CR text, and close the features at risk issue. 08:50:04 [TRutt] Glen stated that the axis implementation can generate the wsa:from element, and can do so for testing purposes. 08:51:11 [TRutt] Hugo: we should ensure that the complete implementations can all receive messages with all the optional features. 08:52:38 [TRutt] Paul D: we should add a test case which has wsa:from with mustUnderstand=true. 08:54:50 [bob] q? 08:55:06 [TRutt] Jugo took the action to add the new test case for wsa:from generation with mustUnderstand=true 08:55:17 [TRutt] s/Jugo/Hugo/ 08:56:55 [TRutt] TOPIC: CR2 08:59:17 [dhull] q+ 08:59:43 [TRutt] Bob F: this is a posponed issue on [Details] for wsa:ActionMismatch Subsubcode) 09:00:58 [bob] ack dh 09:03:56 [TRutt] Dave H: add text to section 2.4 of soap binding- "This invalid addressing header fault MUST/SHOULD contain a problem action fault detail. 09:05:55 [TRutt] Jonathan: I do not think we need to do this, given the existing text. 09:06:07 [TRutt] RDSOLUTION: agreed to close CR2 with no action. 09:06:21 [TRutt] s/RDSOLUTION/RESOLUTION/ 09:11:46 [Zakim] -yinleng 09:31:53 [hugo] Zakim, who's on the phone? 09:31:53 [Zakim] On the phone I see TP_Iles_B 09:31:57 [Zakim] -TP_Iles_B 09:31:58 [Zakim] WS_AddrWG(TP)3:00AM has ended 09:31:59 [Zakim] Attendees were yinleng, TP_Iles_B 09:39:39 [jeffm] jeffm has joined #ws-addr 09:39:52 [TRutt] TOPIC: Dave Hull NEW ISSUE 09:39:54 [GlenD] GlenD has joined #ws-addr 09:41:00 [anish] anish has joined #ws-addr 09:41:55 [dhull] 09:41:56 [bob] This will be cr25 09:42:53 [TRutt] tile of issue Use SOAP 1.2 properties where possible in describing SOAP 1.2 behavior. 09:43:57 [TRutt] There were no objections to accepting the proposal, as an editorial change 09:44:18 [TRutt] RESOLUTION: accept D Hull proposal for CR25 as editorial change 09:45:03 [TRutt] TOPIC: Resolution challenge for CR3 09:47:31 [TRutt] John Kemp sent concern in email 09:50:46 [TRutt] Discussion led to conclusion that the original resolution was still acceptable to WG 09:52:29 [TRutt] Jonathan: we can point to the existence of xml id exists. 09:52:55 [TRutt] Jonathan: there is no local id attribute because xml:id exists. 09:53:17 [TRutt] s/xml id exists/xml:id/ 09:54:06 [TRutt] RESOLUTION: Editor will provide additional text pointing to existence of xml:id 09:55:28 [TRutt] Bob F: we need to have someone give a response to John Kemp 09:55:51 [TRutt] Jonathan took action to prepare response to John Kemp on our reconsideration of CR3 09:57:11 [hugo] RRSAgent, where am I? 09:57:11 [RRSAgent] See 09:57:19 [hugo] RRSAgent, make log member 09:57:28 [TRutt] TOPIC: Additional issues on Core 09:57:41 [TRutt] Bob F asked if there are any additional issues on the Core spec. 09:57:50 [TRutt] There were no further issues identified. 09:58:28 [TRutt] Bob F: since we have no further issues, we have to produce the final version of the docs to review, and recommend for progression to PR. 09:58:40 [dorchard] dorchard has joined #ws-addr 09:58:42 [TRutt] Glen: when will the formal objections be reviewed and resolved. 09:59:31 [TRutt] Mark N: the director has seen the formal objections, and has not sent feedback to the WG. 09:59:56 [TRutt] Glen: what message did he send. 10:00:06 [TRutt] Marc N: the messages was "yes you can go to CR" 10:01:42 [TRutt] Hugo: until we are in recommendation, the director can say we have to resolve a particular formal objection. Officially we have to wait to see if he will assert on these objections, which he has already seen. 10:02:29 [TRutt] Bob 10:03:14 [TRutt] Bob F asked if any companies change their allignment with either of the formal objections. No company wished to change their allighment. 10:03:53 [TRutt] Bob F asked the editors when they will have documents incorporating all resolutions. 10:04:06 [TRutt] Marc H stated the documents would be ready by the end of the day. 10:05:02 [TRutt] Bob F: I ask all members to review and send any coments before March 13. The intent is to vote to progress to PR at the March 13 meeting. 10:05:13 [TonyR] s/allighment/alignment/ 10:05:33 [TRutt] Hugo: we should publish the soap 1.1 note at the same time as the PR. 10:07:00 [TRutt] Bob F: Hugo will schedule a call with the Director after we vote to go to PR. The PR should be availalbe by the end of March, give a WG desicion on March 13. 10:07:46 [TRutt] TOPIC: WSDL Doc Last Call issue LC09 10:09:04 [TRutt] s/LC01/LC109/ 10:09:16 [TRutt] s/LC09/LC109/ 10:11:33 [dhull] q+ 10:12:51 [TRutt] s/desicion/decision/ 10:13:11 [bob] ack dh 10:15:04 [TRutt] D hull: you can leave the faultTo empty if you have a replyTo present. 10:15:09 [umit] q+ 10:15:25 [TRutt] Marc H: we need to clarify "either this or that" 10:16:15 [bob] ack u 10:17:22 [TRutt] Katy: the fault endpoint may be able to be derived by different means than presence in the request 10:17:39 [anish] q+ 10:17:42 [dhull] q+ 10:18:40 [bob] ack an 10:20:07 [TRutt] discussion ensued on table 5-5 10:20:36 [bob] ack dh 10:21:06 [TRutt] Marc H : suggest comgining reply endpoint and fault endpoint rows. 10:22:56 [TRutt] Dave H: for Table 5.5, and Table 5.7 , and Table 5.2, we can change entroy for fault endpoint to Y with asterisk, with asterisk pointing to reference to section 3 of core. 10:23:13 [TRutt] Anish: I prefer the merger of the two rows into "response endpoint". 10:23:40 [TRutt] Call attention to section 3.4 of core regarding the fault endpoint semantics. 10:24:24 [TRutt] Umit: I would rather not combine the two rows, I prefer Dave H proposal. 10:25:10 [TRutt] Jonathan: concensus that one of reply endpoint or reply endpoint properties should appear in table 5.5. 10:25:27 [dhull] q+ 10:26:02 [bob] ack dh 10:26:10 [Jonathan] q+ 10:26:17 [TonyR] a/reply endpoint or reply/reply endpoint or fault/ 10:26:25 [TonyR] s/reply endpoint or reply/reply endpoint or fault/ 10:26:28 [umit] i would really like an example just like Anish. Combination of the specs need to be illustrated. 10:26:48 [bob] ack j 10:27:10 [TRutt] Dave H: it should be clarified that for robust in only the fault endpoint defaults to the reply endpoint. 10:28:53 [TRutt] RESOLUTION: LC109 - at least one of reply endpoing or fault endpoint properties should appear in table 5.5 10:29:02 [TRutt] s/endpoing/endpoint/ 10:30:21 [TRutt] s/appear in table 5.5/appear in table 5.5, with some indication of the co-constraints in the core spec/ 10:31:15 [TRutt] TOPIC: LC110 Should [fault endpoint] be prohibited in Robust in-only fault messages? 10:31:35 [anish] q+ 10:31:36 [TRutt] Jonathan: this applies to table 5.6 and 5.8. 10:31:47 [TRutt] Marc: table 5.6 was the first place it applied. 10:32:33 [Zakim] WS_AddrWG(TP)3:00AM has now started 10:32:41 [Zakim] +Mark_Little 10:32:45 [Zakim] -Mark_Little 10:32:46 [Zakim] WS_AddrWG(TP)3:00AM has ended 10:32:47 [Zakim] Attendees were Mark_Little 10:32:58 [anish] q? 10:33:01 [anish] q+ 10:33:33 [bob] ack a 10:34:35 [TonyR] q+ 10:35:46 [TRutt] Anish: what is good for reply is good for fault. We should not prohibit. 10:36:00 [bob] ack t 10:36:32 [dhull] q+ 10:36:38 [TRutt] Marc H: you canot give a fault to a fault message in soap. 10:37:07 [TRutt] Tony R: all fault messages should have this note, not just the robust meps. 10:37:17 [pauld] pauld has joined #ws-addr 10:37:38 [TRutt] Dave H stated that we should not prohibit a fault to a fault. 10:38:01 [bob] q? 10:38:08 [bob] ack d 10:38:39 [dhull] Just wondering whether it's our job to try to prohibit fault to a fault 10:38:46 [TRutt] Tony R: in 5.2.3 we do not distinguish fault. 10:38:56 [TRutt] Marc H: that is because it is an out. 10:39:08 [uyalcina] uyalcina has joined #ws-addr 10:39:16 [TRutt] RESOLUTION: LC110 agreed to be closed with no action. 10:39:39 [TRutt] TOPIC: LC111 Section 3.1.1 clarity 10:40:01 [TRutt] Bob F: this came from the WSDL 2 group. 10:40:34 [TRutt] Hugo: the proposal is " Section 3.1.1 says: 10:40:34 [TRutt] A property of the binding or endpoint named {addressing required} 10:40:34 [TRutt] of type xs:boolean 10:40:34 [TRutt] 10:40:34 [TRutt] should be phrased: 10:40:35 [TRutt] 10:40:37 [TRutt] A property {addressing required} of type xs:boolean, to the 10:40:39 [TRutt] Binding and Endpoint components 10:41:08 [TRutt] Marc H: typically you put it on one place or another, not both 10:43:42 [TRutt] RESOLUTION:LC110 resolved by accepting Hugo proposal 10:44:47 [TRutt] s/110 resolved by/111 resolved by/ 10:45:07 [TRutt] TOPIC: LC112 Three states in two 10:46:25 [TRutt]. 10:47:33 [bob] q? 10:48:05 [TRutt] Marc H: you either do or do not support addressing 10:50:38 [TRutt] Tony R; addressing required is a mandatory boolean property. 10:51:40 [TonyR] s/;/:/ 10:52:13 [TRutt] Anish: supported but not required forces a false value for "addressing required". 10:54:04 [TRutt] Glen: we could have values "none" , required, and optional 10:54:13 [Jonathan] q+ 10:54:31 [TRutt] Glen: having two values "required" and "optional" for this attribute. 10:54:45 [TRutt] Jonathan summarized on the whiteboard what we have today. 10:56:43 [TRutt] Jonathan: if using is on binding ti goes to both binding and endpoint. If using is on endpoint, it does not go to binding. 10:59:01 [TRutt] Anish: I like having the values "required" and "optional" string enumerations. 10:59:41 [bob] ack j 11:01:40 [TRutt] Jonathan: we need to clarify 3.1.1 to say what we want. I do not like calling these "required" properties. if the existence of the property depends on the syntax of "using addressing" 11:02:10 [TRutt] Tony: could be change "required" propety to "mandatory" property. 11:03:38 [TRutt] Jonathan: exisence of using addressing on binding results in the required attribute to be true in binding. 11:03:58 [TRutt] Anish: I do not understand what required means in this context. 11:09:31 [TRutt] Katy: I challenge our earlier decision to put using addressing on endpoint 11:09:46 [uyalcina] +1 to Katy 11:09:58 [anish] i see the following columns for the table: 1) what's in the syntax, 2) does the processor recognize the extension, 3) wsdl:required value, 4) property present in the component model 5) value of the property in the component 11:10:52 [anish] q+ 11:11:34 [TRutt] Jonathan: we can restrict the rules for bindings to be separate as for endpoint. 11:11:41 [bob] ack a 11:13:50 [TRutt] Anish proposed a table with 5 columns to express the semantics of using addressing to components. 11:15:30 [TRutt] Jonathan: we need to remove the word required in the text, and to have a link from binding using addressing to binding component, and another link form endpoint using addressing to endpoint component. 11:16:39 [TRutt] Group broke for lunch, to think about proper resolution for this lc issue 12:19:48 [yinleng] yinleng has left #ws-addr 12:25:29 [Jonathan] Jonathan has joined #ws-addr 12:27:47 [Jonathan] Scribe: Jonathan 12:32:53 [TonyR] TonyR has joined #ws-addr 12:34:35 [Jonathan] Topic: Doc status update 12:34:41 [Jonathan] Marc has checked in draft PR docs. 12:35:37 [uyalcina] uyalcina has joined #ws-addr 12:35:39 [Jonathan] Hugo will send a link to the snapshot to the WG. 12:36:08 [Jonathan] Topic: lc112 continued 12:36:43 [Jonathan] Bob: before lunch, Anish was thinking of a table. Jonathan was talking about a list of actions to resolve this issue. 12:37:38 [Jonathan] Jonathan: Proposal: 12:38:04 [Jonathan] ... Section 3.1.1: remove the word REQUIRED. 12:38:43 [Jonathan] ... Describe that UsingAddressing on Binding annotates Binding component, 12:38:49 [Jonathan] ... Describe that UsingAddressing on Endpoint annotates Endpoint component, 12:39:27 [Jonathan] ... Possibly note that both values must be considered to determine whether Addressing is required for a particular message. 12:41:08 [Jonathan] Anish: wsdl:required should not be used directly as the value of the property. 12:41:25 [Jonathan] ... Might want a different value set for the property. 12:41:45 [Jonathan] Glen: Would be nicer if the property existed or not, and then a separate property for the value. 12:42:09 [Jonathan] ... If wsdl:required=true the value should be "required", if wsdl:required=false or not there, the value should be "optional". 12:42:27 [marc] marc has joined #ws-addr 12:42:39 [Jonathan] Tony: I like "addressing support" with the possible values of "required", "optional", "not known"/"not supported" 12:43:04 [Jonathan] Anish: If the sytnax doesn't exist, you can still add the property. 12:43:20 [Jonathan] ... The processor doesn't understand addressing, it won't be a property in the component model. 12:43:42 [Jonathan] Jonathan: Be clear on component model - it's subtle. 12:44:16 [Jonathan] Anish: Just change the naming of the property. 12:45:05 [Jonathan] Bob: Regardless of the name, we have relationships. We need first to get relationship. 12:45:29 [Jonathan] Tony: Want to allow the property appear even when there is no UsingAddressing extension. 12:45:47 [Jonathan] Marc: Strange since you're telling people about yourself. 12:46:07 [Jonathan] Tony: Want the third property to encompass that there is no addressing support here. 12:46:25 [Jonathan] ... Not happy that absence implies it's supported. 12:47:17 [Jonathan] ... How can I describe the service as not supporting addressing?> 12:47:33 [Jonathan] Anish: We don't have such a marker. 12:47:46 [Jonathan] Katy: Send a mustUnderstand="1" and get an error back. 12:47:56 [marc] can't imagine a service ever saying wsa:addressing_support="unknown" 12:48:50 [Jonathan] Tony: Thought that was what the tri-state is about. 12:49:04 [Jonathan] Marc: It really only has two states. You either require it, or you don't. 12:49:22 [Jonathan] Glen: It says, I support, or you have to use. 12:49:47 [Jonathan] Marc: You don't have to tell I support. No new information provided. 12:50:06 [Jonathan] Anish: We have three states in the value. 12:50:11 [Jonathan] ... and presence. 12:50:29 [Jonathan] marc: But if it's not present, it's not telling you that the service requires addressing. 12:50:46 [Jonathan] Anish: Maybe the service isn't telling you but it is still required., 12:50:50 [Jonathan] (don't go there) 12:51:19 [Jonathan] Glen: Difference between supported and required, and no indication. 12:51:29 [Jonathan] ... If you understand addressing, you've gotta do it. 12:51:55 [anish] q+ 12:51:56 [Jonathan] Marc: from the services perspective, you say UA=true when it's required. 12:52:11 [Jonathan] ... when it's not, you put it in or not. 12:52:17 [Jonathan] ... doesn't matter which. 12:52:39 [Jonathan] Glen: How does that map to component model properties? Should be this addressing use property. 12:53:10 [bob] ack a 12:53:24 [Jonathan] Anish: If you require addressing, you must put UsingAddressing in the WSDL? 12:53:39 [Jonathan] Marc: Not that far, just if you require it and you want an interoperable mechanism, use this one. 12:54:17 [Jonathan] Umit: Provision in WSDL for this marker. We went through this well in WSDL. 12:55:22 [Jonathan] Marc: My proposal is equivalent to {prop}="true" or not there. "false" doesn't give you any other information. 12:55:36 [Jonathan] Glen: "false" tells you that you understood the marker at least. 12:56:08 [Jonathan] ... If you don't support WS-A in the syntax, you shouldn't support it in the component model. 12:57:18 [NiloM] NiloM has joined #ws-addr 12:57:28 [anish] q+ to ask marc how his view would look like in terms of the component model 12:57:32 [Jonathan] Jonathan: Thinks there is a difference. "False" means you can send the headers with mu and not expect a fault. 12:58:04 [Jonathan] Glen: If you see this at the WSDL processing time, I will know whether I can send those headers or not. I might want to fault if the service doesn't delcare support for WS-A. 12:58:40 [Jonathan] ... Tricky case is the optional one. We're overloading the marker to mean "process the WSDL" and "allows WS-A". 12:58:51 [Jonathan] ... Once its in the component model, you're supposed to use WS-A at that point. 13:02:17 [Jonathan] Tony: wsdl:required is different than addressing required. 13:02:43 [Jonathan] Glen: Those concepts do get confused, both in SOAP and WSDL. We've been trying to overload that. 13:02:49 [bob] ack ani 13:02:49 [Zakim] anish, you wanted to ask marc how his view would look like in terms of the component model 13:02:50 [Jonathan] Jonathan: Believe they collapse in practice. 13:03:12 [Jonathan] Anish: Spec says if you put an annotation in and say wsdl:required, it may change the meaning of the element to which it's attached. 13:03:29 [Jonathan] ... The qname we've defined means that you have to use addressing if required=true. 13:03:40 [Jonathan] ... We define the meaning of the QName. 13:04:12 [Jonathan] Glen: It says the meaning of [parent] might change when you understand [extension]. 13:05:04 [Jonathan] ... in practice it works out Ok. It's your choice to "understand" or not. 13:05:05 [marc] q+ to talk about table 3.1 13:05:20 [Jonathan] Anish: Can you translate how that translates to the component model. 13:05:29 [Jonathan] Marc: Not up on cm speak. 13:05:49 [Jonathan] Glen: If you don't understand the element you can't annotate the cm. 13:06:15 [Jonathan] Umit: Provider puts the extension in. Client's perspective it contributes to the component model. 13:06:32 [Jonathan] Glen: Choices are: understand the required extension or fault. 13:08:20 [anish] it turns out that it is not us who are getting confused about overloading wsdl:required. The wsdl spec says the following: 13:08:22 [anish] "A key purpose of an extension is to formally indicate (i.e., in a machine-processable way) that a particular feature or convention is supported or required." 13:10:04 [bob] ack marc 13:10:04 [Zakim] marc, you wanted to talk about table 3.1 13:10:11 [Jonathan] (scribe loses a bit) 13:10:50 [Jonathan] Marc: I'm willing to change my position. Spec says there are different requirements on an endpoint depending on whether they've put this in the WSDL or not. 13:11:13 [Jonathan] ... Table 3-1. Key difference is MAPs in input message. 13:11:41 [Jonathan] ... If you put it in, you have to accept addressing headers. 13:11:47 [pauld] pauld has joined #ws-addr 13:11:59 [Jonathan] ... Component model does need to reflect tri-state. 13:13:19 [Jonathan] Bob: Tri-state issue, seems discussion revolves around whether this. 13:13:35 [Jonathan] Katy: Required/supported/not-known are the states in the table. 13:14:30 [bob] q? 13:15:14 [dorchard] dorchard has joined #ws-addr 13:15:52 [Jonathan] Glen: This is a problem with WSDL, I don't know what properties there are, what good does an abstract model do? 13:19:13 [Jonathan] Jonathan: That's taken care of us by WSDL - read the Extensions part. 13:19:17 [Jonathan] Bob: What's the proposal then? 13:19:34 [Jonathan] Jonathan repeats. Essentially asking for a mapping of XML to component model. 13:20:06 [Jonathan] Hugo: I proposed a mapping originally, Marc said it duplicated a lot of things. 13:20:19 [Jonathan] ... Group said we can keep what we have. 13:20:30 [Jonathan] Jonathan: Asserts that failed to be clear enough. 13:21:02 [Jonathan] ... Would like to follow WSDL's style. 13:21:09 [Jonathan] Bob: Fundamental objections? 13:21:47 [Jonathan] Glen: Takes the WSDL required value rather than a different value. 13:21:59 [uyalcina] uyalcina has joined #ws-addr 13:22:11 [Jonathan] Anish: Call it {addressing} = "required 13:22:18 [Jonathan] ..." / "optional" 13:22:27 [Jonathan] Glen: call it {using addressing} 13:22:54 [Jonathan] Jonathan: Proposal: 13:22:54 [Jonathan] <Jonathan> ... Section 3.1.1: remove the word REQUIRED. 13:23:11 [Jonathan] ... Add mapping of XML to component model 13:23:30 [Jonathan] ... Possibly note that both properties must be consulted. 13:24:21 [Jonathan] ... Change property name to {addressing}, values "required" / "optional" 13:24:34 [Jonathan] Glen: Namespace properties? 13:26:07 [vikas] vikas has joined #ws-addr 13:26:14 [vikas] vikas has left #ws-addr 13:26:18 [Jonathan] Jonathan: Didn't namespace the core WSDL properties. No framework for doing that. 13:26:38 [Jonathan] Bob: Accept the proposal? 13:26:51 [Jonathan] Katy: Looking at 3.2.1, might be impacts there. 13:28:00 [vikas] vikas has joined #ws-addr 13:29:19 [Jonathan] Marc: Needs more editorial direction. 13:29:26 [Jonathan] Hugo: I'll draft some text. 13:30:03 [Jonathan] ACTION: Hugo to draft mapping to CM of UsingAddressing. 13:30:59 [Jonathan] RESOLUTION: Proposal (see above) accepted as resolution of lc112. 13:31:51 [Jonathan] ... and equivalent editorial changes to 3.2.1. 13:32:09 [Jonathan] ACTION 1=Hugo to draft mapping of CM to UsingAddressing and Anonymous 13:32:25 [Jonathan] Topic: lc113 Section 3.3. clarity 13:33:12 [Jonathan] ACTION 1=Hugo to draft mapping of CM to UsingAddressing and Anonymous, and Action 13:33:16 [Jonathan] 13:34:11 [Jonathan] Hugo: This section should be translated into WSDL 2.0 lingo (CM instead of XML) 13:34:51 [Jonathan] ... Also not too clear on where it is allowed, have to chase references to intersect where UsingAddressing and soap:module are both allowed. 13:35:04 [Jonathan] ... We should do the math for our readers. The intersection is the Binding component. 13:35:30 [Jonathan] Glen: Not on endpoint? 13:35:43 [Jonathan] ... Didn't we fix that at some point? 13:35:53 [Jonathan] Hugo checks. 13:36:22 [Jonathan] Glen: Need separate bindings for differnet module combinations? Too bad. 13:36:35 [Jonathan] Bob: Objections? 13:37:50 [Jonathan] Umit: UsingAddressing and soap:module have different expressive powers? 13:38:44 [Jonathan] Glen: Researching a WSDL issue, we need soap:module at endpoint level. 13:40:09 [Jonathan] Umit: Doesn't like this at the endpoint. Would rather we removed UsingAddressing at the endpoint. 13:40:34 [Jonathan] Proposal acceptable as it stands? 13:40:46 [Jonathan] s/Proposal/Bob: Proposal/ 13:41:30 [Jonathan] Umit: Need to check editorially that we don't imply UA and module are equivalent. 13:41:49 [Jonathan] Glen: Equivalent semantics, but not equivalent places you can put it. 13:42:00 [Jonathan] RESOLUTION: lc113 closed by accepting Hugo 13:42:23 [Jonathan] RESOLUTION: lc113 closed by accepting Hugo's proposal, plus editorial check that we don't imply UA and module are completely equivalent. 13:42:50 [Jonathan] Topic: lc114 Typos 13:43:05 [Jonathan] RESOLUTION: Fix typos. 13:43:26 [Jonathan] RESOLUTION: lc114 closed by fixing typos. 13:43:48 [Jonathan] Topic: lc115 13:44:43 [Jonathan] RESOLUTION: lc115 closed by accepting fix. 13:44:49 [bob] bob has joined #ws-addr 13:45:22 [Jonathan] Topic: lc116 use of wsa:ReferenceParameters 13:45:38 [Jonathan] Bob: Doesn't say how this extension affects the WSDL 2.0 CM. 13:46:43 [Jonathan] Jonathan: Let's do it. 13:46:52 [Jonathan] ... property is a list of elements. 13:47:21 [Jonathan] Anish: What about attributes on the wsa:ReferenceParameters element? Are they lost? 13:47:40 [Jonathan] ... Isn't there a type for reference parameters already? 13:49:51 [Jonathan] ... So use the same type as the [reference properties] property in 2.1 of Core. 13:50:36 [Jonathan] Umit: We discussed it, we just forgot? 13:51:23 [Jonathan] s/properties/parameters/ 13:51:53 [uyalcina] uyalcina has joined #ws-addr 13:52:10 [Jonathan] Proposal: Add a {reference parameters} property to the WSDL 2.0 component model, with the same type as the [reference parameters] property in Core 2.1 13:53:36 [Jonathan] RESOLUTION: lc116 closed with proposal above. 13:53:48 [Jonathan] Topic: Future meetings. 13:54:46 [Jonathan] Bob: Call on the 13th is the last opportunity to touch the document. Our fundamental reason for the call is to pass the document off. The meeting will last as long as it takes. 13:56:35 [Jonathan] Jonathan: suggests we require any comments to be accompanied with a complete and detailed proposal. 13:57:10 [pauld] +1 to Jonathan 13:57:13 [Jonathan] RESOLUTION: Comments must be accompanied with a detailed proposal. 13:57:50 [mnot] mnot has joined #ws-addr 13:58:42 [Jonathan] Anish: Once it goes to PR it's out of our hands. 13:59:00 [dhull] dhull has joined #ws-addr 13:59:14 [Jonathan] Hugo: It's in my hands, so small changes (e.g. editorial) can be made as a result of AC or other comments. 14:00:00 [Jonathan] Bob: Would like to hear from the test group after the meeting on tuesday, if there are issues that mean we'll slip the date we'll have to reschedule. 14:00:14 [Jonathan] ... No reason to hold the 8th call - cancelled. 14:00:37 [Jonathan] ... FTF in Cambridge, MA for May 4-5(?) by IBM. 14:01:17 [Jonathan] ... Pencil in the FTF. 14:01:41 [Jonathan] Jonathan: Thinks we'll need it. 14:01:50 [Jonathan] Bob: Don't by tickets quite yet though. 14:02:36 [Jonathan] Bob: This is your 8 week notice of the FTF. Possibility it might be cancelled though. 14:02:42 [anish] s/by/buy/ 14:03:12 [Jonathan] Ajourned... 14:03:17 [Jonathan] RRSAgent, draft minutes 14:03:17 [RRSAgent] I have made the request to generate Jonathan 14:03:49 [Jonathan] RRSAgent, set log member 14:03:56 [Jonathan] RRSAgent, draft minutes 14:03:56 [RRSAgent] I have made the request to generate Jonathan 14:05:59 [TRutt] TRutt has left #ws-addr 14:06:42 [bob] rrsagent, make logs public 14:07:06 [bob] bob has left #ws-addr 14:16:48 [Katy] Katy has left #ws-addr 14:20:22 [prasad] prasad has joined #ws-addr 14:20:32 [prasad] prasad has left #ws-addr 15:14:34 [jeffm] jeffm has joined #ws-addr 15:28:45 [Zakim] Zakim has left #ws-addr 17:18:54 [jeffm] jeffm has joined #ws-addr 18:16:26 [pauld] pauld has joined #ws-addr 18:39:39 [jeffm] jeffm has joined #ws-addr 21:16:45 [dhull] dhull has joined #ws-addr 22:24:04 [jeffm] jeffm has joined #ws-addr 23:03:13 [pauld] pauld has joined #ws-addr
http://www.w3.org/2006/03/03-ws-addr-irc
CC-MAIN-2015-40
refinedweb
5,846
71.65
Here we will learn iOS iAd in swift with example and how to use iAd in ios applications to create banner ads in swift applications with an example using Xcode. In iOS apple has introduced a platform called iAd framework which will allow app publishers to monetize their apps by placing banner ads or full ads or both into the app. In iOS, once we integrate iAd Banner and publish app in-store the Apple will review the appropriateness of app to show ads from iAd advertisers. Once our app is approved by Apple the ads will start a show in our app. By using iAd banner in iOS swift applications we can place ads at the bottom of the screen or top of the screen like as shown below. To get payments for iAds advertising that enabled in our application, we need to make settings in the iTunes Connect portal at itunesconnect.apple.com by using our Apple ID and need to enter all required tax and banking information. Now we will see how to create banner ads using iOS iAd in our swift applications iAd Integration example, we will use the most basic template “Single View Application”. To select this one, Go to the iOS section: “iAD. Go to Main.storyboard click on your ViewController and connect ViewController with Delegate by drag and drop like as shown below. Now click on Project à Go to Build Phases à Click on + button à Search for iAd à Select iAd.framework and click on Add button iAd Banner View in Filter field then drag and drop iAd Banner View into Main.storyboard ViewController like as shown below. Now we will make connection between controls and ViewController.Swift code for that click on assistant button (overlap circle) in Xcode toolbar right side corner like as shown below. To map the controls, press the Ctrl button in keyboard and drag the iAd Banner from viewcontroller and drop into ViewController.swift file like as shown below. Once we did all the settings we need to write custom code to show the banner ad in our iOS applications. Our ViewController.swift file should contain code like as shown below import UIKit import iAd class ViewController: UIViewController,ADBannerViewDelegate { @IBOutlet weak var Banner: ADBannerView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. Banner.hidden=true } func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) { Banner.hidden = false } func bannerViewDidLoadAd(banner: ADBannerView!) { Banner.hidden=false } func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool { return true } iAd integration app in swift. Once our application is ready to upload in App Store, we need to enable iAd network for the app before it is submitted and this can be achieved by using the iTunes Connect portal. Once the app is registered in iTunes Connect à Go to Manage Your Apps page à Click on Set Up iAd Network button à Click on Enable iAd Network button on the resulting page like as shown below This is how we can use iOS iAd framework to show ad banners in swift applications based on our requirements.
https://www.tutlane.com/tutorial/ios/ios-iad-to-integrate-ads
CC-MAIN-2020-40
refinedweb
522
62.38
Hello Thanks for the Info. I was able to implement the BLOG in our site. I used the existing demo templates project. But there is one issue that i am facing. In the demo templates when we add a Personal Blog Start page, and if we right click that page and if we want to add page which is blogitem, automatically the demo templates project picks up Blog Item page type and DATES and TAGS item was created beneath Blog Start Page where as in my project these are not coming. Can any one help me out Thanks Rachappa Hi Rachappa! I'm having problems with integrating the blog function in my project, i was wondering if you could be so kind as to share how you did it step-by-step? I have tried from the alloy template package and also looked at the link previous in this thread, but i would like some more hands on tips. Would be very grateful for your assistance. /Jonas I have followed the steps provided in the blog post from epinova and tried to adapt the pagetypes and other code from the Alloy templates, but when i create a new personal start page it fails to create the tags and dates pages and i get an "object referance not set to an instance of the object" and i can't figure out where or what i'm doing wrong. So the best thing for me would be some steps on how to proceed from where the blog post ended. Maybe it's time for a new part in the series on how to create an epi site from scratch on your website ;-) Thanks for some good exaples there btw! Hello Jonas, Please check the files, a) You should include the complete blog folder in ur porject. Check the pagetype of PPersonalStart for it's virtual path. Templates/Demo/Blog/Pages b) Templates/Demo/Units folder is required c) Check the web.config for the section name episerver.blo d) In web.config, check for this tag personalStartPageTypeName, If it's not set then the page might throw an exception Thanks Hi Haven't worked on this since December, but now i need to get it working. 1. I have installed the demotemplates on my site through episerver deployment center and included the blog folder and the units folder. 2. I have checked my webconfig to make sure all necessarry parts are there 3. But when i compile i get Error 109 The type or namespace name 'Workroom' does not exist in the namespace 'EPiServer.Templates.Demo' (are you missing an assembly reference?) C:\EPiServer\Sites\SandboxSite2\Templates\Demo\Units\Placeable\CreatePageBox.ascx.cs 14 32 PublicTemplates Error 110 The type or namespace name 'Forum' does not exist in the namespace 'EPiServer.Templates.Demo' (are you missing an assembly reference?) C:\EPiServer\Sites\SandboxSite2\Templates\Demo\Blog\Pages\Item.aspx.cs 27 32 PublicTemplates Hello How can i integrate/implement the Episerver Blog to our Site? Thanks Rachappa
https://world.optimizely.com/forum/legacy-forums/Episerver-CMS-6-CTP-2/Thread-Container/2010/11/Episerver-Blog/
CC-MAIN-2022-40
refinedweb
505
69.62
Hello, I am new to this forum and happy to be a new member and eager to learn from you guys! I have this code dealing with C++ stream classes and I can't seem to get it to work. It seems simple enough, I need to read contents of a file and list them in the output. Could someone please advise how I can get this to compile and run correctly on VC++.net? I have also tried this on Dev-C++ compiler and it will not work for me. I know something with the source code is wrong. Could it be that I am using "old" style and trying to use fstream.h ? Thanks in advance!!Thanks in advance!!Code: #include <iostream> #include <fstream.h> using namespace std; void main () { char ch; fstream file; char filename[20]; cout << "Enter the name of the file: " <<flush; cin >> filename; file.open(filename, ios::in); file.unsetf(ios::skipws); while (1) { file >> ch; if (file.fail()) break; cout << ch; } file.close(); }
http://cboard.cprogramming.com/cplusplus-programming/56646-help-using-cplusplus-stream-classes-printable-thread.html
CC-MAIN-2015-40
refinedweb
170
85.69
Content-type: text/html dbminit, fetch, store, delete, firstkey, nextkey, forder - Database subroutines DBM Library (libdbm.a) #include <dbm.h> typedef struct { char *dptr; int dsize; } datum; int dbminit( char *file ); datum fetch( datum key ); int store( datum key, datum content ); int delete( datum key ); datum firstkey( void ); datum nextkey( datum key ); long forder( datum key ); Specifies the database file. Specifies the key. Specifies a value associated with the key parameter. The dbminit(), fetch(), store(), delete(), firstkey(), nextkey(), and forder() functions maintain key/content pairs in a database. They are obtained with the -ldbm loader option. The dbm library is provided only for backwards compatibility, having been obsoleted by the ndbm functions in libc. See the manual page for ndbm for more information. The dbminit(), fetch(), store(), delete(), firstkey(), nextkey(), and forder() functions handle very large databases (up to a billion blocks) and access a keyed item in one or two file system access dbminit() function. At the time that dbminit() is called, the file.dir and file.pag files must exist. (An empty database is created by creating zero-length .dir and .pag files.) Once open, the data stored under a key is accessed by the fetch() function and data is placed under a key by the store() function. A key (and its associated contents) is deleted by the delete() function. A linear pass through all keys in a database may be made by use of the firstkey() and nextkey() functions. The firstkey() function returns the first key in the database. With any key, the nextkey() function returns the next key in the database. The following code traverses the database: for (key = firstkey(); key.dptr != NULL; key = nextkey(key)) Upon successful completion, the functions that return an int return 0 (zero). Otherwise, a negative number is returned. The functions that return a datum indicate errors with a null (0) dptr . Functions: ndbm(3) delim off
http://backdrift.org/man/tru64/man3/dbm.3.html
CC-MAIN-2017-22
refinedweb
316
67.04
In PR comment 187 jbeich@ writes: FreeType is disabled because iconv() detection fails which itself fails due to auto-enabled -pie. On amd64 configure appends -fpie, assuming shared libraries are built with -fPIC, but on i386 this is not required. $ cat >a.c #include <stdio.h> int main() { printf("Hello World\n"); return 0; } $ cc a.c -pie /usr/bin/ld: error: can't create dynamic relocation R_386_32 against symbol: .L.str in readonly segment; recompile object files with -fPIC >>> defined in /tmp/a-5c8390.o >>> referenced by a.c >>> /tmp/a-5c8390.o:(main) cc: error: linker command failed with exit code 1 (use -v to see invocation) > Checking for GUI ... yes > > Error: The GUI requires either FreeType or bitmap font support. > > Check "config.log" if you do not understand why it failed. > ===> Script "configure" failed unexpectedly. Adding LDFLAGS_i386+= -Wl,-z,notext to ${PORTSDIR}/multimedia/mplayer/Makefile.options fixes the build with lld and produces a (on my test setup) working binary of mplayer and mencoder. Ed: From previous discussions around the lld topic I understood that this is the preferred solution. Could you quickly confirm, then I'll commit this. Thank you. (In reply to Thomas Zander from comment #2) Yes, this is the most straightforward option and configures lld to act as ld.bfd did, so is a minimal change. Committed in r489814, see bug #214864
https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=234745
CC-MAIN-2020-16
refinedweb
229
68.57
I have a small script to have random functions available, and it works fine. But I have to load and run the script for each new Blend file that I create. I do register it, so it loads with each file (I think). Is there a way to have this little script open automatically whenever I start Blender? Is it an addon? If not, making it an addon would probably be the easiest way. No, it’s a small script I found online to add some random functions to use for drivers. I have no idea how to make it be an add-on. I know that for a new .blend file, if I want to use it, I have to open a text editor, paste it in from the text file I saved, then make sure script running is enabled in preferences. Then I have to run the script and then click “Register”. After that, it loads with the .blend file the next time I open it. It works, but would be nice to just have it always available every time I start Blender. [EDIT]: Could I just save this little script in the 2.78 startup folder, just as it’s written? Or would that create problems? Yeah, addon would be the easiest way imo. Post the code. You can save the script running in your preferences to have it always on too. It’s this script that was in a tutorial: (Note: the three lines that start with “return” are indented in the file but doesn’t show here.) Could I just save this little script in the 2.78 startup folder, just as it’s written? Or would that create problems? Anyone have any info? If it runs with no errors, you can put it in your startup folder. OK Thanks. I’ll try that. Surround your code with [noparse] and [/noparse] tags and then it’ll be shown properly. how would you even make an addon for driver functions? i just posted a question asking about that as i am having trouble getting it to work cmomoney, I put it in the startup folder, and no errors, however I still have to run the script myself from a copy, or else it doesn’t work. I tested, its working, but it may be working too soon. Try this instead: import bpy import random from bpy.app.handlers import persistent #) @persistent def add_namespace(dummy): bpy.app.driver_namespace["randf"] = randf bpy.app.driver_namespace["randi"] = randi bpy.app.driver_namespace["gauss"] = gauss bpy.app.handlers.load_post.append(add_namespace) I will try it. Thanks. Do I still need to have “autorun scripts” checked in my preferences though?
https://blenderartists.org/t/making-registered-script-permanent/681935
CC-MAIN-2022-40
refinedweb
447
85.69
You have a problem.You wrote a cross-platform mail server in C++.It runs on Windows, Linux and Mac. Well, is that a problem? No, it's cool. But now, you feel pathetic about yourself.Your manager says, "all is fine, but I want the users to edit the config file using a GUI." Yes, just a single dialog box, with a few input fields.But how to add it to your command line application? "Qt?" "No, we can't spend big cash for just a single window." "Gtk? or wxWidgets?" "No, we can't add that much bloat to our executable.""And mind it, I need it fast, 1 day, at-most". Now you feel stuck.It's itching your sole and steaming your brow. I tell you, stay cool - read on. Yes, that is the answer to your woes, embed Python.Python comes bundled with Tkinter - the lightweight, mature, cross-platform UI toolkit. You can handcraft your UI in a matter of few minutes. And it won't add much to the size of your application. I will show you how easy it is. "But one word before that, why Python?"Well, these are some of the reasons that I personally like it: Many smart people are using it in demanding systems. Some of the most celebrated Python users include: "Ok, Ok. I agree that, on its own, Python is a good language.""But I have had enough, trying to embed it.""The C API is very low-level, and it never worked as documented." Yes, I agree that the documentation on embedding Python is missing something. But remember what I said, 'I will show you an easy way.' I have written a C++ wrapper over the Python API. Just use it. You no longer need to worry about mapping Python objects to C/C++ types. You don't need to reference count objects on heap, for garbage collection. All is taken care of. Just use it. The classes that we are going to use are declared in 'pyembed.h'. Consider the following Python script: def multiply(a,b): "Finds a product, the other way round!" c = 0 for i in range(0, a): c = c + b return c The function "multiply" takes two integers as arguments and returns an integer. Let us write some code to call this function from C++. multiply #include <iostream> #include "pyembed.h" using namespace pyembed; // for brevity int main(int argc, char** argv) { try // always check for Python_exceptions { // Create an instance of the interpreter. Python py(argc, argv); // Load the test module into the interpreter py.load("test"); // value returned by python is stored here long ret = 0; // our argument list that maps string values // to their python types Arg_map args; // fill up argument strings and their types. args["10"] = Py_long; args["20"] = Py_long; // make the call py.call("multiply", args, ret); // will print 200 std::cout << ret << '\n'; return 0; } catch (Python_exception ex) { std::cout << ex.what(); } return 0; } I am not going to explain the code, as it is well commented. Our main actor here is the class "Python". It has a large variety of "call" functions, that can be used to call Python functions that return different kind of objects. The following Python types are handled as return values and mapped to C++ types: Python call PyString std::string PyLong PyInt long PyFloat double PyTuple std::vector<std::string> (typedefed as String_list) PyList PyDict std::map<std::string, std::string> (typedefed as String_map) Tuples, lists and dictionaries embedded inside other objects are returned as comma or colon delimited strings, which you further need to parse. But such values are seldom required. You can pass the following C++ types as arguments to Python functions: (Py_real) std::string char (Py_string) You can also execute arbitrary Python scripts using the "run_string" function.To execute a script file as it is, use the "run_file" function. run_string run_file Example: py.run_string("print 'Hello World from Python!'); py.run_file("test.py"); Just go through pyembed.h to get a feel of all the facilities offered by our "Python" class. The downloadable zip file contains the code of the pyembed library, along with a small C++ commandline program that demonstrates a GUI using Tkinter. Here is the command I used on Linux to compile the sample application "users.cpp": g++ -o users -I/usr/local/include/python2.4 pyembed.cpp users.cpp -L/usr/local/lib/python2.4/config -Xlinker -export-dynamic -lpython2.4 -lm -lpthread -ltk -lutil You need to change the -I and -L options to point to your Python installation folders. -I -L For compiling on Windows (or any other platform), download and install Python and link the application with the platform specific Python library. If you are using Visual C++, you may also need to link with the multi-threaded runtime library. I don't work on Windows, so this is just an imagination. Always remember to add pyembed.cpp and pyembed.h to your project. Play around with the sample code. Make changes to "adduserform.py" while the application is still running, and see if the changes are reflected immediately. Yes, you can modify the UI, without recompiling the program. You can modify it on-the-fly. This is just one of the advantages of giving your application a Python face. The py_embed library is not yet complete. But still it can be put to many useful purposes. Please send me your comments, suggestions and bug reports. Thank you for staying this long. Bye. py_embed.
http://www.codeproject.com/Articles/14192/Embedding-Python-In-Your-C-Application?fid=308728&df=10000&mpp=10&sort=Position&spc=None&select=2603738&tid=3957043
CC-MAIN-2016-18
refinedweb
925
77.03
There are some really cool features coming online in Class Designer Beta 2 - automatic layout of the diagram, ability to export diagram as an image, display collection associations, display member types, ability to auto adjust the width of the shapes, etc. I will go over the auto layout feature in this post. When I create a diagram to visualize an existing code base (source code or assembly), I expect to quickly create a default diagram of all the types. Then I usually go over the high level class structure of the project. Then I will go ahead and start removing the types that I am not interested in and drill into the details of the rest. In order to do this efficiently, I would like to have the shapes in the auto created diagram organized in some manner that I can understand. In Beta 2, selecting the “View Class Diagram” context menu on a project node in the solution explorer or a namespace node in class view will create a class diagram with shapes for all the types in the project/namespace. Types participating in inheritance relationships will be placed on the left hand side and types not participating in an inheritance relationship will be grouped according to the type (classes, interfaces, enums etc.) and placed on the right hand side. This provides me with a quick understanding of the inheritance hierarchy of the classes in the project. If I want to remove all the types not participating in inheritance, it is very easy for me to select them and remove them from the diagram. The layout algorithm is smart about the white spaces in the diagram and tries to utilize them as much as possible. The shapes are initially collapsed. I can then go and expand the types I am interested in, look at the member details. Now, this may screw up my layout. But not to worry. There will also be a "Layout Diagram" command available to layout the diagram which can be invoked on the entire diagram or on a selection. I can use that command to re-auto layout the diagram. Here is a link to a couple of diagrams (System.Xml and System.IO namespaces) auto laidout by the tool (this is before doing any manual editing). Of course, auto layout will not be able to solve all your layout issues. We have to pick and choose between providing an optimal layout versus performance and other issues. It is intended to give you a running start. You will probably end up manually placing the shapes and rerouting the lines when you are ready to publish the diagram. Yes, you can publish your diagram as images - more on that soon. Cheers, Ramesh.
http://blogs.msdn.com/b/r.ramesh/archive/2005/01/18/355658.aspx
CC-MAIN-2015-14
refinedweb
456
62.27
setrlimit(), setrlimit64() Set the limit on a system resource Synopsis: #include <sys/resource.h> int setrlimit( int resource, const struct rlimit * rlp ); int setrlimit64( int resource, const struct rlimit64 * rlp ); Since: BlackBerry 10.0.0 Arguments: - resource - The resource whose limit you want to set.() and setrlimit64() functions set the PROCMGR_AID_RLIMIT ability enabled (see procmgr_ability()) can raise a hard limit. Both hard and soft limits can be changed in a single call to setrlimit(), subject to the constraints described above. Limits may have an "infinite" value of RLIM_INFINITY. RLIM_INFINITY is a special value, and its actual numerical value doesn't represent a valid size of virtual memory or the address space. you're calling process doesn't have the required permission; see procmgr_ability(). Classification: setrlimit() is POSIX 1003.1 XSI; setrlimit64() is Large-file support Last modified: 2014-11-17 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/s/setrlimit.html
CC-MAIN-2017-09
refinedweb
156
50.84
Implement windows NTLM authentication using SSPI VERIFIED FIXED in mozilla1.4alpha Status () People (Reporter: daniel, Assigned: darin.moz) Tracking Firefox Tracking Flags (Not tracked) Details Attachments (2 attachments, 6 obsolete attachments) Bug 23679 (NTLM auth for HTTP) is an rfe for implementing crossplatform NTLM authentication, enabling mozilla to talk to MS web and proxy servers that are configured to use "windows integrated security". For the following 2 reasons, the windows implementation of this should use SSPI instead of a cross-platform solution: 1) SSPI can by used to send the credentials of the user running the browser without any user interaction. In an intranet situation (workstation and web/proxy server share the same user database) this means seamless authentication. IMHO, this is usually how windows authentication is used. I am not sure if Mozilla would be able to grab a hold of these credentials and use them for network authentication without using SSPI (I doubt it). 2) The first step of an SSPI driven authentication negotiates the authentication protocol. NTLM is but one possible outcomes. Two windows 2000 machines might choose to use MS's kerebos implementation instead of NTLM. If memory serves me, it is possible to disable NTLM altogether in a pure windows 2000+ domain, my guess is that then IIS/MS Proxy server will require kerebos instead of NTLM to authenticate the connection and the solutions proposed in the bug won't work. SSPI documentation can be found on (thanks to Jason Prell for the ptrs): *** Bug 159215 has been marked as a duplicate of this bug. *** cc NTLM is also used for other protocols like POP3, IMAP and NNTP. I guess they do LDAP authentication as well. So I suggest using SSPI in a more general way and therefor changing the bug's component accordingly to "Networking". This bug will be functionally comparable to the fix for bug 23679, but this will be a Windows-only implementation, using the built-in Microsoft tools, namely SSPI. Multiple protocols, thus just Browser/networking. Reassign. We have to assume that Microsoft won't change the API. If/when they make changes, only then does that the dodgy API become an issue. Anyone have an idea of the difficulty of this implementation, assuming the API remains the same? Assignee: darin → new-network-bugs Component: Networking: HTTP → Networking Keywords: mozilla1.2, nsbeta1 QA Contact: tever → benc I have found this helpful: Documentation: Utility: I could help implement this in VB, but I don't know if that will help since mozilla is Java. SSPI has been around since windows 95/NT4 (3.51?), the API itself is very unlikely to change. What could change is the way IIS expects the http headers to contain the SSPI generated data. I have some SSPI client code lying around. If bug 23679 comes up with a working implementation, it means the rest of netwerk can handle this type of authentication (authenticate a persistent connection instead of a individual HTTP requests). Plugging in SSPI on windows would then be a semi-trivial task. Had a brief e-mail exchange with darin@netscape.com. Bug 23679 is apparently being worked on but making a windows specific implementation is lower priority. Feel free to depend this one on bug 23679 and assign to me. I beleive this is the 'correct' way to solve this issue on the MS Windows platform. By taking advantage of the same API MS uses, you ensure maximum compatiblity. NTLMSSP is not simple, and if we can avoid having to actually deal with it at all (ie just pass blobs) then I think this is a big plus. On other platforms, I'm proposing a Samba based solution that involves an independent NTLMSSP implementation. May I ask how this depends on 23679? OK, i saw the light ;-) ... last night i hacked together a patch to get mozilla using SSPI and things mostly work. the patch i'm about to attach is by no means final. it has many serious problems, but i'm just submitting it here so people can try it out and let me know if they discover any other problems that i'm not expecting. Assignee: daniel → darin Target Milestone: --- → mozilla1.4alpha this patch is at best a hack. things that still need to be done: 1- implement auth prompt with domain field. currently, you must enter your username as "username\domain" ... this is just for testing purposes ;-) 2- try default credentials first before prompting user. 3- come up with a better way of suppressing Authorization headers on an already authenticated connection. current method is a total hack. 4- aggressively send first auth header if URL looks like it will require authentication. currently we only do NTLM auth when challenged. 5- i hacked around the problem of needing to reuse the same connection for the second auth header by delaying the second HTTP transaction until the first is finished (instead of firing it off as soon as we read the header with the challenge as is usually done). it turns out that our next transaction stands a very good chance of being sent out over the same connection that the first transaction was sent out over. so, this hack mostly works. it will probably fail if we are authenticating multiple connections at once. to get this right, i really need to tag the transactions with some extra state information and have the connection machinery check that and try to do the right thing from there. at any rate, i'm anxious to hear how this patch behaves in the real world as is :) Just one comment - in Windows, it's traditionally DOMAIN\username when entering things in a single box. It's great to see this finally moving! ok, i cleaned up the previous patch, and architecturally things are looking better. for example, i'm not sending default credentials first before prompting the user. some big things still remain to be done: 1- i haven't made any UI changes, so i took Andrew's advice and made it so that you must supply "domain\username" in the prompt dialog. if i'm lucky, maybe 2 or 3 other people will know how to enter things correctly into this prompt without reading this bug report (or digging through the release notes if i don't fix this by 1.4 alpha) :-/ 2- we continue to only send out NTLM credentials if challenged. this can mean one extra round trip, but i'd like to take the perf hit for now (i don't think it'll be huge). by doing this we avoid the problem of having to detect an already authenticated channel. yes, this shouldn't be difficult, but given the way things are organized, it is not as trivial as it should be. 3- same hack in place that depends on request order to reuse the right connection. i'm pretty sure this won't hold up. despite the remaining problems, i think this patch stands on its own. i'm going to move forward and try to land this for 1.4 alpha. i'll then try to clean up the remaining issues (especially the UI) in a subsequent patch. Attachment #116584 - Attachment is obsolete: true Comment on attachment 116892 [details] [diff] [review] phase 1 patch bbaetz: can you please review this. at least from a design point of view. nsIHttpAuthenticator needed to be seriously wacked. thx! The UI shouldn't be a big deal at all. The 3rd 'Domain:' field is actually used when invoking 'Integrated Windows Authentication'. Anyone who is using a domain account that is using Windows XP with IE 6 or any version of Windows with NS (any version) will have to enter the 'Domain\Username'. The 3rd 'Domain:' field only appears in pre-Windows XP clients if the 'Integrated Windows Authentication' is enabled as an authentication method in IIS. You shouldn't need to worry about the UI if you do not want to. :) Comment on attachment 116892 [details] [diff] [review] phase 1 patch >Index: public/nsIHttpAuthenticator.idl How would an ASCII-art state diagram look? It may be too complex, bu if not, it would be good to add here >Index: src/nsHttpAuthCache.cpp > >+static inline void >+GetAuthKey(const char *host, PRInt32 port, nsCString &key) >+{ > >+ key.Assign(nsDependentCString(host) + nsPrintfCString(":%d", port)); nsDependentCString(host) + NS_LITERAL_CSTRING(":") + <Something>(port) I don't know what the <something> is - prdtoa, perhaps? Save on the :%d parsing each time. I skipped over the rest, though - I don't have time, and can't test it anyway. >Index: src/nsHttpNTLMAuth.cpp >@@ -0,0 +1,364 @@ >+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ >+/* ***** BEGIN LICENSE BLOCK ***** >+ * Version: NPL 1.1/GPL 2.0/LGPL 2.1 New files should be MPL-tru-licensed. finally got a hold of a copy of MS Proxy to test this on, and there are definitely some issues to be ironed out. I don't understand, this is just SSPI or cross-platform NTLM module? How about bug 23679 comment 161? I would like to test this patch but am not sure how to implement it. I am currently developing an ASP intranet site that uses "windows intergrated security" please advise... Thanks, Dan > I ... made it so that you must supply "domain\username" in the prompt dialog. You mean there's no default for the domain? Trust Microsoft to make things difficult :-/ Summary: Implement windows authentication using SSPI → Implement windows NTLM authentication using SSPI ok, this patch seems to pass all my stress tests. it's is really ugly still, and needs some major cleanup... so no reviewing yet ;-) but, if someone wants to try out this patch, this is the one to test. Attachment #116892 - Attachment is obsolete: true oh fun! so i submitted that last patch via a NTLM proxy, and i noticed that it POSTed the entire patch twice to the proxy server. the first POST request was rejected with a 407, but the second POST request succeeded (and was passed on to bugzilla). we have the same problem with Basic and Digest auth... we so need to implement the HTTP/1.1 "expect 100 continue" method of uploading. Status: NEW → ASSIGNED I just downloaded the nightly, and I guess your patch was in it... Anyway, I can now pass through our proxy which before I could not, so the patch seems to be working... Thanks... I can now finally get back to my favorite browser :-) WinXP, build 2003031714 no, the patch isn't checked into the tree ! cleaned up a bit. addressed bbaetz's review comment. ready for more reviews. Attachment #117179 - Attachment is obsolete: true Comment on attachment 117630 [details] [diff] [review] v1.2 patch I am about 1/2 way done. Do we warn the user before we send the response to the auth request? Sending the username, domain name, and workgroup in the clear to anyone who asks seans like it should have a alert dialog. i would wait a milestone before tagging the nsIHttpAuthenticator as UNDER_REVIEW. In the comments of nsIHttpAuthenticator, you should make it explict who is going to be prompting the user. We should build this feature into a configurable build option: +ifeq ($(OS_ARCH),WINNT) +CPPSRCS += \ + nsHttpNTLMAuth.cpp \ + $(NULL) +endif Make it so, or drop the comment. :-) +#define NS_HTTP_STICKY_CONNECTION (1<<2) +// XXX bah! this name could be better :( I really don't like this procedure. It returns TRUE if i pass a="liar", b=nsnull. +StrEquivalent(const PRUnichar *a, const PRUnichar *b) instead of using calloc, just assign a null after PL_Base64Encode returns + // use calloc, since PL_Base64Encode does not null terminate. Fix your copyright dates. static void ParseUserDomain(PRUnichar *buf, const PRUnichar **user, const PRUnichar **domain) if buf is ever null, ParseUserDomain will crash. I think that the result of PromptUsernameAndPassword could get you into this condition Maybe you should explain this where you got the numbers :-) : + // decode into the input secbuffer + ib.BufferType = SECBUFFER_TOKEN; + ib.cbBuffer = (len * 3)/4; Why the changes from PRPackedBool to PRUint32 - PRPackedBool mConnected; - PRPackedBool mHaveStatusLine; - PRPackedBool mHaveAllHeaders; - PRPackedBool mTransactionDone; - PRPackedBool mResponseIsComplete; // == mTransactionDone && NS_SUCCEEDED(mStatus) ? - PRPackedBool mDidContentStart; - PRPackedBool mNoContent; // expecting an empty entity body? - PRPackedBool mReceivedData; - PRPackedBool mDestroying; + // state flags + PRUint32 mClosed : 1; + PRUint32 mDestroying : 1; + PRUint32 mConnected : 1; + PRUint32 mHaveStatusLine : 1; + PRUint32 mHaveAllHeaders : 1; + PRUint32 mTransactionDone : 1; + PRUint32 mResponseIsComplete : 1; + PRUint32 mDidContentStart : 1; + PRUint32 mNoContent : 1; // expecting an empty entity body + PRUint32 mReceivedData : 1; + PRUint32 mStatusEventPending : 1; Comment on attachment 117630 [details] [diff] [review] v1.2 patch +static PRBool +StrEquivalent(const PRUnichar *a, const PRUnichar *b) +{ + if (a && b) + return nsCRT::strcmp(a, b) == 0; + + if (a && a[0] == '\0') + return PR_TRUE; + + if (b && b[0] == '\0') + return PR_TRUE; + + return PR_FALSE; +} + wait, doesn't that mean that "foo" and "" are equivalent? maybe you meant something like if (a && b && a[0] == b[0] == '\0') return PR_TRUE? I'm looking at the AuthCache stuff now, then onto NTLM Comment on attachment 117630 [details] [diff] [review] v1.2 patch duh, shaver straightened me out on my last comment, ignore that.. The rest of this looks good though.. can we have some kind of a pref and configure definition so this can be disabled at both build time and runtime? The build time stuff is for bloat, obviously, but the runtime stuff would cover people who don't want their credentials just sent unconditionally .. I guess dougt covered that too :) you should document why StrEquivalent works, just because both dougt and I fell into the same confusion and I'd hate to see someone come along and try to 'fix' it :) (something along the lines of // a has value, so b must be null ... // b has value so a must be null ... As for the changing of GenerateCredentials to contain user/pass/domain - is there any reason you can't just pass around nsHttpAuthIdentity like you do in PromptForIdentity? or perhaps if this is going to be frozen (and thus you can't use concrete classes) could you just wrap an interface around the identity, or abstract the domain into some sort of "extra" user data so that if some other authentication mechanism shows up and wants to hijack the "domain" parameter.. almost done... Mind you, that check will also report that NULL and NULL aren't equivalent, though they're each equivalent to "". Not what I would expect. thanks for the comments guys. i've applied changes to my local tree, minus the following: 1- no fancy build changes at this time. that can happen later. anyways, this has very low footprint already. 2- dougt: i changed nsHttpTransaction to store its flags as bit fields instead of bytes. in the end this shaves off a few DWORDS. 3- alecf: good idea about COM'ifying the auth identity structure, but i think i'd prefer to wait on that. it isn't necessary at the moment. maybe something that can be done when we want to freeze this interface. mike: good catch.. thx! i'll fix that. revised per previous comments. Attachment #117630 - Attachment is obsolete: true Attachment #118353 - Flags: superreview?(alecf) Alec (#31), I think "realm" is the term used in other protocols for "domain". martin: sort of. actually, with NTLM the "domain" is something the user must enter, whereas with other protocols the "realm" is something specified in the server challenge. Comment on attachment 118353 [details] [diff] [review] v1.3 patch ok, the rest of this looks good! sr=alecf Attachment #118353 - Flags: superreview?(alecf) → superreview+ updated the patch to apply cleanly to the trunk and applied changes per the review comments. Attachment #118353 - Attachment is obsolete: true Comment on attachment 118465 [details] [diff] [review] v1.4 patch r=cathleen :-) Attachment #118465 - Flags: review+ landed everything except nsHttpNTLMAuth.{h,cpp} and nsNetModule/nsNetCID changes. these are still pending approval. this patch includes only the NTLM SSPI portion. Comment on attachment 118602 [details] [diff] [review] remaining portion of patch that didn't land before the tree closed for 1.4 alpha requesting drivers approval for 1.4 alpha. this patch has r=dougt,cathleen & sr=alecf. Attachment #118602 - Flags: approval1.4a? Comment on attachment 118602 [details] [diff] [review] remaining portion of patch that didn't land before the tree closed for 1.4 alpha >+ifeq ($(OS_ARCH),WINNT) >+CPPSRCS += \ >+ nsHttpNTLMAuth.cpp \ >+ $(NULL) >+ifdef MOZ_PSM >+REQUIRES += pipnss >+DEFINES += -DHAVE_PSM >+endif >+endif I don't think this will work in a clobber build, will it? (Given the order of client.mk, designed to prevent dependencies like this one.) >+#ifdef HAVE_PSM ... >+static PRBool >+IsFIPSEnabled() >+{ >+ nsresult rv; >+ nsCOMPtr<nsIPKCS11ModuleDB> pkcs = >+ do_GetService("@mozilla.org/security/pkcs11moduledb;1", &rv); Shouldn't this function exist even if HAVE_PSM isn't defined, so that it car return false if the service is present, to allow for a case where the security DLLs (which can, after all, be installed drop-in) are added later? I'd think you could do_GetService outside of the |#ifdef HAVE_PSM| and then QI to the right interface and test inside of it? dbaron: the issue i ran into is that if MOZ_PSM is not defined, then nsIPKCS11ModuleDB.h will not be exported! so, i do unfortunately need some kind of compile time check :( hmm... any suggestions? Comment on attachment 118602 [details] [diff] [review] remaining portion of patch that didn't land before the tree closed for 1.4 alpha a=asa (on behalf of drivers) for checkin to 1.4a. Attachment #118602 - Flags: approval1.4a? → approval1.4a+ thanks to kaie for providing better PSM hooks. Attachment #118602 - Attachment is obsolete: true Attachment #118671 - Flags: superreview?(dbaron) Attachment #118671 - Flags: review?(kaie) Comment on attachment 118671 [details] [diff] [review] updated final patch I compared this patch with the different version of the patch. r=kaie on the new portions added, and carrying forward the other reviews Attachment #118671 - Flags: review?(kaie) → review+ alright! final patch is in! marking FIXED =) Status: ASSIGNED → RESOLVED Closed: 16 years ago Resolution: --- → FIXED What about NTLM for Moz running on Linux machines, or is this a separate bugzilla issue? Manik, this is bug is about SSPI, which is a Windows 2000 API. For a Linux solution see bug #171500. It seems that winbindd is not favoured by SAMBA developers. OTOH SAMBA provides no other means for non-GPL programs. For a discussion of the general topic see bug #23679. Great work - lack of NTLM support has for ages been one great reason why corporates haven't dared consider moving away from IE. But can I just check that there's no information leakage going on? IE rightly has a preference which goes something like "authenticate only in intranet zone", which prevents NTLM credentials from leaking out to nasty sites on the Internet. Does your implementation do the same? It's not enough to rely on only authenticating when challenged, because of course the challenge can come from anywhere. mozilla will never send your NT logon credentials without first consulting you. thereafter, it will automatically send them to the same domain per the protection space matching rules defined by RFC2617. in the future, we may look into offering the default credentials using some kind of heuristic like same intranet or proxy- only, etc. Hi - Like many others I'm really excited to have this in Moz and I've been testing it out. On one site it works fine. On a second site, I get a prompt: Enter Username and password for "" at myurl.example.com In user name I have tried US\bob and then my password in the password field After hitting enter the prompt just returns over and over again. I think a clue to the issue might be that the prompt is for "". On the site that works it lists the hostname. eg/ Enter Username and password for "myurl.example.com" at myurl.example.com Am I missing something here? Just curious: does this put the machinery in place to support SPA, which is basically NTLM over SMTP, in the mail/news client? (More info at) dave: please see bug 199644#c4 rich: short answer is not really. feel free to file a bug ;-) Comment on attachment 118353 [details] [diff] [review] v1.3 patch (clearing review request on obsolete patch) VERIFIED: commercial 2003-04-29-04, Win 98. I'm in the process of moving some testing to Win2K, so I'll check the NT end soon. BTW, can someone confirm for me: Although 1.4a was released a couple days after this checkin, this was not in for the 1.4a milestone release. Status: RESOLVED → VERIFIED Re comment 52 ! (and may be 31 ?) Could there be a preference, with default to 'false' if you prefer, to let Mozilla authenticate itself without prompting the user, as MsIE does ? using mozilla 1.6b I still don't seem to be able to get out of my corporate network. Do I need to switch NTLM explicitly on, somehow? (I can get out with IE)
https://bugzilla.mozilla.org/show_bug.cgi?id=159015
CC-MAIN-2019-26
refinedweb
3,491
65.32
Opened 14 years ago Closed 13 years ago #2658 closed defect (fixed) gdal_array.BandReadAsArray() takes bogus parameter Description gdal_array.BandReadAsArray() function is defined as def BandReadAsArray( band, xoff, yoff, win_xsize, win_ysize, buf_xsize=None, buf_ysize=None, buf_obj=None ): """Pure python implementation of reading a chunk of a GDAL file into a numpy array. Used by the gdal.Band.ReadaAsArray method.""" See What is a purpose of the 'buf_obj' parameter? Actually ,it is not used at all, just created if _not_ None (losing the passed value) and then being lost itself () if buf_obj is not None: buf_obj = numpy.zeros( shape, typecode ) band_str = band.ReadRaster( xoff, yoff, win_xsize, win_ysize, buf_xsize, buf_ysize, datatype ) ar = numpy.fromstring(band_str,dtype=typecode) ar = numpy.reshape(ar, [buf_ysize,buf_xsize]) return ar Compare it with the original implementation where that parameter was used and had perfect sense (): if buf_obj is None: buf_obj = zeros( shape, typecode ) return _gdal.GDALReadRaster( band._o, xoff, yoff, win_xsize, win_ysize, buf_xsize, buf_ysize, datatype, buf_obj ) I think we should restore the original meaning of this parameter. The fix required quite a few changes in the gdal_array module (I swig'ified it, removed swig/python/extensions/numpydataset.cpp which was unused, etc..). Testing by others appreciated.
https://trac.osgeo.org/gdal/ticket/2658
CC-MAIN-2022-40
refinedweb
199
58.69
Have a look at the messages from the top… It will answer all… Regarding the CSV… After removing the space inbetween, At the time of submission we need to undo that …using data.classes… Have a look at the messages from the top… It will answer all… Regarding the CSV… After removing the space inbetween, At the time of submission we need to undo that …using data.classes… The steps are: Download data from Kaggle under “data/seedlings/” unzip train.zip under “data/seedlings/” run the script and generate the labels.csv under “data/seedlings/” (then you can use this labels.csv to count and visualize the data) Since we are going to use ImageClassifierData.from_csv, all the images need to sit under “train” folder and the sub-folders become redundant. 4. mv train/**/*.png to move files from species sub-folders to “train” folder rm -r train/**/to remove all species sub-folders Hope this help. All credit to @shubham24 to provide the codes. After five experiments (~3 hours), I submitted the best one. Kudos to the fast.ai library. I hope that put things in perspective for other people. The thread to parse the data and to create the final CSV file was super useful. Thanks to everyone that shared their insights. Maybe a late reply and you probably don’t need it anymore but still def f1(preds, targs): preds = np.argmax(preds, 1) targs = np.argmax(targs, 1) return sklearn.metrics.f1_score(targs, preds, average='micro') learn = ConvLearner.pretrained(f_model, data=data, ps=0.5,xtra_fc=[], metrics=[f1]) My targets are one-hot encoded for example [0, 0, 1, 0, 0, 0, 0, 0, 0, 0] -> class 3 This worked for me Use this csv file its has been edited… Okay. Looks like I’m struggling with this competition but seems like it’s giving me an opportunity to play with many parameters. With bs of 64 or 32 I wasn’t getting a curve which flattens or loss starts to increase so I tried bs of 16. This is how my lr curve is. This suggests me to use 1 as lr which eventually giving no better than .6 f1 score. Any guidance? I am getting the same error. I have deleted the sub-folders in train folder but i checked again to make sure. How did you fix this? I would say you have some issues with data/labels/filenames/anything_not_related_to_training. You have an incredibly low loss (lower than even @jamesrequa declared in this thread) and very low accuracy with high variance. In three epochs (one of which after unfreeze) you should get 0.9 + accuracy with 4-5 times higher loss. I redid everything and ignored f1 metrics for now and things are looking promising. Question: reduced batch size to 32 for this problem (even though GPU could accommodate) so that each epoch (gradient) gets more time to learn? Or right way to think is because we had less number of images? 10 places improvement happened because of this equation. lrs=np.array([lr/18,lr/6,lr/2]) than original lrs=np.array([lr/9,lr/3,lr]) Thank you @mmr, @ecdrid for continuous guidance. Disregard this, didn’t see that you’ve fixed it already
http://forums.fast.ai/t/kaggle-comp-plant-seedlings-classification/8212?page=5
CC-MAIN-2018-13
refinedweb
544
67.35
naming conventions: id, xtype naming conventions: id, xtype Common naming convention for xtypes? Just curious of any naming conventions being used for id's versus xtype. I had an inclination to use the same name. Code: items: [{ xtype: 'panel-login', itemId: 'loginPanel', id: 'loginPanel', region: 'north', height: 50 }, I haven't tracked down what the problem is yet, but if you use the same id and xtype name it causes problems. For example, using something like: Code: items: [{ xtype: 'loginPanel', itemId: 'loginPanel', id: 'loginPanel',//note I match the xtype region: 'north', height: 50 }, Code: Ext.getCmp('loginPanel') Ext.getCmp('loginPanel') has no propertiesMJ API Search || Ext 3: docs-demo-upgrade guide || User Extension Repository Frequently Asked Questions: FAQs Tutorial: Grid (php/mysql/json) , Application Design and Structure || Extensions: MetaGrid, MessageWindow By matching the id to the xtype you are restricted to one instance of that class... And in your example Ext.getCmp() is looking for "'loginPanel'" instead of 'loginPanel' so it won't find it. We're all using our own namespaces like good coders, but if we're sharing code in the community seems like there might be a good standard to go by so our xtypes don't get clobbered by others...or are easily intuitive, etc.MJ API Search || Ext 3: docs-demo-upgrade guide || User Extension Repository Frequently Asked Questions: FAQs Tutorial: Grid (php/mysql/json) , Application Design and Structure || Extensions: MetaGrid, MessageWindow I try to steer clear of using ids as much as possible, there are akin to global variables in my opinion. using getId() or itemId and getComponent does the job for me in virtually every scenario i come across. in regards to xtype naming, the norm seems lowercase without word separation which is a bit contradictory to the class naming convention which seems to be captial for new words. although i think i recall looking in the code and seeing that teh xtype is actually formatted to lower case so it doesn't matter if you use capitals to separate words for xtype and really xtype doesn't really have anyting to do with id, it is the name of the class / method being called - in your exmaple above it holds relavence, but when you think of a more generic type like xtype: 'panel' it does not seem so relevent
http://www.sencha.com/forum/showthread.php?46023-naming-conventions-id-xtype
CC-MAIN-2015-11
refinedweb
387
53.65
On Tue, Aug 28, 2007 at 12:42:23AM -0700, Matthew Dillon wrote: > > :Matthew Dillon wrote: > :> This is running for make obj target, before the object directory exists, > :> which means that make can't find the object directory at that point in > :> the file (because it doesn't exist yet), which means that make's idea > :> of .OBJDIR is the source directory. > : > :Oh. I wonder why it worked here then. I'll see what I can do. > : > :cheers > : simon > > I'm guessing your /usr/src is R+W. Mine is a read-only NFS mount. > > The following patch fixes the problem, but it's a bit of a hack so > I'm assuming you'll be able to come up with something cleaner. > > -Matt > Matthew Dillon > <dillon@backplane.com> Can you try this one instead? I only tested it in gnu/usr.bin/cc41 with -j5, but I believe it works for buildworld, too. - move mktooldir target into cc_tools/Makefile.tools, and make beforedepend depend on it, if ${TOOLGENDIR} doesn't exist yet. This conditional is there only to omit many 'mkdir -p' during depend stage. Cheers. Index: cc_tools/Makefile =================================================================== RCS file: /home/source/dragonfly/cvs/src/gnu/usr.bin/cc41/cc_tools/Makefile,v retrieving revision 1.2 diff -u -p -r1.2 Makefile --- cc_tools/Makefile 25 Aug 2007 15:29:28 -0000 1.2 +++ cc_tools/Makefile 19 Sep 2007 08:03:02 -0000 @@ -10,13 +10,7 @@ SUBDIR+= gcov-iov genchecksum #SUBDIR+= fini #.endif -.ORDER: mktooldir ${SUBDIR} - .include "Makefile.tools" -obj depend: mktooldir -mktooldir: - mkdir -p ${TOOLGENDIR} - clean cleandir: rm -rf ${TOOLGENDIR} Index: cc_tools/Makefile.tools =================================================================== RCS file: /home/source/dragonfly/cvs/src/gnu/usr.bin/cc41/cc_tools/Makefile.tools,v retrieving revision 1.2 diff -u -p -r1.2 Makefile.tools --- cc_tools/Makefile.tools 25 Aug 2007 15:29:28 -0000 1.2 +++ cc_tools/Makefile.tools 19 Sep 2007 08:04:36 -0000 @@ -4,3 +4,9 @@ MIC= sh ${GCCDIR}/move-if-change TOOLGENDIR= ${OTOPDIR}/cc_tools/gen .PATH: ${TOOLGENDIR} CFLAGS+= -I${TOOLGENDIR} + +.if !exists(${TOOLGENDIR}) +beforedepend: mktooldir +mktooldir: + mkdir -p ${TOOLGENDIR} +.endif
http://leaf.dragonflybsd.org/mailarchive/commits/2007-09/msg00124.html
CC-MAIN-2013-20
refinedweb
344
61.93